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 |
|---|---|---|---|---|---|
This tutorial is all about How to do Fibonacci Sequence in Java Tutorial using NetBeans IDE. In this tutorial you will learn How to use Fibonacci Sequence in Java Tutorial. Fibonacci. This tutorial uses some package called Scanner, follow all the steps below to complete this tutorial.
How to do Fibonacci Sequence in Java Tutorial using NetBeans IDE steps
The first step is to, create your project by clicking file at the top of your project and then click new project, you can name your project whatever you want. After that you need to create you class by right clicking the Source Packages and then click the New – Java Class
After that you need to import these packages
import java.util.Scanner;
above your class and
copy paste the code below:
[java]
int k, a = 1, b =1;
Scanner scanner = new Scanner(System.in);
k =0;
System.out.println(“Enter a number: “);
int number = scanner. nextInt ();
System.out.print(“1 1 “);
while(k<=number) {
k = a+ b;
if(k>=number)
break;
System.out.print(k + ” “);
a = b;
b = k;
} JOptionPane.showMessageDialog(null, e);
}
[ /java]
Then you’re done. Run your project and see if it works.
About How To Do Fibonacci Sequence.) Simple Restaurant Management System using Java
2.) Common String Methods In Java Tutorial Using Netbeans IDE | https://itsourcecode.com/free-projects/java-projects/fibonacci-sequence-in-java-tutorial/ | CC-MAIN-2021-49 | refinedweb | 218 | 58.08 |
By: Juancarlo Anez
Abstract: Like the reptile it's named after, Python squishes problems little by little.
Like the reptile it's named after, Python squishes problems little by
little.
By Juancarlo Aqez
Today I spent the whole afternoon with a snake. I've known
Python for several years now -- the oldest version of Python on my
hard drive is v. 1.3, dated March 1996 -- and I've studied and played with the
language several times. But it wasn't until today
that I actually tried to do something useful with it.
The task at hand? I wanted to lay out the articles I've written
during the last couple of months in an HTML format that is consistent with that of the rest of my Web site. My site is a
modest one, and producing the few pages of HTML in it is fairly
easy, even by hand. But doing the same formatting for a dozen or so
articles (and the many more to come), even with a WISIWYG editor,
is the kind of task that makes us lazy programmers start thinking
about a better way: writing a program.
Figuring out that the formatting of the articles had to be automated
was the easy part. Deciding on how to automate the process
was more difficult. It's not that I lacked a tool to do the job, but rather
that I didn't know the right tool to use. One of the mantras of programming is
"When in doubt, start hacking," so I did.
After some experimenting with Perl, SED, and AWK, I remembered
Python, a programming language often touted as capable of
accomplishing everything easily. I hacked my way out of this
problem with Python, and I wasn't disappointed.
Python is an interpreted, interactive, object-oriented
programming language that offers advanced features like modules,
exception handling, and classes. Python's syntax is simple, yet the
native support for first-order functions (functions you can assign
to variables or pass as parameters), lists, tuples, and maps
(associative arrays) make it quite powerful. The
compiler/interpreter and libraries are extensible, very portable,
and open source. The language has been ported to the most
diverse platforms, including several brands of Unix, Linux, MacOS,
MS-DOS, Windows, and OS/2. Python libraries support everything from
string handling to system calls to concurrency to Internet programming -- including sockets, HTTP servers and clients, and HTML
and XML parsing and formatting.
The greatest strength of Python is that it lets you think big,
yet start small. Using Python, you can expand a four- line procedural
or functional program into a full- blown web of concurrently
interacting objects. Like the snake, Python can squish a
problem, little by little.
The simplest automated scheme I could think of was to strip the
original articles of everything but the basic HTML and embed them
into a pre-formatted template, much like is done with server-side
includes. I wrote the template and placed the tag
<macro:text> right in the middle of it. I launched a
browser with the Python HTML documentation, opened a console
window, and started hacking.
To begin, I needed to open the template and target files. Python is
an eclectic language; it borrows concepts from procedural,
functional, and object-oriented programming languages.
Whatever seems to work well, Python does. According to the Python
documentation, to open a file I just needed to call the open function:
template = open("template.html")
target = open(article.html')
You don't have to declare variables in Python and you can
enclose strings in either single or double quotation marks.
Reading the files came next. Python provides an assortment of
file reading functions, the simplest of which was precisely what I
needed. In Python, the result from a call to open is
an object of File type. Calling read on
the object returns the complete contents of the file as a
string:
template_text =
template.read()
I finally opted for the more straightforward:
template = open("template.html").read()
target =
open('article.html').read()
To embed the article in the template I needed a text
substitution function, the simplest of which was to be found in the string module. As in many other languages, Python
modules are used to hold related stuff together. Module
string holds a set of useful string manipulation functions.
The one I needed was the replace method. To use a module, you
have to import it like this:
import string
After importing the module, I just had to call replace to do the substitution:
result = string.replace(template,
"<macro:text>", target)
So far, the complete Python program I had written looked like
this:
import string
template = open("template.html").read()
target = open(sys.argv[1]).read()
result = string.replace(template,
"<macro:text>", target)
print result
I saved the program to a file, then made a couple of adjustments to make it more generic.
For example, I made the program work
on any file passed as a command-line parameter by using the
functions available in the sys module. Here was the
program after the changes:
import string
template = open("template.html").read()
target = open(sys.argv[1]).read()
result = string.replace(template, "<macro:text>", target)
print result
Now I could call the program up on any of my articles from the
command line, like this:
python format.py article.html >
formatted_article.html
Alas, my initial attempt at automating the formatting of the
articles wasn't good enough. For starters, it didn't cope with
important HTML meta-information such as the
<title> tag, which should be included in every
HTML file. Nor did it deal with the specific placement and formatting
I wanted to give to the article's abstract or the author's name
(mine). But Python was still up to the task. First I edited the
articles and added the relevant meta-information on the very few
lines of each file. Then I told Python to read the files as a list
of lines instead of as a string, like this:
raw = open(filename).readlines()
Then I retrieved the information items by indexing the already
read list:
title = raw[0]
author = raw[1]
text = string.join(raw[2:])
To convert the non-field article text from a list of lines back
into a string, I used the string module's
join function, which does exactly what you'd expect. The
expression raw[2:] retrieves the items from position 2
onward, as a new list.
title = raw[0]
author = raw[1]
text = string.join(raw[2:])
I added a couple of special tags (<macro:title> and
<macro:author>) as to the template to embed the new
information at the right places. After adding the replacements for
the new tags, the code looked like this:
import string
template = open("template.html").read()
target = open(sys.argv[1]).read()
result = string.replace(template,
"<macro:text>", target)
result = string.replace(template,
"<macro:title>", title)
result = string.replace(template,
"<macro:author>", author)
print result
That was it for version 1.0: a seven-line program. The current
version of the program (which you can download
from my Web site) is 48 lines long and handles the article
abstracts, parses the article's date and formats it in two
different ways, and manages the hyperlink to the article's
original publication URL. Had I been inclined to do so, I could
have parsed the original HTML files to retrieve the chunks of
information using Python's XML and HTML parsing libraries. I could
have also used the built-in dictionary (map) type to make the text
substitutions more generic, and the regular expressions library to
get really fancy. I didn't, though, because my 48-line program already did
what I needed. I'm fond of the KISS principle, especially in Extreme Programming.
My philosophy: Do the simplest
thing that could possibly work.
Server Response from: SC1 | http://edn.embarcadero.com/article/20584 | crawl-002 | refinedweb | 1,318 | 64.2 |
Okay, we had an assignment in computer class that I have been working on for awhile but what I've got so far isn't working. It seems that it may be a compiler issue, but since I can't get to a linux compiler (what the program will be evaluated on), and since I suspect I have some other errors, I figured I would ask it here. I am not asking for you to rewrite the program, but I would like help as soon as possible, as it is due shortly.
Here's the problem:
1. Define a class called NumberSet that will be used to stored a set of integers.
Use a vector to implement the set (i.e. to store the elements).
2. Create a constructor that takes as an input paramter an array of integers for the
initial value in the set. Clearly you need to tell the constructor the size of your
array (i.e. the number of elements in the array).
3. Then write member functions to
a) (void add(int A)) add an element to the set. If the element is already in the
set, do nothing.
b) (void remove(int A)) remove an element from the set. If the set does not already contain
the element, do nothing.
c) (void clear()) clear the entire set. If the set is already empty, do nothing.
d) (int size()) return the number of element in the set. Return 0 if the set is empty.
e) (void output()) output all elements in the set properly (in any order).
4. Define your ADT class in separate files so that it can be compiled separately. To compile the project, use makefile. Put the main function in its own file separate from the ADT files. In your main
function, make sure you test all member functions (i.e. the constructor,
add, remove, size, and output).
What I have so far are the three files containing the actual code, plus the makefile, which was given to me.
File: SSApp1.cpp
#include <iostream> #include "SSassg1.h" using namespace std; int main() { int next; int horcounter = 0; int nextcounter = 0; int array_size_horizontal = 0; int *array1; cout << "Please enter the quantity of integers you will enter: "; cin >> array_size_horizontal; array1 = new int[array_size_horizontal]; cout << "Please enter " << array_size_horizontal << " integers, then press return: "; while (cin >> next) { nextcounter++; array1[horcounter++] = next; if (nextcounter > array_size_horizontal-1) { break; } } NumberSet runonce; int input1; cout << "To test the add function, please enter an integer and press return: "; cin >> input1; runonce.add(input1); int input2; cout << "To test the remove function, please enter an integer and press return: "; cin >> input2; runonce.remove(input2); cout << "Now testing size function...\n"; runonce.size(); cout << "Now testing output function...\n"; runonce.output(); cout << "The program is about to end. Now testing clear function...\n"; runonce.clear(); cout << "Goodbye\n"; return 0; }
File: SSassg1.cpp
#include <iostream> #include <vector> #include "SSassg1.h" using namespace std; NumberSet::NumberSet(int array1[]) { //Constructor for (int e=0; e < array_size_horizontal; c++ { v1.push_back(array1[e]); } delete [ ]array1; //to prevent dangling pointer; now that the values are stored in the vector, they aren't needed here } NumberSet::NumberSet( ) { //Body intentionally left empty (Default Constructor) } void NumberSet::add(int A) //need it to test for each element's value and when it gets to the end, if none are equal, then use push_back { for (int i=0; i<v1.size( ); i++) { if (v1[i] == A) { add = 1; } else { add = 2; } switch (add) { case 1: cout << "The number is already present"; for (i; i<v1.size(); i++) { } break; case 2: i++; break; default: cout << "error in prgram"; } if (v1[(v1.size()-1)] == A) { add = 1; } else { v1.push_back(A); } } } void NumberSet::remove(int A) { for (int i=0; i<v1.size( ); i++) { if (v1[i] == A); v1.erase(v1.begin() + i); i--; } } void NumberSet::clear() //clears entire vector { for (int i=0; i<v1.size ( ); i++) { v1.erase (v1.begin() + i); i--; } } int NumberSet::size() //sets variable vectorsize to the size of v1 { vectorsize = v1.size(); cout << "The size of the vector is: " << vecotrsize <<endl; } void NumberSet::output() //outputs entire vector { for (unsigned int i=0; i < v1.size( ); i++) { cout << v1[i] << " "; } cout << endl; }
File: SSassg1.h
#ifndef SSASSG1_H #define SSASSG1_H class NumberSet { public: void add (int A); //adds an element to the set if not already present void remove (int A); //removes an element from the set if present void clear(); //clears the set if there are elements present int size(); //returns the number of elements in the set void output(); //outputs all elements properly NumberSet(int array1[]); //transfers the data from an array to a vector NumberSet( ); //default constructor private: vector<int> v1; int vectorsize; } #endif //SSASSG1_H
Also, here is the makefile used to run the program:
File: SSmakefile1.cc
##TARGET: Dependencies ## Instructions SumnerApp.exe: SumnerApp.o SSassg1.o g++ SumnerApp.o SSassg1.o -o SumnerApp.exe SumnerApp.o: SumnerApp.cpp SSassg1.h g++ -c SomeApp.cpp SSassg1.o: SSassg1.cpp SSassg1.h g++ -c SSassg1.cpp clean: rm -f SumnerApp.o SSassg1.o SumnerApp.exe
I realize this is a lot, but I would really appreciate any tips anyone can give me.
Thanks a lot! | https://www.daniweb.com/programming/software-development/threads/345021/separate-compilation-of-vector-program | CC-MAIN-2017-26 | refinedweb | 866 | 65.62 |
Raspberry this Raspberry Pi Tutorial Series, you will be able to do high profile projects by yourself. Go through below tutorials:
- Getting Started with Raspberry Pi
- Raspberry Pi Configuration
- LED Blinky
- Raspberry Pi Button Interfacing
- Raspberry Pi PWM generation
- Controlling DC Motor using Raspberry Pi
- Stepper Motor Control with Raspberry Pi
In this Raspberry Pi shift register tutorial, we will Interface Shift Register with Pi. PI has 26 GPIO pins, but when we do projects like 3D printer, the output pins provided by PI are not enough. So we need more output pins, for adding more output pins to PI, we add Shift Register Chip. A Shift Register chip takes data from PI board serially and gives parallel output. The chip is of 8bit, so the chip takes 8bits from PI serially and then provides the 8bit logic output through 8 output pins.
For 8 bit shift register, we are going to use IC 74HC595. It’s a 16 PIN chip. The pin configuration of the chip is explained later below in this tutorial.
In this tutorial, we will use three PI’s GPIO pins to get eight outputs from Shift Register Chip. Remember here the PINS of chip are for output only, so we cannot connect any sensors to chip output and expect the PI to read them. LEDs are connected at the chip output to see the 8 bit data sent from PI.
We will discuss a bit about Raspberry Pi GPIO Pins before going any further,
There are 40 GPIO output pins in Raspberry Pi 2. But out of 40, only 26 GPIO pins (GPIO2 to GPIO27) can be programmed. Some of these pins perform some special functions. With special GPIO put aside, we have only 17 GPIO remaining. Each of these 17 GPIO pin can deliver a maximum of 15mAcurrent. And the sum of currents from all GPIO Pins cannot exceed 50mA. To know more about GPIO pins, go through: LED Blinking with Raspberry Pi (6)
- LED (8)
- 0.01µF capacitor
- 74HC595 IC
- Bread Board
Circuit Diagram:
Shift Register IC 74HC595:
Let’s talk about the PINS of SHIFT REGISTER we are going to use in here.
Flow of Working:
We will follow the Flow Chart and write a decimal counter program in PYTHON. When we run the program, we see LED Counting using Shift Register in Raspberry Pi.
Programming 29’ on the board is ‘GPIO5’. So we tell here either we are going to represent the pin here by ‘29’ or ‘5’.
IO.setmode (IO.BCM)
We are setting GPIO4, GPIO5 and GPIO6 pins as output
IO.setup(4,IO.OUT) IO.setup(5,IO.OUT) IO.setup(6,IO.OUT)
This command executes the loop 8 times.
for y in range(8):
While 1: is used for infinity loop. With this command the statements inside this loop will be executed continuously.
Further explanation of Program is given in Code Section Below. We have all instructions needed to send data to the SHIFT REGISTER now.
import RPi.GPIO as IO # calling for header file which helps us use GPIO’s of PI
import time # calling for time to provide delays in program
IO.setwarnings(False) # do not show any warnings
x=1
IO.setmode (IO.BCM) # programming the GPIO by BCM pin numbers. (like PIN29 as‘GPIO5’)
IO.setup(4,IO.OUT) # initialize GPIO Pins as an output.
IO.setup(5,IO.OUT)
IO.setup(6,IO.OUT)
while 1: # execute loop forever
for y in range(8): # loop for counting up 8 times
IO.output(4,1) # pull up the data pin for every bit.
time.sleep(0.1) # wait for 100ms
IO.output(5,1) # pull CLOCK pin high
time.sleep(0.1)
IO.output(5,0) # pull CLOCK pin down, to send a rising edge
IO.output(4,0) # clear the DATA pin
IO.output(6,1) # pull the SHIFT pin high to put the 8 bit data out parallel
time.sleep(0.1)
IO.output(6,0) # pull down the SHIFT pin
for y in range(8): # loop for counting up 8 times
IO.output(4,0) # clear the DATA pin, to send 0
time.sleep(0.1) # wait for 100ms
IO.output(5,1) # pull CLOCK pin high
time.sleep(0.1)
IO.output(5,0) # pull CLOCK pin down, to send a rising edge
IO.output(4,0) # keep the DATA bit low to keep the countdown
IO.output(6,1) # pull the SHIFT pin high to put the 8 bit data out parallel
time.sleep(0.1)
IO.output(6,0) | https://circuitdigest.com/microcontroller-projects/raspberry-pi-74hc595-shift-register-tutorial | CC-MAIN-2018-17 | refinedweb | 763 | 74.59 |
2 ?- bits(3,Bits). Bits = [0, 0, 0] ; Bits = [0, 0, 1] ; Bits = [0, 1, 0] ; Bits = [0, 1, 1] ; Bits = [1, 0, 0] ; Bits = [1, 0, 1] ; Bits = [1, 1, 0] ; Bits = [1, 1, 1] ; NoHere's the code:
% Non-deterministically returns a string of N bits. % bits(+N,?Bit_string) bits(0,[]). bits(N, [R | Rs]) :- N > 0, bit(R), N1 is N - 1, bits(N1,Rs). bit(0). bit(1).Here is another example.
bit(0). bit(1). bits(X,Y,Z) :- bit(X), bit(Y), bit(Z), write(X), write(Y), write(Z), nl, fail.The predicate (something like a function, though it doesn't work like a function) bits is non-deterministic, and returns multiple answers. In this example, it generates all bit strings of length 3. This is a quick and dirty tool for combinatorial computing, and you can easily use it to generate bits strings as input to other functions. You can also use bits to check if a list is a bit string, e.g.:
3 ?- bits(5,[1,0,1,1,1]). Yes 4 ?- bits(5,[1,1,1,1,0,1]). NoBut, and this is one of the frustrating parts of Prolog, this particular predicate doesn't work if the first parameter is a variable, e.g.
5 ?- bits(N,[1,1,1,1,0,1]). ERROR: Arguments are not sufficiently instantiatedThis error refers to the line N > 0, which requires that N be instantiated. ConstraintLogicProgramming is a useful extension of LogicProgramming that partially solves this sort of problem. If you would like to have the predicate also count the length of bit strings, add a second clause that checks for an uninstantiated variable, cuts choice point for the other recursive case, checks the first element of the list for being a bit, make a recursive call and increment the count as the stack unwinds. The new predicate would be,
% Non-deterministically returns a string of N bits or returns the length of a bit string. % bits(+N,?Bit_string) % bits(?N,+Bit_string) bits(0,[]). bits(N, [R | Rs]) :- var(N), !, bit(R), bits(N1, Rs), N is N1 + 1. bits(N, [R | Rs]) :- N > 0, bit(R), N1 is N - 1, bits(N1,Rs). bit(0). bit(1).This modified version gives the expected,
| ?- bits(N,[1,1,1,1,0,1]). N = 6 ? ; nowith no dangling choice points. What may be less obvious is the result of bits(X,Y) in this modified version or even what modifications would allow it to generate all combinations of bits for increasing length lists.
if(Condition, TrueClause?, FalseClause?) :- Condition, !, TrueClause?; !, FalseClause?)- I think. I don't have an implementation installed at the moment to check it, though. --DorKleiman Prolog already has an "if_then_" operator:
Condition -> TrueClause?; !, FalseClause?--RichardBotting
if (x == 1) { y = 0; } else { y = 1; } Alternatively: y = (x == 1) ? 0 : 1;Prolog:
if(X, Y) :- \+ var(X), var(Y), X is 1, % if this fails, prolog tries the next clause of if/2 Y is 0. if(X, Y) :- \+ var(X), var(Y), Y is 0. ?- if(0, A). A = 1. ?- if(1, A). A = 0.moral: Prolog CAN handle if-then-else clauses but not in the conventional sense. As DorKleiman says above, flow control is implicit and much of it is handled by the implementation. This is can be even simpler in Prolog:
if(1, 0). if(_, 1). ?- if(0, A). A = 1. ?- if(1, A). A = 0.Of course, now the word 'if' is consumed for this purpose... a rather poor choice, seriously. The prolog program above does not reflect the Java snippet, it would translate to public int ifx(int x) { //for lack of a better name
return (x == 1) ? 0 : 1;} The -> operator reflects the if-then-else more closely, and is, as stated above a short form for (condition, ! thenClause); !, elseClause. By the way, a constraint language could express the same thing as x#=\=y (unequal), given appropriate domain definitions. | http://c2.com/cgi/wiki?PrologLanguage | CC-MAIN-2016-26 | refinedweb | 665 | 70.53 |
Mark. I'm not an expert on this stuff so my apologies if I'm confused... First of all, it seems like -std=c89 specifies the variant of the C language that the compiler expects, whereas _BSD_SOURCE and _POSIX_SOURCE affect what declarations (and #define's) are included in the namespace visible to the compiler from #include files. So these two things seem to be orthogonal, so I don't understand what you mean by "we need the _BSD_SOURCE defined on GNU systems when compiling with -std=c89". On the other hand, it would make sense if you said: "we need the _BSD_SOURCE defined on GNU systems when compiling with _POSIX_SOURCE". Now, back to my other question: why not just get rid of _POSIX_SOURCE? That seems to solve the problem in all cases (unless I'm confused, which is probably the case :-) -Archie __________________________________________________________________________ Archie Cobbs * CTO, Awarix * | http://lists.gnu.org/archive/html/commit-classpath/2004-04/msg00077.html | CC-MAIN-2018-05 | refinedweb | 147 | 64.75 |
1 /*2 3 Copyright 2000-2001.event;19 20 import org.apache.batik.gvt.GraphicsNode;21 22 /**23 * An event which indicates that a keystroke occurred in a graphics node.24 *25 * @author <a HREF="mailto:Thierry.Kormann@sophia.inria.fr">Thierry Kormann</a>26 * @version $Id: GraphicsNodeKeyEvent.java,v 1.7 2005/02/22 09:13:02 cam Exp $27 */28 public class GraphicsNodeKeyEvent extends GraphicsNodeInputEvent {29 30 static final int KEY_FIRST = 400;31 32 /**33 * The "key typed" event. This event is generated when a character is34 * entered. In the simplest case, it is produced by a single key press.35 * Often, however, characters are produced by series of key presses, and36 * the mapping from key pressed events to key typed events may be37 * many-to-one or many-to-many.38 */39 public static final int KEY_TYPED = KEY_FIRST;40 41 /**42 * The "key pressed" event. This event is generated when a key43 * is pushed down.44 */45 public static final int KEY_PRESSED = 1 + KEY_FIRST;46 47 /**48 * The "key released" event. This event is generated when a key49 * is let up.50 */51 public static final int KEY_RELEASED = 2 + KEY_FIRST;52 53 /**54 * The unique value assigned to each of the keys on the55 * keyboard. There is a common set of key codes that56 * can be fired by most keyboards.57 * The symbolic name for a key code should be used rather58 * than the code value itself.59 */60 int keyCode;61 62 /**63 * <code>keyChar</code> is a valid unicode character64 * that is fired by a key or a key combination on65 * a keyboard.66 */67 char keyChar;68 69 /**70 * Constructs a new graphics node key event.71 * @param source the graphics node where the event originated72 * @param id the id of this event73 * @param when the time the event occurred74 * @param modifiers the modifier keys down while event occurred75 */76 public GraphicsNodeKeyEvent(GraphicsNode source, int id,77 long when, int modifiers, int keyCode,78 char keyChar) {79 super(source, id, when, modifiers);80 this.keyCode = keyCode;81 this.keyChar = keyChar;82 }83 84 /**85 * Return the integer code for the physical key pressed. Not localized.86 */87 public int getKeyCode() {88 return keyCode;89 }90 91 /**92 * Return a character corresponding to physical key pressed.93 * May be localized.94 */95 public char getKeyChar() {96 return keyChar;97 }98 99 }100
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/apache/batik/gvt/event/GraphicsNodeKeyEvent.java.htm | CC-MAIN-2017-30 | refinedweb | 412 | 65.62 |
1. Introduction to Boot Environments
2. Using beadm Utility (Tasks)
Zones Support Specifications
4. Appendix: beadm Reference
Note the following limitations of support for non-global zones in the beadm utility and in related processes:
When you use the pkg command, the command only upgrades ipkg branded zones.
The beadm utility is not supported inside a non-global zone.
Non-global zone support is limited to ZFS support. Zones are not supported unless they are on ZFS.
Zones are not supported in the rpool/ROOT namespace. Non-global zones are cloned or copied only when the original zone is within the shared area for the global zone, for example, within rpool/export or within rpool/zones.
Although the beadm utility affects the non-global zones on your system, the beadm utility does not display zones information. Use the zoneadm utility to view changes in the zones in your boot environment. For example, use the zoneadm list command to view a list of all current zones on the system.
For further information, see the zoneadm(1M) man page. | http://docs.oracle.com/cd/E19963-01/html/820-6565/zonelimit.html | CC-MAIN-2017-17 | refinedweb | 177 | 57.27 |
This project implements Dependency Injection for C++. It supports property setter injection and constructor injection. It is compiled on multiple platform. It supports POCO (Plain Old C++ Object) and has no constraints on the classes you create. It has no incursion to your program code.
Autumn framework contains two parts:
- a dynamic library and
- a wrapper generator named AutumnGen.
Autumn use a Small, simple, cross-platform, free and fast C++ XML Parser written by Frank Vanden Berghen to parse config file.
07/26/2007 Ver 0.5.0 released.
This version:
- support multi-inheritance, including direct and indirect inheritance. Indirect inheritance should list base classes in doccomment.
- add namespace Autumn for Autumn framework.
- decorate some class member functions with const.
- other changes, including Issues 1~3
05/21/2007 Ver 0.4.0 released.
This version:
- has AutumnGen, a generator for wrapper files. You needn't now write any code to use Autumn framework, you can generate wrapper files(a head file and a implementation file) from a head file with AutumnGen.
- bean support init-method, destroy-method and delete-method attributes.
- change "type" to "bean", remove "type" element in configure file.
03/26/2007 Ver 0.3.0 released.
This version:
- needn't set property's type or constructor argument's type in configuration file. If set, it will replace the type got with wrapper.
- bean supports factory-method attribute and multiple factory methods, and don't support overloading.
- erase bean's attributes: initializable and destroyable. Bean supports init and destroy function however, it's decided by definition of bean wrapper
- support bean reference.
- unite IBasicType and ICombinedType into IAutumnType.
03/13/2007 Ver 0.2.0 released.
This version supports creating bean using 'instance factory' and 'static factory method' patterns. You can find samples in test project.
03/05/2007 Ver 0.1.0 released.
You can download source code here. A simple install guide is here.The code has been compiled on:
- WindowsXP with Visual C++ 6.0
- Linux Ubuntu 6.06 with GCC 4.0.3
- SunOS 5.10 i86pc with Sun C++ 5.8
- AIX 5L with XL C V7.0
01/16/2007 Ver 0.1.0 beta for Windows VC6 released.
You can download it here. Some docs are here. CppDoc is here.
It may be very babyish now, because I don't know Spring well and do this to imitate Spring in a hurry. I will write some docs ASAP. Now, it support:
- Support property injection and constructor injection.Only two constructors now, one has arguments and one has no argument. The setter function name should be like setXXX where XXX is a property name. You may not obey that rule if you rewrite the file BeanWrapperMacro.h.
- Support following basic type: char, short, int, long, float, double, char*, string, and some docrated with unsigned.
- Support class injection. (A class is named as a bean in Autumn like in Spring.)
- Support customized type using interface IBasicType.
- Support pointer to above types.
- Support singleton.
- Support initialization and destroyation functions.
- Support property setter overloading.
- Supoort dependence(it may be not like Spring).
- Support multiple dynamic libraries and local library(bean is in main process).
- Support configuration of log file path and level. | http://code.google.com/p/autumnframework/ | crawl-002 | refinedweb | 538 | 62.85 |
When a program is running, the amount of elapsed time (as far as the 8051 is aware) is displayed in the field above the source code. The user can set the number of instructions executed between updates to the simulator GUI by selecting a value from the Update Freq. menu. Certain update frequencies suit some programs better than others. For example, if a program is multiplexing the four 7-segment displays, then it is best to run this program with an update frequency of 1. But if a program is sending data to the serial port, then a higher update frequency might be used in order to see the data arrive promptly. All of these programs have been written for 12 MHz 8051 system clock. For other clock frequencies, time delays would need to be modified accordingly. 1. 2. 3. 4. Binary Pattern on the Port 1 LEDs Echoing the Switches to the LEDs Multiplexing the 7-segment Displays LCD Module o in C o in assembly o plus a couple of CGRAM examples: Euro Symbol ADC Bar Graph Indicator on LCD 5. Ramp Signal on the DAC Output 6. Taking Samples from the ADC and Displaying them on the Scope via the DAC 7. Scanning the Keypad 8. Transmitting Data on the 8051 Serial Port 9. Receiving Data on the 8051 Serial Port 10. The Motor 11. Download the Examples source code:
edsim51examples.zip
The peripheral logic diagram is shown below. This diagram (and the extracts further down) relates to the standard peripheral interface. The user can move the peripherals to other port pins. A new logic diagram is then available from the simulator itself. Get more information.
Logic Diagram Extracts: Logic diagram showing the LED bank, DAC and 7-segment display connections only. Logic diagram showing the LED bank, DAC and LCD Module connections only. Logic diagram showing the switch bank and ADC connections only. Logic diagram showing the comparator and DAC connections only. Logic diagram showing the motor and UART connections only.
1. Binary Pattern on the Port 1 LEDs - logic diagram extract Notes on 8051 Parallel Input/Output
<-
; JMP start ; decrement port 1 ; and repeat
When running this program, best viewed with Update Freq. set to 1. 2. Echoing the Switches to the LEDs - logic diagram extract Notes on 8051 Parallel Input/Output
<-
;. MOV P1, P2 JMP start ; move data on P2 pins to P1 ; and repeat
start:
When running this program, best viewed with Update Freq. set to 1.
<-
; This program multiplexes the number 1234 ; on the four 7-segment displays. ; Note: a logic 0 lights a display segment. start: SETB P3.3 SETB P3.4 MOV P1, #11111001B CALL delay CLR P3.3 MOV P1, #10100100B CALL delay CLR P3.4 SETB P3.3 MOV P1, #10110000B CALL delay CLR P3.3 MOV P1, #10011001B CALL delay JMP start ; a crude delay delay: MOV R0, 200 DJNZ R0, $ RET ; | ; | enable display 3 ; put pattern for 1 on display ; enable display 2 ; put pattern for 2 on display ; | ; | enable display 1 ; put pattern for 3 on display ; enable display 0 ; put pattern for 4 on display ; jump back to start
When running this program, best viewed with Update Freq. set to 100. 4. LCD Module - logic diagram extract The example program for programming the LCD module is written in C. It was developed and compiled using the Keil uVision3 IDE. If you wish to write your own C programs for the 8051, get the free evaluation version of uVision3. The EdSim51 simulator can only parse assembly programs. It cannot compile C programs, therefore do not try to copy and paste the program below into EdSim51. Instead, you should compile the program in uVision3 and use the Intel HEX output file. This type of file can be loaded into EdSim51. See notes on EdSim51 and Intel HEX files. When the program below is running in the simulator, the user can shift the display right and left and can return the cursor home by using switches 5, 6 and 7 (see the comment in the main program for details). Since the simulator is not real-time, to be able to see the display shift left and right, it is best to set the simulator update frequency to 100.
<-
You can also download the HEX file output which was generated by the uVision3 compiler. #include <reg51.h> sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit void void void void void void DB7 = P1^7; DB6 = P1^6; DB5 = P1^5; DB4 = P1^4; RS = P1^3; E = P1^2; clear = P2^4; ret = P2^5; left = P2^6; right = P2^7; returnHome(void); entryModeSet(bit id, bit s); displayOnOffControl(bit display, bit cursor, bit blinking); cursorOrDisplayShift(bit sc, bit rl); functionSet void, DB4 = getBit(c, RS = 1; E = 1; E = 0; DB7 = getBit(c, DB6 = getBit(c, DB5 = getBit(c, DB4 = getBit(c, E = 1; E = 0; delay(); }
5); 4);
// -- End of LCD Module instructions // -------------------------------------------------------------------void sendString(char* str) { int index = 0; while (str[index] != 0) { sendChar(str[index]); index++; } } bit getBit(char c, char bitNumber) { return (c >> bitNumber) & 1; } void delay(void) { char c; for (c = 0; c < 50; c++); }
LCD Module Assembly Program Example The example below sends the text ABC to the display.
<-
; put data in RAM MOV 30H, #'A' MOV 31H, #'B' MOV 32H, #'C' MOV 33H, #0
; initialise the display ; see instruction set for details CLR P1.3 being sent to the module ; function set CLR P1.7 ; clear RS - indicates that instructions are
; |
CLR P1.6 SETB P1.5 CLR P1.4 SETB P1.2 CLR P1.2 CALL delay
; | ; | ; | high nibble set ; | ; | negative edge on E ; time SETB P1.7 changed) SETB P1.2 CLR P1.2 CALL delay ; low nibble set (only P1.7 needed to be ; ; ; ; | | negative edge on E function set low nibble sent wait for BF to clear ; | ; | negative edge on E ; same function set high nibble sent a second
; entry mode set ; set to increment with no shift CLR P1.7 ; | CLR P1.6 ; | CLR P1.5 ; | CLR P1.4 ; | high nibble set SETB P1.2 CLR P1.2 SETB P1.6 SETB P1.5 SETB P1.2 CLR P1.2 CALL delay ; | ; | negative edge on E ; | ; |low nibble set ; | ; | negative edge on E ;.2 CLR P1.2 CALL delay ; send data SETB P1.3 to module MOV R1, #30H starting at location 30H loop: MOV A, @R1 JZ finish - jump out of loop CALL sendCharacter INC R1 JMP loop finish: JMP $ sendCharacter: MOV C, ACC.7 MOV P1.7, C MOV C, ACC.6 MOV P1.6, C MOV C, ACC.5 MOV P1.5, C MOV C, ACC.4 MOV P1.4, C SETB P1.2 CLR P1.2 MOV MOV MOV MOV MOV MOV MOV MOV C, ACC.3 P1.7, C C, ACC.2 P1.6, C C, ACC.1 P1.5, C C, ACC.0 P1.4, C
; clear RS - indicates that data is being sent ; data to be sent to LCD is stored in 8051 RAM, ; move data pointed to by R1 to A ; if A is 0, then end of data has been reached ; send data in A to LCD module ; point to next piece of data ; repeat
; ; ; ; ; ; ; ;
<-
; This program generates a ramp on the DAC ; output. ; You can try adding values other than 8 ; to the accumulator to see what this does ; to the ramp signal. CLR P0.7 loop: MOV P1, A P1) ADD A, #4 JMP loop ; increase accumulator by 4 ; jump back to loop ; move data in the accumulator to the ADC inputs (on ; enable the DAC WR line
When running this program, best viewed with Update Freq. set to 1. The output on the scope should be something like this:
6. Taking Samples from the ADC and Displaying them on the Scope via the DAC - logic diagram extract Note: When using the ADC, the switches in the switch bank must be open (the switches are grey when closed, grey when closed). This is because the switch bank and the ADC share the same port, as can be seen in the logic diagram extract. Notes on ADC Interfacing.
<-
; JMP main ORG 3 JMP ext0ISR ORG 0BH JMP timer0ISR ORG 30H main: SETB IT0 SETB EX0 CLR P0.7 MOV TMOD, #2 timer MOV TH0, #-50 reload value, a timer 0 overflow every 50 us MOV TL0, #-50 ; | put the same value in the low byte to ensure the timer starts counting from ; | 236 (256 - 50) rather than 0 SETB TR0 SETB ET0 SETB EA JMP $ ; end of main program ; timer 0 ISR - simply starts an ADC conversion timer0ISR: CLR P3.6 ; clear ADC WR line SETB P3.6 ; then set it - this results in the required positive edge to start a conversion RETI ; return from interrupt ; external 0 ISR - responds to the ADC conversion complete interrupt ext0ISR: CLR P3.7 ; clear the ADC RD line - this enables the data lines ; ; ; ; start timer 0 enable timer 0 interrupt set the global interrupt enable bit jump back to the same line (ie: do nothing) ; | put -50 into timer 0 high-byte - this ; | with system clock of 12 MHz, will result in ; reset vector ; jump to the main program ; external 0 interrupt vector ; jump to the external 0 ISR ; timer 0 interrupt vector ; jump to timer 0 ISR ; main program starts here ; ; ; ; set external 0 interrupt as edge-activated enable external 0 interrupt enable DAC WR line set timer 0 as 8-bit auto-reload interval
; take the data from the ADC on P2 and send it ; disable the ADC data lines by setting RD ; return from interrupt
When running this program with Update Freq. set to 1, the student will observe the time delay between a change in the ADC input voltage appearing on the scope. In order to see this change appear on the scope more quickly, select a higher update frequency. A Further exercise for the student might be to display, using multiplexing, the actual input signal voltage to the ADC on the 7-segment displays. 7. Scanning the Keypad - logic diagram extract Notes on Keypads
<-
The following program shows how to scan the keypad. The program halts (to be precise, sits in an endless loop) once a key is pressed.
; | +----+----+----+ | 8 | 7 | 6 | +----+----|----+ | 5 | 4 | 3 | +----+----+----+ | 2 | 1 | 0 | +----+----+----+ col2 col1 col0 row3 row2 row1 row ; scan row0 SETB P0.3 CLR P0.0 CALL colScan JB F0, finish number is in R0) ; ; ; ; ; set row0 clear row1 call column-scan subroutine | if F0 is set, jump to end of program | (because the pressed key was found and its ; clear R0 - the first key is key0 ; ; ; ; ; set row3 clear row0 call column-scan subroutine | if F0 is set, jump to end of program | (because the pressed key was found and its
; scan row1 SETB P0.0 CLR P0.1 CALL colScan JB F0, finish number is in R0)
; scan row2 SETB P0.1 CLR P0.2 CALL colScan JB F0, finish number is in R0)
; ; ; ; ;
set row1 clear row2 call column-scan subroutine | if F0 is set, jump to end of program | (because the pressed key was found and its
; scan row3 SETB P0.2 CLR P0.3 CALL colScan JB F0, finish number is in R0)
; ; ; ; ;
set row2 clear row3 call column-scan subroutine | if F0 is set, jump to end of program | (because the pressed key was found and its
; | go back to scan row 0 ; | (this is why row3 is set at the start of ; | - when the program jumps back to start,
row3 has just been scanned) finish: JMP $ found - do nothing ; column-scan subroutine colScan: JNB P0.4, gotKey INC R0 JNB P0.5, gotKey ; program execution arrives here when key is
; if col0 is cleared - key found ; otherwise move to next key ; if col1 is cleared - key found
; ; ; ;
otherwise move to next key if col2 is cleared - key found otherwise move to next key return from subroutine - key not found
It may appear as if this program does nothing. Remember, the program simply scans the keypad until a key is pressed. It then places the key number in R0 and enters an endless loop, doing nothing. Therefore, to see that it has performed the task correctly, examine the contents of R0 after a key is pressed. Also remember that, if the update frequency is set to 1, it will take a short amount of time for they pressed key's number to appear in R0. Key number: the key number mentioned here is not the number on the key, but the key's position in the matrix. The # key is key number 0, 0 key is key number 1, * key is key number 2, and so on. Further exercises for the student might be: Modify the program so that the keypad is scanned continuously (ie: it doesn't stop after one key-press). Write extra code that displays the key symbol on one of the 7-segment displays. For example, if key 4 is pressed, the number 8 appears on the display. If key 10 is pressed the number 2 appears on the display. (Note: the symbols # and * cannot be displayed on a 7segment display, but some special characters could be invented and displayed instead.
8. Transmitting Data on the 8051 Serial Port - logic diagram extract Notes on the 8051 Serial Port
<-
; MOV A, PCON SETB ACC.7 ; | ; | put serial port in 8-bit UART mode ; | ; |
MOV PCON, A MOV TMOD, #20H timing mode MOV TH1, #243 overflow every 13 us) MOV TL1, #243 first started it will overflow SETB TR1 MOV 30H, #'a' MOV 31H, #'b' MOV 32H, #'c' 30H
; | set SMOD in PCON to double baud rate ; put timer 1 in 8-bit auto-reload interval ; put -13 in timer 1 high byte (timer will ; put same value in low byte so when timer is after 13 us ; start timer 1 ; | ; | ; | put data to be sent in RAM, start address
MOV 33H, #0 ; null-terminate the data (when the accumulator contains 0, no more data to be sent) MOV R0, #30H ; put data start address in R0 again: finish: JMP $ ; do nothing
Take note of what happens if the external UART is not set to Even Parity (ie: run the program with the UART on No Parity, then run it again with it set to Odd Parity). With the help of the ASCII table, see if you can explain the actual data that is displayed. It takes quite some time (from the 8051's perspective of time) for data to be sent to the UART. If the user wishes to see the data arrive at the UART quickly, it may be best, when running this program, to select an Update Freq. of 100 or 1000. Further exercises for the student might be: Modify the program to transmit data with no parity. Modify the program to transmit data with odd parity. The above program uses busy-waiting. In other words, it sends a byte to the serial port, then sits in a loop (testing the TI flag) waiting for the serial port to say it's ready for another byte. Rewrite the program making use of the serial port interrupt (get help with
8051 interrupts).
9. Receiving Data on the Serial Port - logic diagram extract Notes on the 8051 Serial Port
<-
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; SETB REN MOV A, PCON SETB ACC.7 MOV PCON, A MOV TMOD, #20H timing mode MOV TH1, #0FDH overflow every 3 us) MOV TL1, #0FDH first started it will overflow SETB TR1 MOV R1, #30H again: JNB RI, $ CLR RI MOV A, SBUF ; | ; | put serial port in 8-bit UART mode ; enable serial port receiver ; | ; | ; | set SMOD in PCON to double baud rate ; put timer 1 in 8-bit auto-reload interval ; put -3 in timer 1 high byte (timer will ; put same value in low byte so when timer is after approx. 3 us ; start timer 1 ; put data start address in R1 ; wait for byte to be received ; clear the RI flag ; move received byte to A
CJNE A, #0DH, skip instruction JMP finish the end of the program skip: MOV @R1, A INC R1 data will be stored JMP again finish: JMP $
; compare it with 0DH - it it's not, skip next ; if it is the terminating character, jump to ; move from A to location pointed to by R1 ; increment R1 to point at next location where ; jump back to waiting for next byte ; do nothing
Further exercises for the student might be: Modify the program to receive data with even parity. Modify the program to receive data with odd parity. Using parity checking, light LED0 (on port 1) if an error is detected in a received byte. The above program uses busy-waiting. In other words, it sits in a loop (testing the RI flag) waiting for a byte to be received. Rewrite the program making use of the serial port interrupt (get help with 8051 interrupts). Combine the transmit and receive programs to send back the data received from the external UART. In other words, whatever is sent from the UART Tx window should appear in the UART Rx window.
It takes quite some time (from the 8051's perspective of time) for data to be received from the UART. If the user wishes to see the data arrive in 8051 RAM quickly, it may be best, when running this program, to select an Update Freq. of 100 or 1000. 10. The Motor - logic diagram extract Notes on DC Motors
<; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; SETB TR1 MOV DPL, #LOW(LEDcodes) start address of the MOV DPH, #HIGH(LEDcodes) CLR P3.4 CLR P3.3 again: CALL setDirection MOV A, TL1 CJNE A, #10, skip 10 skip next instruction CALL clearTimer reset timer 1 skip: MOVC A, @A+DPTR - the index into the table is to the start of the ; | table - if there are two revolutions, then A will contain two, ; | therefore the second code in the table will be copied to A) MOV C, F0 carry MOV ACC.7, C ensure Display 0's decimal point MOV P1, A revolutions and motor direction JMP again setDirection: PUSH ACC PUSH 20H ; and from there to ACC.7 (this will ; will indicate the motor's direction) ; | move (7-seg code for) number of ; | indicator to Display 0 ; do it all again ; save value of A on stack ; save value of location 20H (first ; move motor direction value to the ; set the motor's direction ; move timer 1 low byte to A ; if the number of revolutions is not ; if the number of revolutions is 10, ; | get 7-segment code from code table ; | decided by the value in A ; | (example: the data pointer points ; put timer 1 in event counting mode ; start timer 1 ; | put the low byte of the ; | 7-segment code table into DPL ; put the high byte into DPH ; | ; | enable Display 0
bit-addressable CLR A MOV 20H, #0 MOV C, P2.0 MOV ACC.0, C MOV C, F0 MOV 0, C (which has bit address 0) CJNE A, 20H, changeDir of 20H) ; | - if they are not the same, the motor's direction needs to be reversed JMP finish ; if they are the same, motor's direction does not need to be changed changeD (it will therefore have the opposite motor will start ; | again in the new direction) finish: POP 20H from the stack POP ACC stack RET clearTimer: CLR A CLR TR1 MOV TL1, #0 SETB TR1 RET ; get original value for location 20H ; get original value for A from the ; return from subroutine ; ; ; ; ; reset revolution count in A to zero stop timer 1 reset timer 1 low byte to zero start timer 1 return from subroutine ; | and move it to motor control bit 0 ; | value to control bit 1 and the ; ; ; ; ; ; ; location in RAM) on stack clear A clear location 20H put SW0 value in carry then move to ACC.0 move current motor direction in carry and move to LSB of location 20H
LED
Note: The above program is a good illustration of what can go wrong if the sampling frequency
is too low. Try running the program with the motor at full speed (use the slider to the right of the motor to increase the motor speed). You should notice the motor completes a number of revolutions before the display updates. In other words, the motor's highest speed is too fast for the 8051 running at system clock of 12 MHz. Since the program only shows up to nine revolutions (displayed on the 7-segment display) and then starts counting again, it is best to run this program with an Update Freq. of 1. This allows the user observe the display count up from 0 to 9 and back to 0 again. It also illustrates the delay between the motor arm passing the sensor and the display update. Similarly, the delay between pressing the switch for a direction change and the actual direction change occurring is evident. The student will learn that, while in real time these delays are not noticeable, to the microcontroller these operations take quite some time. Further exercises for the student might be: With the above program only up to nine revolutions are counted, then the display resets. Use multiplexing on the 7-segment displays to count up to 99 revolutions. (Remember, when testing your program you do not have to sit idly by waiting for the motor to revolve a hundred times. You can pause the program, manually change the value in the timer 1 low byte - say to 98 - and then click Run to start the program again.) | https://id.scribd.com/document/132056747/The-Simulator-Does-Not-Run-in-Real-Time | CC-MAIN-2019-30 | refinedweb | 3,616 | 68.3 |
#include <Servo.h> Servo myservo; int pos = 0; const int buttonPinleft = 2;const int buttonPinright = 5;int buttonStateleft = 0;int buttonStateright = 0;void setup() { pinMode(buttonPinleft, INPUT); pinMode(buttonPinright, INPUT); myservo.attach(9);} void loop() { buttonStateleft = digitalRead(buttonPinleft); buttonStateright = digitalRead(buttonPinright); if (pos<180) pos=180; if (pos>0) pos=0; if (buttonStateleft == HIGH) { pos += 5; } if (buttonStateright == HIGH) { pos -= 5; } myservo.write(pos); delay(0);}
I'm doing a project where I have to control multiple servos with one arduino. I have this code I used for one servo, but I don't know if it will work for more than one. What do I have to do? Can I just do the code over again and define more buttons?
I didn't understand how to make the R-2R circuit.
One last thing. Is there any way to connect more servos than pins? For this, I need to connect 14 servos and 15 buttons. The buttons are taken care of, so I was wondering about the servos.
Thank you, but I'm confused. Let's say Buttons 1 and 2 are connected to Analog pin 1. Will the Analog pin be able to tell the difference between the buttons, or will it just read the amount of input it is receiving?
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=117386.msg885344 | CC-MAIN-2015-11 | refinedweb | 248 | 66.54 |
Description
beekeeper is a Python library designed around dynamically generating a RESTful client interface based on a minimal JSON hive.
The hive specification is designed to provide beekeeper (or other applications consuming hive files) with programmatically-designed insight into the structure of both the REST endpoints that are available and the objects and methods that those endpoints represent.
While the classes available in beekeeper can be used manually to create Pythonic representations of REST endpoints, it is strongly preferred that the library be used as a whole with a constructed hive file. As APIs become larger in scale (in terms of the number of endpoints and represented objects), the time benefit of beekeeper becomes more pronounced, as adding additional objects and endpoints is a trivial process.
Requirements
beekeeper requires Python 2.7.9/3.4.3 or higher and their built-in modules, as well as xmltodict.
Installation
pip install beekeeper
Usage
The usage of beekeeper will depend on what features are provided by the person who wrote the hive file. There are a number of ways that the hive writer can make your life easier. Regardless, at a base level, usage will look something like this:
from beekeeper import API myAPI = API.from_hive_file('fname.json') x = myAPI.Widgets.action(id='foo', argument='bar')
If the hive developer defines an ID variable for the object you’re working with, you can subscript, dictionary style:
x = myAPI.Widgets['foo'].action(argument='bar')
If you’ve only got one remaining argument in the method call, you don’t even need to name it! You can do something like this:
x = myAPI.Widgets['foo'].action('bar')
This also holds true if you have multiple variables, but the other ones are assigned by name:
x = myAPI.Widgets['foo'].action('bar', var2='baz')
If you’re using a hive file, then it should define which variables are needed. If you try to call a function without filling in that variable, it should automatically yell at you and tell you what variables are missing. Since these variables are defined within the hive, beekeeper will do the work for you, automatically determine what data type a particular variable is, and put it exactly where it needs to go.
beekeeper will also automatically handle parsing data. When you send data, beekeeper will read the MIME type that was defined in the variable for that data, and try to automatically move it from a “Python” format (e.g., a dictionary) to the right REST API format (e.g., JSON).
This holds true in the other direction as well; beekeeper will read the MIME type of the response data, and hand it back to you in a Pythonic format! If beekeeper doesn’t know how to handle the data, it’ll just give you the raw bytes so that you can do what you need to with them.
Notes
beekeeper does not currently do SSL certificate verification when used on Python versions earlier than 2.7.9 or 3.4.3.
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/beekeeper/ | CC-MAIN-2017-51 | refinedweb | 522 | 52.7 |
Hi there,
On Sat, 3 Aug 2002, Enrico Sorcinelli wrote:
> First of all, sorry for my duplicate RFC post to this list.
Heh, we all make mistakes. :)
[snip,snip]
> another old RFC with the same namespace has been submitted. However
> the RFC is out of date (October 2000!!!) I've found this module
> only on sourceforge but the project seems to be closed (the last
> 'work in progress' version is dated october 2000). How I proceed?
I'd mail the authors at their last known addresses saying that you
propose steal^H^H^H^H take over the namespace. If you get no reply in
a couple of weeks I'd guess you're safe enough to use it.
I like your module and I like the name. I'll give it a try when I get
a chance. (But don't hold your breath:). Would you like some help
with the documentation?
73,
Ged. | http://mail-archives.apache.org/mod_mbox/perl-modperl/200208.mbox/%3CPine.LNX.4.21.0208031052330.24849-100000@www2.jubileegroup.co.uk%3E | CC-MAIN-2020-45 | refinedweb | 155 | 84.68 |
This chapter is an excerpt from the new book, JavaFX: Developing Rich Internet Applications, authored by Jim Clarke, Jim Connors and Eric Bruno, published by Addison-Wesley Professional as part of The Java Series, ISBN 013701287X, Copyright 2009 Sun Microsystems, Inc. For more info, please visit: Safari Books Online subscribers can access the book here:?e.
As we already mentioned, JavaFX Script is a declarative scripting language with object-oriented support. If you are already acquainted with other languages such as Java, JavaScript, Groovy, Adobe ActionScript, or JRuby, JavaFX Script will look familiar, but there are significant differences. While supporting traditional pure scripting, it also supports the encapsulation and reuse capabilities afforded by object orientation. This allows the developer to use JavaFX to produce and maintain small- to large-scale applications. Another key feature is that JavaFX Script seamlessly integrates with Java.
Conceptually, JavaFX Script is broken down into two main levels, script and class. At the script level, variables and functions may be defined. These may be shared with other classes defined within the script, or if they have wider access rights, they may be shared with other scripts and classes. In addition, expressions called loose expressions may be created. These are all expressions declared outside of a class definition. When the script is evaluated, all loose expressions are evaluated.
A very simple script to display Hello World to the console is
println("Hello World");
Another example, showing how to do a factorial of 3, is shown in Listing 3.1.
def START = 3;
var result = START;
var a = result - 1;
while(a > 0) {
result *= a;
a--;
}
println("result = {result}");.
Apart from the script level, a class defines instance variables and functions and must first be instantiated into an object before being used. Class functions or variables may access script level functions or variables within the same script file, or from other script files if the appropriate access rights are assigned. On the other hand, script level functions can only access class variables and functions if the class is created into an object and then only if the class provides the appropriate access rights. Access rights are defined in more detail later in this chapter.
To declare a class in JavaFX, use the class keyword.
public class Title {
}
Developer Note - By convention, the first letter of class names is capitalized.
Developer Note - By convention, the first letter of class names is capitalized.
The public keyword is called an access modifier and means that this class can be used by any other class or script, even if that class is declared in another script file. If the class does not have a modifier, it is only accessible within the script file where it is declared. For example, the class Point in Listing 3.2 does not have a visibility modifier, so it is only has script visibility and can only be used within the ArtWork script.
class Point {// private class only
//visible to the ArtWork class
var x:Number;
var y:Number;
}
public class ArtWork {
var location:.
To extend a class, use the extends keyword followed by the more generalized class name. JavaFX classes can extend at most one Java or JavaFX class. If you extend a Java class, that class must have a default (no-args) constructor.
public class Porsche911 extends Porsche {
}
JavaFX may extend multiple JavaFX mixin classes or Java interfaces. Mixin classes are discussed in the next section.
An application may contain many classes, so it is helpful to organize them in a coherent way called packages. To declare that your class or script should belong to a package, include a package declaration at the beginning of the script file. The following example means that the Title class belongs to the com._mycompany.components package. The full name of the Title class is now com.mycompany.components.Title. Whenever the Title class is referenced, it must be resolved to this full name.
package com.mycompany.components;
public class Title {
}
To make this resolution easier, you can include an import statement at the top of your source file. For example:
import com.mycompany.components.Title;
var productTitle = Title{};
Now, wherever Title is referenced within that script file, it will resolve to com.mycompany.components.Title. You can also use a wildcard import declaration:
import com.mycompany.components.*;
With the wildcard form of import, whenever you refer to any class in the com.mycompany.components package, it will resolve to its full name. The following code example shows how the class names are resolved, showing the fully qualified class name in comments.
package com.mycompany.myapplication;
import com.mycompany.components.Title;
// com.mycompany.myapplication.MyClass
public class MyClass {
// com.mycompany.components.Title
public var title: Title;
}
A class can have package visibility by using the package keyword instead of public. This means the class can only be accessed from classes within the same package.
package class MyPackageClass {
}
A class may also be declared abstract, meaning that this class cannot be instantiated directly, but can only be instantiated using one of its subclasses. Abstract classes are not intended to stand on their own, but encapsulate a portion of shared state and functions that several classes may use. Only a subclass of an abstract class can be instantiated, and typically the subclass has to fill in those unique states or behavior not addressed in the abstract class.
public abstract class MyAbstractClass {
}
If a class declares an abstract function, it must be declared abstract.
public abstract class AnotherAbstractClass {
public abstract function
setXY(x:Number, y:Number) : Void;
}.
In JavaFX, objects are instantiated using object literals. This is a declarative syntax using the name of the class that you want to create, followed by a list of initializers and definitions for this specific instance. In Listing 3.3, an object of class Title is created with the text “JavaFX is cool” at the screen position 10, 50. When the mouse is clicked, the provided function will be called.
var title = Title {
text: "JavaFX is cool"
x: 10
y: 50
onMouseClicked: function(e:MouseEvent):Void {
// do something
}
};
When declaring an object literal, the instance variables may be separated by commas or whitespace, as well as the semi-colon.
You can also override abstract functions within the object literal declaration. The following object literal, shown in Listing 3.4, creates an object for the java.awt .event.ActionListener interface and overrides the abstract java method void actionPerformed(ActionEvent e) method.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
var listener = ActionListener {
override function
actionPerformed(e: ActionEvent) : Void {
println("Action Performed!");
}
}
JavaFX supports two kinds of variables: instance and script. Script variables hold state for the entire script, whereas instance variables hold state for specific instantiations of a class declared within the script file.
There are basically two flavors of variables: unassignable and changeable. Unassignable variables are declared using the def keyword and must be assigned a default value that never changes.
public def PI = 3.14;
These variables cannot be assigned to, overridden, or initialized in object literals. In a sense, these can be viewed as constants; however, they are not “pure” constants and can participate in binding. (For more information on binding, see Chapter 4, Synchronize Data Models—Binding and Triggers.)
Consider the following example of defining an unassignable variable that contains an object. The object instance cannot change, but that does not mean the state of that instance will not.
def centerPoint = Point{x: 100, y:100};
centerPoint.x = 500;
The actual Point object assigned to centerPoint remains unchanged, but the state of that object instance, the actual x and y values, may change. When used in binding though, centerPoint is constant; if the state of centerPoint changes, the bound context will be notified of the change.
Changeable instance variables are declared using the var keyword with an optional default value. If the default value is omitted, a reasonable default is used; basically, Numbers default to zero, Boolean defaults to false, Strings default to the empty string, Sequences default to the Empty Sequence, and everything else defaults to null.
Script variables are declared outside of any class declaration, whereas instance variables are declared within a class declaration. If a script variable is declared with one of the access modifiers—public, protected, or package—it may be used from outside of the script file, by referring to its fully qualified name. This fully qualified name is the combination of package name, script name, and the variable name. The following is the fully qualified name to a public script variable from the javafx.scene.Cursor class for the crosshair cursor.
javafx.scene.Cursor.CROSSHAIR;
Instance variables are declared within a class declaration and come into being when the object is created. Listing 3.5 illustrates several examples of script and instance variables.
import javafx.scene.Cursor;
import javafx.scene.paint.Color;
// import of script variable from javafx.scene.Cursor
import javafx.scene.Cursor.CROSSHAIR;
// Unchangeable script variable
def defaultText = "Replace ME"; // Script accessible only
// Changeable script variable
public var instanceCount: Integer; // Public accessible
public class Title {
// Unchangeable instance variables
def defStroke = Color.NAVY; // class only access,
//resolves to javafx.scene.paint.Color.NAVY
// Changeable instance variables
// defaults to the empty String ""
public var text:String;
public var width: Number; // defaults to zero (0.0)
public var height = 100; // Infers Integer type
public var stroke: Color = defaultStroke;
public var strokeWidth = 1.0; // Infers Number type
public var cursor = CROSSHAIR;
//resolves to javafx.scene.Cursor.CROSSHAIR
...
}
You may have noticed that some of the declarations contain a type and some don’t. When a type is not declared, the type is inferred from the first assigned value. String, Number, Integer, and Boolean are built-in types, everything else is either a JavaFX or a Java class. (There is a special syntax for easily declaring Duration and KeyFrame class instances that will be discussed in Chapter 7, Add Motion with JavaFX Animation.)
Table 3.1 lists the access modifiers for variables and their meaning and restrictions. You will notice reference to initialization, which refers to object literal declarations. Also, you will notice variables being bound. This is a key feature of JavaFX and is discussed in depth in Chapter 4.
var
The default access permission is script access, so without access modifiers, a variable can be initialized, overridden, read, assigned, or bound from within the script only.
def
The default access permission is script access; a definition can be read from or bound to within the script only.
public var
Read and writable by anyone. Also, it can be initialized, overridden, read, assigned, or bound from anywhere.
public def
This definition can be read anywhere. A definition cannot be assigned, initialized (in an object literal), or overridden no matter what the access permissions. It may be bound from anywhere.
public-read var
Readable by anyone, but only writable within the script.
public-init var
Can be initialized in object literals, but can only be updated by the owning script. Only allowed for instance variables.
package var
A variable accessible from the package. This variable can be initialized, overridden, read, assigned, or bound only from a class within the same package.
package def
Define a variable that is readable or bound only from classes within the same package.
protected var
A variable accessible from the package or subclasses. This variable can be initialized, overridden, read, assigned, or bound from only a subclass or a class within the same package.
protected def
Define a variable that is readable or bound only from classes within the same package or subclasses.
public-read protected var
Readable and bound by anyone, but this variable can only be initialized, overridden, or assigned from only a subclass or a class within the same package.
public-init protected var
Can be initialized in object literals, read and bound by anyone, but can only be overridden or assigned, from only a subclass or a class within the same package. Only allowed for instance variables.
You can also declare change triggers on a variable. Change triggers are blocks of JavaFX script that are called whenever the value of a variable changes. To declare a change trigger, use the on replace syntax:
public var x:Number = 100 on replace {
println("New value is {x}");
};
public var width: Number on replace (old) {
println("Old value is {old}, New value is {x}");
}
Change triggers are discussed in more depth in Chapter 4.
Sequences are ordered lists of objects. Because ordered lists are used so often in programming, JavaFX supports sequence as a first class feature. There is built-in support in the language for declaring sequences, inserting, deleting, and modifying items in the sequence. There is also powerful support for retrieving items from the sequence.
To declare a sequence, use square brackets with each item separated by a comma. For example:
public def monthNames = ["January", "February", "March",
"April", "May", "June",
"July", August", "September",
"October", "November", "December"];
This sequence is a sequence of Strings, because the elements within the brackets are Strings. This could have also been declared as
public def monthNames: String[] = [ "January", .....];
To assign an empty sequence, just use square brackets, []. This is also the default value for a sequence. For example, the following two statements both equal the empty sequence.
public var nodes:Node[] = [];
public var nodes:Node[];
When the sequence changes, you can assign a trigger function to process the change. This is discussed in depth in the next chapter.
A shorthand for declaring a sequence of Integers and Numbers uses a range, a start integer or number with an end. So, [1..9] is the sequence of the integers from 1 thru 9, inclusive; the exclusive form is [1..<9]—that is, 1 through 8. You can also use a step function, so if, for example, you want even positive integers, use [2..100 step 2]. For numbers, you can use decimal fractions, [0.1..1.0 step 0.1]. Without the step, a step of 1 or 1.0 is implicit.
Ranges may also go in decreasing order. To do this, the first number must be higher than the second. However, without a negative step function, you always end up with an empty sequence. This is because the default step is always positive 1.
var negativeNumbers = [0..-10]; // Empty sequence
var negativeNumbers = [0..-10 step -1]; // 0,-1,-2,...-10
var negativeNumbers = [0..<-10 step -1]; // 0,-1,-2,...,-9
To build sequences that include the elements from other sequences, just include the source sequences within the square brackets.
var negativePlusEven = [ negativeNumbers, evenNumbers ];
Also, you can use another sequence to create a sequence by using the Boolean operator. Another sequence is used as the source, and a Boolean operator is applied to each element in the source sequence, and the elements from the source that evaluate to true are returned in the new sequence. In the following example, n represents each item in the sequence of positive integers and n mod 2 == 0 is the evaluation.
var evenIntegers = positiveIntegers[n | n mod 2 == 0];
One can also allocate a sequence from a for loop. Each object “returned” from the iteration of the for loop is added to the sequence:
// creates sequence of Texts
var lineNumbers:Text[] = for(n in [1..100]) {
Text { content: "{n}" };
};
// creates Integer sequence, using indexof operator
var indexNumbers = for(n in nodes) {
indexof n;
};
To get the current size of a sequence use the sizeof operator.
var numEvenNumbers = sizeof evenNumbers;
To access an individual element, use the numeric index of the element within square brackets:
var firstMonth = monthNames[0];
You can also take slices of sequence by providing a range. Both of the next two sequences are equal.
var firstQuarter = monthNames[0..2];
var firstQuarter = monthNames[0..<3];
The following two sequences are also equal. The second example uses a syntax for range to indicate start at an index and return all elements after that index.
var fourthQuarter = monthNames[9..11 ];
var fourthQuarter = monthNames[9.. ];
To iterate over a sequence, use the for loop:
for( month in monthNames) {
println("{month}");
}
To replace an element in a sequence, just assign a new value to that indexed location in the index.
var students = [ "joe", "sally", "jim"];
students[0] = "vijay";.
To insert an element into the sequence, use the insert statement:
// add "vijay" to the end of students
insert "vijay" into students;
// insert "mike" at the front of students
insert "mike" before students[0];
// insert "george" after the second student
insert "george" after students[1];
To delete an element, use the delete statement:
delete students[0]; // remove the first student
delete students[0..1]; // remove the first 2 students
delete students[0..<2]; // remove the first 2 students
delete students[1..]; // remove all but the first student
delete "vijay" from students;
delete students; // remove all students
Native array is a feature that allows you to create Java arrays. This feature is mainly used to handle the transfer of arrays back and forth from JavaFX and Java. An example of creating a Java int[] array is shown in the following code.
var ints: nativearray of Integer =
[1,2,3] as nativearray of Integer;
Native arrays are not the same as sequences, though they appear similar. You cannot use the sequence operators, such as insert and delete, or slices. However, you can do assignments to the elements of the array as shown in the following code:
ints[2] = 4;
However, if you assign outside of the current bounds of the array, you will get an ArrayIndexOutOfBounds Exception.
You can also use the for operator to iterate over the elements in the native array. The following code shows an example of this.
for(i in ints) {
println(i);
}
for(i in ints where i mod 2 == 0) {
println(i);
}
Functions define behavior. They encapsulate statements that operate on inputs, function arguments, and may produce a result, a returned expression. Like variables, functions are either script functions or instance functions. Script functions operate at the script level and have access to variables and other functions defined at the script level. Instance functions define the behavior of an object and have access to the other instance variables and functions contained within the function’s declaring class. Furthermore, an instance function may access any script-level variables and functions contained within its own script file.
To declare a function, use an optional access modifier, public, protected, or package, followed by the keyword function and the function name. If no access modifier is provided, the function is private to the script file. Any function arguments are contained within parentheses. You may then specify a function return type. If the return type is omitted, the function return type is inferred from the last expression in the function expression block. The special return type of Void may be used to indicate that the function returns nothing.
In the following example, both function declarations are equal. The first function infers a return type of Glow, because the last expression in the function block is an object literal for a Glow object. The second function explicitly declares a return type of Glow, and uses the return keyword.
public function glow(level: Number) {
// return type Glow inferred
Glow { level: level };
}
public function glow(): Glow { // explicit return type
return glow(3.0); // explicit return keyword
}
The return keyword is optional when used as the last expression in a function block. However, if you want to return immediately out of an if/else or loop, you must use an explicit return.
In JavaFX, functions are objects in and of themselves and may be assigned to variables. For example, to declare a function variable, assign a function to that variable, and then invoke the function through the variable.
var glowFunction : function(level:Number):Glow;
glowFunction = glow;
glowFunction(1.0);
Functions definitions can also be anonymous. For example, for a function variable:
var glowFunction:function(level:Number): Glow =
function(level:Number) {
Glow { level: level };
};
Or, within an object literal declaration:
TextBox {
columns: 20
action: function() {
println("TextBox action");
}
}
Use override to override a function from a superclass.
class MyClass {
public function print() { println("MyClass"); }
}
class MySubClass extends MyClass {
override function print() { println("MySubClass"); }
}
String literals can be specified using either double (") or single (') quotes. The main reason to use one over the other is to avoid character escapes within the string literal—for example, if the string literal actually contains double quotes. By enclosing the string in single quotes, you do not have to escape the embedded double quotes. Consider the following two examples, which are both valid:
var quote = "Winston Churchill said:
\"Never in the field of human conflict was
so much owed by so many to so few.\""
var quote = 'Winston Churchill said:
"Never in the field of human conflict was
so much owed by so many to so few."'
Expressions can be embedded within the string literal by using curly braces:
var name = "Jim";
// prints My name is Jim
println ( "My name is {name}" );
The embedded expression must be a valid JavaFX or Java expression that returns an object. This object will be converted to a string using its toString() method. For instance:
println ( "Today is {java.util.Date{}}" );
var state ="The state is {
if(running) "Running" else "Stopped"}";
println(" The state is {getStateStr()}" );
println("The state is {
if(checkRunning()) "Running" else "Stopped"}");
Also, a string literal may be split across lines:
var quote = "Winston Churchill said: "
"\"Never in the field of human conflict was so much owed "
"by so many to so few.\"";
In this example, the strings from both lines are concatenated into one string. Only the string literals within the quotes are used and any white space outside of the quotes is ignored.
Unicode characters can be entered within the string literal using \u + the four digit unicode.
var thanks = "dank\u00eb"; // dank
Embedded expressions within string literals may contain a formatting code that specifies how the embedded expression should be presented. Consider the _following:
var totalCountMessage = "The total count is {total}";
Now if total is an integer, the resulting string will show the decimal number; but if total is a Number, the resulting string will show the number formatted according to the local locale.
var total = 1000.0;
produces:
The total count is 1000.0
To format an expression, you need a format code within the embedded expression. This is a percent (%) followed by the format codes. The format code is defined in the java.util.Formatter class. Please refer to its JavaDoc page for more details ().
println("Total is {%f total}"); // Total is 1000.000000
println("Total is {%.2f total}"); // Total is 1000.00
println("Total is {%5.0f total}"); // Total is 1000
println("Total is {%+5.0f total}"); // Total is +1000
println("Total is {%,5.0f total}"); // Total is 1,000
Developer Note - To include a percent (%) character in a string, it needs to be escaped with another percent (%%). For example:
println("%%{percentage}"); // prints %25
Developer Note - To include a percent (%) character in a string, it needs to be escaped with another percent (%%). For example:
println("%%{percentage}"); // prints %25
To internationalize a string, you must use the “Translate Key” syntax within the string declaration. To create a translate key, the String assignment starts with ## (sharp, sharp) combination to indicate that the string is to be translated to the host locale. The ## combination is before the leading double or single quote. Optionally, a key may be specified within square brackets ([]). If a key is not specified, the string itself becomes the key into the locale properties file. For example:
var postalCode = ## "Zip Code: ";
var postalCode = ##[postal]"Zip Code: ";
In the preceding example, using the first form, the key is "Zip Code: ", whereas for the second form, the key is "postal". So how does this work?
By default, the localizer searches for a property file for each unique script name. This is the package name plus script filename with a locale and a file type of .fxproperties. So, if your script name is com.mycompany.MyClass, the localizer code would look for a property file named com/mycompany/MyClass_xx. fxproperties on the classpath, where xx is the locale. For example, for English in the United Kingdom, the properties filename would be com/mycompany/MyClass_en_GB.fxproperties, whereas French Canadian would be com/mycompany/MyClass_fr_CA.fxproperties. If your default locale is just English, the properties file would be MyClass_en.fxproperties. The more specific file is searched first, then the least specific file is consulted. For instance, MyClass_ en_GB.fxproperties is searched for the key and if it is not found, then MyClass_en.fxproperties would be searched. If the key cannot be found at all, the string itself is used as the default. Here are some examples:
Example #1:
println(##"Thank you");
println(##"Thank you");
French – MyClass_fr.fxproperties:
"Thank you" = "Merci"
"Thank you" = "Merci"
German – MyClass_de.fxproperties:
"Thank you" = "Danke"
"Thank you" = "Danke"
Japanese – MyClass_ja.fxproperties:
"Thank you" = "Arigato"
"Thank you" = "Arigato"
Example #2:
println(##[ThankKey] "Thank you");
println(##[ThankKey] "Thank you");
"ThankKey" = "Merci"
"ThankKey" = "Merci"
"ThankKey" = "Danke"
"ThankKey" = "Danke"
"ThankKey" = "Arigato"
"ThankKey" = "Arigato"
When you use a string with an embedded expression, the literal key contains a %s, where the expression is located within the string. For example:
println(##"Hello, my name is {firstname}");
In this case, the key is "Hello, my name is %s". Likewise, if you use more than one expression, the key contains a "%s" for each expression:
println(##"Hello, my name is {firstname} {lastname}");
Now, the key is "Hello, my name is %s %s".
This parameter substitution is also used in the translated strings. For example:
"Hello, my name is %s %s" = "Bonjour, je m'appelle %s %s"
Lastly, you can associate another Properties file to the script. This is done using the javafx.util.StringLocalizer class. For example:
StringLocalizer.associate("com.mycompany.resources.MyResources", "com.mycompany");
Now, all translation lookups for scripts in the com.mycompany package will look for the properties file com/mycompany/resources/MyResources_xx.fxproperties, instead of using the default that uses the script name. Again, xx is replaced with the locale abbreviation codes.
A block expression is a list of statements that may include variable declarations or other expressions within curly braces. If the last statement is an expression, the value of a block expression is the value of that last expression; otherwise, the block expression does not represent a value. Listing 3.6 shows two block expressions. The first expression evaluates to a number represented by the subtotal value. The second block expression does not evaluate to any value as the last expression is a println() function that is declared as a Void.
// block expression with a value
var total = {
var subtotal = 0;
var ndx = 0;
while(ndx < 100) {
subtotal += ndx;
ndx++;
};
subtotal; // last expression
};
//block expression without a value
{
var total = 0;
var ndx = 0;
while(ndx < 100) {
total += ndx;
ndx++;
};
println("Total is {total}");
}
The throw statement is the same as Java and can only throw a class that extends java.lang.Throwable.
The try/catch/finally expression is the same as Java, but uses the JavaFX syntax:
try {
} catch (e:SomeException) {
} finally {
}
Table 3.2 contains a list of the operators used in JavaFX. The priority column indicates the operator evaluation precedence, with higher precedence operators in the first rows. Operators with the same precedence level are evaluated equally. Assignment operators are evaluated right to left, whereas all others are evaluated left to right. Parentheses may be used to alter this default evaluation order.
1
++/-- (Suffixed)
Post-increment/decrement assignment
2
++/-- (Prefixed)
Pre-increment/decrement assignment
-
Unary minus
not
Logical complement; inverts value of a Boolean
sizeof
Size of a sequence
reverse
Reverse sequence order
indexof
Index of a sequence element
3
/, *, mod
Arithmetic operators
4
+, -
5
==, !=
Comparison operators (Note: all comparisons are similar to isEquals() in Java)
<, <=, >, >=
Numeric comparison operators
6
instanceof, as
Type operators
7
and
Logical AND
8
or
Logical OR
9
+=, -=, *=, /=
Compound assignment
10
=>, tween
Animation interpolation operators
11
=
Assignment
if is similar to if as defined in other languages. First, a condition is evaluated and if true, the expression block is evaluated. Otherwise, if an else expression block is provided, that expression block is evaluated.
if (date == today) {
println("Date is today");
}else {
println("Out of date!!!");
}
One important feature of if/else is that each expression block may evaluate to an expression that may be assigned to a variable:
var outOfDateMessage = if(date==today) "Date is today"
else "Out of Date";
Also the expression blocks can be more complex than simple expressions. Listing 3.7 shows a complex assignment using an if/else statement to assign the value to outOfDateMessage.
var outOfDateMessage = if(date==today) {
var total = 0;
for(item in items) {
total += items.price;
}
totalPrice += total;
"Date is today";
} else {
errorFlag = true;
"Out of Date";
};
In the previous example, the last expression in the block, the error message string literal, is the object that is assigned to the variable. This can be any JavaFX Object, including numbers.
Because the if/else is an expression block, it can be used with another if/else statement. For example:
var taxBracket = if(income < 8025.0) 0.10
else if(income < 32550.0)0.15
else if (income < 78850.0) 0.25
else if (income < 164550.0) 0.28
else 0.33;
for loops are used with sequences and allow you to iterate over the members of a sequence.
var daysOfWeek : String[] =
[ "Sunday", "Monday", "Tuesday" ];
for(day in daysOfWeek) {
println("{indexof day}). {day}");
}
To be similar with traditional for loops that iterate over a count, use an integer sequence range defined within square brackets.
for( i in [0..100]} {
The for expression can also return a new sequence. For each iteration, if the expression block executed evaluates to an Object, that Object is inserted into a new sequence returned by the for expression. For example, in the following for expression, a new Text node is created with each iteration of the day of the week. The overall for expression returns a new sequence containing Text graphical elements, one for each day of the week.
var textNodes: Text[] = for( day in daysOfWeek) {
Text {content: day };
}
Another feature of the for expression is that it can do nested loops. Listing 3.8 shows an example of using nested loops.
class Course {
var title: String;
var students: String[];
}
var courses = [
Course {
title: "Geometry I"
students: [ "Clarke, "Connors", "Bruno" ]
},
Course {
title: "Geometry II"
students: [ "Clarke, "Connors", ]
},
Course {
title: "Algebra I"
students: [ "Connors", "Bruno" ]
},
];
for(course in courses, student in course.students) {
println("Student: {student} is in course {course}");
}
This prints out:
Student: Clarke is in course Geometry I
Student: Connors is in course Geometry I
Student: Bruno is in course Geometry I
Student: Clarke is in course Geometry II
Student: Connors is in course Geometry II
Student: Connors is in course Algebra I
Student: Bruno is in course Algebra I
There may be zero or more secondary loops and they are separated from the previous ones by a comma, and may reference any element from the previous loops.
You can also include a where clause on the sequence to limit the iteration to only those elements where the where clause evaluates to true:
var evenNumbers = for( i in [0..1000] where i mod 2 == 0 ) i;
The while loop works similar to the while loop as seen in other languages:
var ndx = 0;
while ( ndx < 100) {
println("{ndx}");
ndx++;
}
Note that unlike the JavaFX for loop, the while loop does not return any expression, so it cannot be used to create a sequence.
break and continue control loop iterations. break is used to quit the loop altogether. It causes all the looping to stop from that point. On the other hand, continue just causes the current iteration to stop, and the loop resumes with the next iteration. Listing 3.9 demonstrates how these are used.
for(student in students) {
if(student.name == "Jim") {
foundStudent = student;
break; // stops the loop altogether,
//no more students are checked
}
}
for(book in Books ) {
if(book.publisher == "Addison Wesley") {
insert book into bookList;
continue; // moves on to check next book.
}
insert book into otherBookList;
otherPrice += book.price;
}
The instanceof operator allows you to test the class type of an object, whereas the as operator allows you to cast an object to another class. One way this is useful is to cast a generalized object to a more specific class in order to perform a function from that more specialized class. Of course, the object must inherently be that kind of class, and that is where the instanceof operator is useful to test if the object is indeed that kind of class. If you try to cast an object to a class that that object does not inherit from, you will get an exception.
In the following listing, the printLower() function will translate a string to lowercase, but for other types of objects, it will just print it as is. First, the generic object is tested to see if it is a String. If it is, the object is cast to a String using the as operator, and then the String’s toLowerCase() method is used to convert the output to all lowercase. Listing 3.10 illustrates the use of the instanceof and as operators.
function printLower(object: Object ) {
if(object instanceof String) {
var str = object as String;
println(str.toLowerCase());
}else {
println(object);
}
}
printLower("Rich Internet Application");
printLower(3.14);
For a pure script that does not declare exported classes, variables, or functions, the command-line arguments can be retrieved using the javafx.lang.FX .getArguments():String[] function. This returns a Sequence of Strings that contains the arguments passed to the script when it started. There is a another version of this for use in other invocations, such as applets, where the arguments are passed using name value pairs, javafx.lang.FX.getArguments(key:String) :String[]. Similarly, there is a function to get system properties, javafx.lang.FX .getProperty(key:String):String[].
If the script contains any exported classes, variables, or functions, arguments are obtained by defining a special run function at the script level.
public function run(args:String[] ) {
for(arg in args) {
println("{arg}");
}
}.
There are a set of functions that are automatically available to all JavaFX scripts. These functions are defined in javafx.lang.Builtins.
You have already seen one of these, println(). Println() takes an object argument and prints it out to the console, one line at a time. It is similar to the Java method, System.out.println(). Its companion function is print(). Print() prints out its argument but without a new line. The argument’s toString() method is invoked to print out a string.
println("This is printed on a single line");
print("This is printed without a new line");
Another function from javafx.lang.Builtins is isInitialized(). This method takes a JavaFX object and indicates whether the object has been completely initialized. It is useful in variable triggers to determine the current state of the object during initialization. There may be times that you want to execute some functionality only after the object has passed the initialization stage. For example, Listing 3.11 shows the built-in, isInitialized() being used in an on replace trigger.
public class Test {
public var status: Number on replace {
// will not be initialized
// until status is assigned a value
if(isInitialized(status)) {
commenceTest(status);
}
}
public function commenceTest(status:Number) : Void {
println("commenceTest status = {status}:);
}
}
In this example, when the class, Test, is first instantiated, the instance variable, status, first takes on the default value of 0.0, and then the on replace expression block is evaluated. However, this leaves the status in the uninitialized state. Only when a value is assigned to status, will the state change to initialized. Consider the following:
var test = Test{}; // status is uninitialized
test.status = 1; // now status becomes initialized
In this case when Test is created using the object literal, Test{}, status takes on the default value of 0.0; however, it is not initialized, so commenceTest will not be invoked during object creation. Now when we assign a value to status, the state changes to initialized, so commenceTest is now invoked. Please note that if we had assigned a default value to status, even if that value is 0, then status immediately is set to initialized. The following example demonstrates this.
public class Test {
public var status: Number = 0 on replace {
// will be initialized immediately.
if(isInitialized(status)) {
commenceTest(status);
}
}
The last built-in function is isSameObject(). isSameObject() indicates if the two arguments actually are the same instance. This is opposed to the == operator. In JavaFX, the == operator determines whether two objects are considered equal, but that does not mean they are the same instance. The == operator is similar to the Java function isEquals(), whereas JavaFX isSameObject is similar to the Java == operator. A little confusing if your background is Java!
The built-in variables are __DIR__ and __FILE__. __FILE__ holds the resource URL string for the containing JavaFX class. __DIR__ holds the resource URL string for directory that contains the current class. For example,
println("DIR = {__DIR__}");
println("FILE = {__FILE__}");
// to locate an image
var image = Image { url: "{__DIR__}images/foo.jpeg" };
The following examples show the output from a directory based classpath versus using a JAR-based class path.
Using a Jar file in classpath
$javafx -cp Misc.jar misc.Test
DIR = jar:file:/export/home/jclarke/Documents/
Book/FX/code/Chapter3/Misc/dist/Misc.jar!/misc/
FILE = jar:file:/export/home/jclarke/Documents/
Book/FX/code/Chapter3/Misc/dist/Misc.jar!/misc/Test.class
Using directory classpath
$ javafx -cp . misc.Test
DIR = file:/export/home/jclarke/Documents/Book/
FX/code/Chapter3/Misc/dist/tmp/misc/
FILE = file:/export/home/jclarke/Documents/Book/
FX/code/Chapter3/Misc/dist/tmp/misc/Test.class.
This chapter covered key concepts in the JavaFX Scripting language. You were shown what constitutes a script and what constitutes a class. You were shown how to declare script and instance variables, how to create and modify sequences, and how to control logic flow.
You now have a basic understanding of the JavaFX Script language syntax and operators. Now, it is time to put this to use. In the following chapters, we will drill down into the key features of JavaFX and show how to leverage the JavaFX Script language to take advantage of those features. In the next chapter, we start our exploration of JavaFX by discussing the data synchronization support in the JavaFX runtime.
[1] Torgersson, Olof. “A Note on Declarative Programming Paradigms and the Future of Definitional Programming,” Chalmers University of Technology and Göteborg University, Göteborg, Sweden..
[1] Torgersson, Olof. “A Note on Declarative Programming Paradigms and the Future of Definitional Programming,” Chalmers University of Technology and Göteborg University, Göteborg, Sweden..
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) | http://www.codeproject.com/Articles/37505/Chapter-JavaFX-Primer | CC-MAIN-2015-35 | refinedweb | 6,489 | 55.64 |
You can subscribe to this list here.
Showing
8
results of 8
Still unable to get this to run at all.
running OneShot.cgi from command line i got a traceback leading to
FieldStorage.py that assumes that there was a request method.
i changed it
def parse_qs(self):
# cx debug
if self._environ.has_key('REQUEST_METHOD'):
self._method = string.upper(self._environ['REQUEST_METHOD'])
else:
self._method = "GET"
then running it from command line i get:
status: 301 Redirect
location: .//
content-type: text/html
<html>
<head>
<title>301 Moved Permanently</title>
</head>
<body>
<h1>Moved Permanently</h1>
<p> The document has moved to <a href=".//">.//</a>.
</body>
</html>
running from the browser i still get an internal server error.
i still am not sure why i got it to work before !!! under 1.5.2 even.
(many of the contexts were broken but...)
i would like to see if i can get this running for my own purposes.
imho a low-performance (low-traffic) one shot Webware is a good thing to
have.
it certainly would make an attractive entry point for many people (non $
commercial bizness) who don't want to commit to a jsp server or CF or ASP.
i am looking for a good, very OOP thing for my own site, and am not going to
get a 'real' box of my own.
for clients, i can't recommend any system that requires a full time person
to care for it. i write things that work and keep working without further
geekage.
in many cases a full blown app server is much more than they need, but they
might well grow into needing it.
-felix
Oops...
>>aspn/activestate.com/ASPN/Cookbook/Python/Recipe/52558<<
Should be
aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558
...Edmund.
Mike wrote:
>>But if it's something that must be persistent and should not be
recreated, how do you guarantee the module won't be reloaded by some
other part of Webware? Somebody yesterday asked a similar question.<<
There are a few ways to do this. See,
question on "How do I do the Singleton Pattern in Python?", and also a more
extensive set of ways in
aspn/activestate.com/ASPN/Cookbook/Python/Recipe/52558
...Edmund.
At 7:42 AM -0500 1/20/02, Aaron Held wrote:
.
Thanks. I found login() and will explore its use with my host. If it
comes down to it, I know that they provide use of (but not source
access to) a formmail cgi script that doesn't require authentication
and I suppose that I could hack things to use that instead, but would
rather keep things in python if possible.
Richard Gordon
--------------------
Gordon Design
Web Design/Database Development.
-Aaron
----- Original Message -----
From: "Richard Gordon" <richard@...>
To: <webware-discuss@...>
Sent: Saturday, January 19, 2002 5:56 PM
Subject: [Webware-discuss] ErrorEmailServer Authentication Problem
> hi
>
> I decided to go ahead and activate the EmailErrors part of
> Application.config, but ran into a little problem that I thought
> someone here may have overcome in the past. Basically, it turns out
> that my virtual host uses authentication for smtp and if
> ErrorEmailServer is just set to mail.mydomain.com, I get
> SMTPSenderRefused raised when an error occurs that webkit is
> attempting to notify me about. I thought that maybe smtp worked like
> ftp does and you could just expand the ErrorEmailServer string to
> something like username:password@..., but smtplib
> thinks that the ':' signifies a port and doesn't like this, so I
> guess not.
>
> So anyway, can anyone share the magic chant with me that works around
> this? Thanks.
>
> Richard Gordon
> --------------------
> Gordon Design
> Web Design/Database Development
>
>
>
> _______________________________________________
> Webware-discuss mailing list
> Webware-discuss@...
>
On Sat, Jan 19, 2002 at 04:33:10PM -0800, Tavis Rudd wrote:
> On Saturday 19 January 2002.
>
> That won't work (or at least the example won't) because the property
> 'foo' would mask the method 'foo'.
The property shouldn't care, it got the getter code object before the
name disappeared. As for users, we can add a first step of:
rename .foo() -> getFoo()
foo = getFoo
so users won't have to change their servlets until the properties are
ready.
> > Tavis, can you post the .field algorithm you were considering?
>
> ??? I have no idea what you're referring to ;)
I mean, how you were going to transform foo/setFoo into properties:
what all the existing pieces would morph into. If not the way I
described, then how?
> > 2) Sometime later, migrate the docstrings into the properties.
> I believe the transition should proceed in one fell swoop if at all.
> These docstrings a crucial part of the documentation.
True, but doing it piecemeal would help to control for errors at
each stage. Also, how often do people actually use the docstring
objects anyway, rather than reading them in the source? Anyway,
we can make quick-and-dirty docstrings thus:
doc = "GET SYNTAX:\n%s\n---\nSET SYNTAX:\n%s" % \
(getFoo.__doc__, setFoo.__doc)
foo = property(getFoo, setFoo, none, doc)
for now and pretty it up later.
--
-Mike (Iron) Orr, iron@... (if mail problems: mso@...) English * Esperanto * Russkiy * Deutsch * Espan~ol
On Sat, Jan 19, 2002 at 06:38:14PM -0600, Ian Bicking wrote:
>.
That was another thing I was going to say. The big hurdle is switching
the clint code and servlets to .transaction instead of .transaction(),
and .field[] instead of .field()[]. After that, we can improve the
implementation however we want and it will work transparently.
--
-Mike (Iron) Orr, iron@... (if mail problems: mso@...) English * Esperanto * Russkiy * Deutsch * Espan~ol.
Then, while old servlets still won't work, it would be relatively easy
to change all ".foo(" occurances to ".getFoo(", and I think that would
probably be a fairly robust translation (as long as we keep track of all
names that have to be changed).
For plain attributes we'd have to leave the little dummy methods
around. But that's not a big deal. We could add some notation to the
doc string of these dummy functions so that the automatic property adder
doesn't mess with them.
Ian | http://sourceforge.net/p/webware/mailman/webware-discuss/?viewmonth=200201&viewday=20 | CC-MAIN-2014-15 | refinedweb | 1,016 | 75 |
# The Implementation of a Custom Domain Name Server by Using С Sockets
### Abstract
We describe the implementation of a custom Domain Name System (DNS) by using C socket programming for network communication, together with SQLite3 database for the storage of Internet Protocol (IP) for Uniform Resource Locator (URL). Then we provide a performance analysis of our implementation. Our code is available publicly [1].
### Introduction
The DNS is used to retrieve IP addresses corresponding to a given URL. IP is essential for web browsing: the user specifies a human-friendly URL address to the browser and then, before loading the corresponding web page, the URL firstly translated into IP address. To perform this action, DNS servers are used.
DNS server is a database containing URL addresses and their corresponding IP addresses. Due to the large amount of the URL, the DNS server is organized as a distributed hierarchical database. In certain cases, DNS suffer from the problem of high load that results in long delays between user requests and server response and affects user experience.
To overcome the problem of high load, custom DNS servers are introduced. The custom DNS server is used to store the most frequently visited user web pages. That mechanism provides high-speed performance.
In Figure 1 we illustrate the interaction of a custom DNS server with an existent global DNS system. In the presence of a custom DNS server, the request of the user web browser first goes to a custom DNS server. If the custom DNS server already has the IP of the requested web page then it just returns it and the browser loads the web page. Observe, in that case, the custom DNS server does not contact other servers, thereby reducing the execution time of performing the user request. If custom DNS does not have the IP of the requested web page, it contacts the local DNS server.
Figure 1. The high-level view of the DNS server working principal.The paper is organized as follows: first, in section 2 we describe the key implementation aspects of a custom DNS server with section 2.1 covering the stack of technologies we use, section 2.2 covering the programming aspects of C sockets. Then in section 3, we provide the performance analysis of our implementation. Next in section 4, we make program testing. In section 5 we outline the limitations of the project. Finally, in section 6 we conclude the work that has been done.
### Implementation of a Custom DNS Server
We below explain the key implementation aspects of the DNS server.
#### Used Technologies and Network Configuration
The list of technologies used in our implementation is listed in Table 1.
| | |
| --- | --- |
| Technology | Description |
| SQLite3 | Database, that stores corresponding IP and domain name addresses. |
| C sockets | Standard C library, used for network communication. |
| UDP | Transport protocol, used for sending DNS queries. |
| Dig (Domain Information Groper) | Command-line tool for querying DNS servers. |
Table 1. List of technologists, used in our application
#### Custom DNS Implementation
The core of a DNS server is a database that stores pairs of IPs and URL addresses, described in Figure 2.
Figure 2. SQLite 3 database system used in the project.We organized the internal structure in the database in 5 columns: domain\_name column stores the domain name of the server, which IP address should be resolved;
ip1, ip2, ip3, ip4 - first, second, third, fourth 4-bit fields of IPv4 address, associated with the domain name.
For the security issues, we limit the size of the database to 1 GB for avoiding extensive enlarging the database.
Our custom DNS server can be accessed via the following IP and port numbers.
| | |
| --- | --- |
| Access information (IP and port) | Description |
| Port | 9000 |
| IP address | The IP address of the host that runs custom DNS (127.0.0.1 in case of running server locally). |
Table 2. Access information for connecting to custom DNS.
When the client requests the IP, the custom server first checks if the requested mapping of hostname to IP is located in the SQLite 3 database. In case IP is stored in a database, the server retrieves it and responds to the user. In case if IP is not present in the database, the custom server makes a request to the local DNS server. We provide the illustration in Figure 3.
When the custom server fails to retrieve an IP from the custom DNS database, it makes a call to the local DNS server. After searching IP in its database, the local server returns it to the custom server, which saves information to the SQLite 3 database and only then returns it to the user.
Figure 3. Principle of working of our Custom DNS serverThe list of functions used in our implementation is listed in Table 3.
| | | |
| --- | --- | --- |
| Function name | Function argument | Description |
| 1. `dig` | IP address (e.x. `@127.0.0.1`) and port (e.x. `-p 9000`) to connect to a custom DNS server. | The command-line tool, used for DNS server communication. |
| 2. `int get_A_record_from_sqlite` | `u_int8_t addr[4]` - pointer to a resolved IP address; `const char domain_name[]` - domain name (or URL), received from the user. | The function that is used for searching IP addresses in database SQLite3.Returns 0 in case of success, 1 in case of failure: loss of database connection, etc. |
| 3. `int local` | `char *argv[]` - pointer to the domain name, that is sent to the local DNS server. | The function that is used for sending DNS queries to local DNS.Returns 0 in the case of success, 1 in case of failure. |
| 4. `sqlite3::insert` | | The function that is used for putting IP addresses into a database. Implementation of the function consists of API SQLite3: `sqlite3_prepare_v2` and `sqlite3_step`, used for parameter substitution. |
Table 3. List of functions, used in our application
### Performance analysis
We next provide a static analysis of the custom DNS application. We measure the processing time of the DNS requests using `time` command from the standard C-library`time.h` .
We evaluate performance in the following cases:
1. If IP presents in the storage of custom DNS - it immediately sends the requested IP address to the client;
2. If IP not present in the custom server database - it should be retrieved from the local server and then sent to the client;
3. Otherwise, in case of an invalid IP address, the user should receive an empty DNS packet.
We measured the execution time on the 3 cases and reported the results in Figure 4.
Figure 4. Measuring response time of various use cases.We observe that a custom DNS server, having an IP address in the database, provides a huge performance gain, compared to the case when the IP is retrieved from a local DNS server (8 msec. compared to 200 msec.) and in the case of invalid IP address - 20 msec.
### User Interface and Usage
We next describe detailed instructions on running a custom DNS server and provide an example of its usage.
The commands provided are suitable for Linux based operating systems only. Also, It is important to have a C compiler to run the application. Launching a DNS server should be done by command:
`$ gcc -o main -lsqlite3 main.c && ./main`.
Accessing to the DNS server via terminal can be done by a command: dig @ -p A.
After compiling a custom DNS server and asking it IP address of URL [www.habr.com](http://www.habr.com) (by command dig @127.0.0.1 -p 9000 www.habr.com A), a user could see logs, created by the server, in Figure 5; and client logs - in Figure 6.
Figure 5. Logs from the DNS server, obtained from resolving domain name ([www.habr.com](http://www.habr.com)) to IP address (178.248.237.68).
Figure 6. DNS packet, received from the server by client, containing resolved IP address (178.248.237.68) of ([www.habr.com](http://www.habr.com)) domain name.
### Limitations of the Project
We next describe the limitations of the project.
For the simplicity of the project, we limit the functionality of the server. Firstly, the server is not constantly accessible to clients - it could process only one query at a time and then exits the program. Secondly, the server does not support concurrent fulfilling queries, so multiple users can not access it. Thirdly, the server only supports A type of queries. Moreover, the server can run only on Linux-based systems due to special libraries which are working only on that family of the operating system.
### Conclusion
We proposed the implementation of a DNS server that handles request IP and domain name conversion among clients. We discovered a decrease of latency of DNS resolving using a built-in SQLite 3 database that caches recently retrieved IP addresses. During the project, we deeply studied the main principles of the DNS resolution process, C socket programming API and best practices of working with database systems. However, more knowledge is needed to optimize our application.
### Reference list:
1. <https://github.com/homomorfism/dns_server>
**Authors:** *Dariya Vakhitova, Arslanov Shamil (@homomorfism)*
*Innopolis University, 2021* | https://habr.com/ru/post/559884/ | null | null | 1,672 | 57.16 |
Getting Started With Nuxt.js.
We’re going to assume that you have not used it before, as such it will start from the ground-up — introducing you to Nuxt.js, its file structure and how routing works. While also touching how you can get it to work with Vuex.
At the end of this tutorial, you should be able to go on to build basic web applications in Nuxt.js, and if you have been wondering how to get started with Nuxt.js, this will do justice to that.
This article is targeted at those that are fairly familiar with Vue.js and it’s a concept, For those without knowledge of Vue.js, consider starting from the official Vuejs documentation and The Net Ninja’s Vuejs playlist.
What Is Nuxt.js?
According to their official page:
great developer experience in mind.”
It allows you to create three types of applications, depending on the purpose it’s intended for:
Static Generated pages (Pre-rendering)
Static generated applications do not require API requests to fetch the contents of the pages, i.e. the contents are already included in the HTML file. An example of a static site is a portfolio website or a landing page for a product.
Single Page Application
Most JavaScript frameworks (React, Angular, Emberjs, Vue, etc) are single page application whose contents are dynamically populated with faster transitions. Most SPAs make use of the HTML5 history API or the location Hash for routing.
Server Side Rendered Applications (SSR)
Server-Side Rendering is a technique used to fetch and display client-side data on the server to send a fully rendered page to the client. This is a good approach to get good SEO for your application.
Creating Your First Nuxt.js Application
You can create a Nuxt.js application in two ways:
- Using the scaffolding tool
create-nuxt-app.
- From scratch.
In case you just want to see the finished app that we would be building, here’s a link to the GitHub repo.
In this tutorial, we would be focused on using
create-nuxt-app so let’s get started. If you have npx installed, open your terminal and run this command:
$ npx create-nuxt-app nuxt-tutorial-app
or
$ yarn create nuxt-app nuxt-tutorial-app
For the purpose of this tutorial,
nuxt-tutorial-app is the name of the application but feel free to name yours differently.
This would be followed by a list of options that help in configuring your application with what you might need for development.
Here’s what my configuration looks like:
For the purpose of this tutorial, we do not need axios, linting and Prettier configurations.
Once that is done, we’ll run the following command in our terminal:
$ cd nuxt-tutorial-app $ npm run dev
Your app should now be running on and this is what you should see:
At this point, your app is ready for development.
Understanding Nuxt Folder Structure
Scaffolding the application as we did creates different files and folders which we can start working with. For someone who hasn’t work with Nuxt before, this might throw you off balance. So we’ll be looking at the folders, getting to understand their importance.
- Assets
This folder is for un-compiled files such as images, font files, SASS, LESS or JavaScript files. Let us add create a
stylesfolder and a
main.cssfile and copy and paste the following in it.
a { text-decoration: none; color: inherit; cursor: pointer; } .header { width: 100%; max-width: 500px; margin-left: auto; margin-right: auto; height: 60px; top: 0; position: sticky; background-color: #fff; display: flex; justify-content: space-between; align-items: center; } .logo { width: 40%; max-width: 200px; height: 40px; } .logo .NuxtLogo { max-width: 30px; margin-left: 10px; max-height: 40px; } .nav { width: 60%; height: 40px; display: flex; justify-content: space-between; padding-right: 10px; max-width: 300px; } .nav__link { width: 80px; display: flex; align-items: center; border-radius: 4px; justify-content: center; height: 100%; border: 1px solid #00c58e; cursor: pointer; } .nav__link:active { background-color: #00c58e; border: 1px solid #00c58e; color: #fff; box-shadow: 5px 3px 5px 2px #3f41468c; } .home { padding-top: 30px; } .home__heading { text-align: center; } .directories { display: flex; box-sizing: border-box; padding: 10px; max-width: 1000px; margin: 0 auto; flex-wrap: wrap; justify-content: center; } @media (min-width: 768px) { .directories { justify-content: space-between; } } .directory__container { width: 100%; max-width: 220px; cursor: pointer; border-radius: 4px; border: 1px solid #00c58e; display: flex; height: 60px; margin: 10px 5px; margin-right: 0; justify-content: center; align-items: center; } .directory__name { text-align: center; } .directory { width: 100%; margin: 50px auto; max-width: 450px; border-radius: 4px; border: 1px solid #00c58e; box-sizing: border-box; padding: 10px 0; } .directory__info { padding-left: 10px; line-height: 22px; padding-right: 10px; }
The styles above will be used across the application for what we’ll be building. As you can see we have styles for the navigation and other aspects which we’ll plug into the application as we progress.
- Components
This folder is one we’re familiar with from Vue.js, it contains your reusable components.
Now, let’s create our first component and name it
navBar.vue, and add the following code to it. We want the navbar of the site to display the logo and link to the Home and About pages which we will create in future. This navbar will be visible across the application. It will also make use of some styles that we have added above.
<template> <header class="header"> <div class="logo"> <nuxt-link <Logo /> </nuxt-link> </div> <nav class="nav"> <div class="nav__link"> <nuxt-linkHome</nuxt-link> </div> <div class="nav__link"> <nuxt-linkAbout</nuxt-link> </div> </nav> </header> </template> <script> import Logo from "@/components/Logo"; export default { name: "nav-bar", components: { Logo } }; </script> <style> </style>
The template section contains what will be visible to the user. We have a
header element which contains our logo and nav links. For us to link to the pages, we make use of
nuxt-link which provides navigation between component pages.
In the script section, we import the
logo component using Nuxt alias
@ and declared it in our component for use by adding it as a component. This makes it possible for us to render it in the template.
- Layout
Here, we’ll be storing our application layouts. This is particularly useful if your application’s design calls for two or more layouts, e.g. one for authenticated users and another for guests or admins. For the purpose of this tutorial, we’ll be sticking to the default layout.
Let us open our
default.vue file and add our
navBar component to the layout of our application.
<template> <div> <Nav /> <nuxt /> </div> </template> <script> import Nav from "~/components/navBar.vue"; export default { components: { Nav } }; </script>
In the template section, we’ve added our
Nav component inside the layout container to always appear at the top after importing it into the file and declaring it in the script section.
The next thing after our
Nav component is
<nuxt />, which tells Nuxt where to render all its routes.
This
Nav component is the one we created above. By adding it here, the
Nav component will be used across the application.
Middleware
This folder was created to house JavaScript files that are required to run before a page(s) is rendered. If you’ve ever used the Vuejs navigation guard, this folder was created for files like that.
Pages
This is another folder that developers with Vuejs background would not be familiar with. It works in such a way that every
*.vuefile is created as a route in your application so it serves as both views and a router folder at the same time, we’ll talk more about this in the next section.
Plugins
This is where you store files that you want to run before mounting the root Vue.js application. It is not a required folder so it can be deleted.
nuxt.config.js
This file is used to configure your application, it is usually pre-populated based on the config when creating your app. An ideal nuxt.config.js file should look like this by default:
export default { mode: 'universal', /* **: [ ], /* ** Nuxt.js modules */ modules: [ ], /* ** Build configuration */ build: { /* ** You can extend webpack config here */ extend (config, ctx) { } } }
Each time a change is made to this file, your application will automatically restart to reflect the changes. Let’s go over what the properties used in the file mean.
- Mode
The type of application; either
universalor
spa. By selecting universal, you’re telling Nuxt that you want your app to be able to run on both the server-side and the client-side.
- Head
All the default meta tags properties and favicon link found inside the
headtag in your app is found here. This is because Nuxt.js doesn’t have a default
index.htmlfile, unlike Vue.js.
All Nuxt applications come with a default loader component and the
colorcan be customized here.
- css
You’re expected to enter the link to all your global CSS files so your application can take it into account when mounting the application. We’re going to add the link to our css file to this and restart our application.
/* ** Global CSS */ css: ["~/assets/styles/main.css"]
- plugins
This is where you connect all the plugins in your plugins folder to the application. It takes in an object with properties such as
srcthat accepts the file path to the plugin and a
modethat configures how your application treats such plugin; either as a server-side plugin or a client-side plugin. For example:
{ src: '~/plugins/universal-plugin.js' }, // for server and client plugins { src: '~/plugins/client-side.js', mode: 'client' }, // for client only plugins { src: '~/plugins/server-side.js', mode: 'server' }, // for server side only plugins
This is important to avoid error either on the server-side or client-side especially if your plugin requires something like
localStorage that is not available on the server-side.
For more info about the
nuxt.config.js file, check out the official doc.
Nuxt Pages And Routing System
The pages folder in your Nuxt application is used to configure your application’s routes, i.e. your route name is dependent on the name of each file in this folder, e.g. if you have an
about.vue file inside your pages file, it means you now have an
/about route in your app, but that’s not all. What happens if you want a dynamic route for your application? Or a nested route? How do you go about it? let’s find out.
Basic Routes
Basic routes can be classified as routes that do not require extra configuration for them to work. For example, a direct route
/work or a
/contact route. So if your pages folder looks like this:
pages/ --| me/ -----| index.vue -----| about.vue --| work.vue --| contact.vue --| index.vue
Nuxt would automatically generate a router config that looks like this:
router: { routes: [ { name: 'index', path: '/', component: 'pages/index.vue' }, { name: 'work', path: '/work', component: 'pages/work' }, { name: 'contact', path: '/contact', component: 'pages/contact' }, { name: 'me', path: '/me', component: 'pages/me/index.vue' }, { name: 'me-about', path: '/me/about', component: 'pages/me/about.vue' } ] }
These paths can then be used to access the components tied to them. You can see that the path does not contain
pages. And Nuxt handles the components named
index.vue as it should without an additional config for that.
Nested Routes
To create a nested route, create a folder called dashboard inside the pages folder. This folder should contain all the files you want to nest in it. For example, user.vue and settings.vue. Then at the root of pages folder, create a file called dashboard.vue.
pages/ --| me/ -----| index.vue -----| about.vue --| dashboard/ -----| user.vue -----| settings.vue --| dashboard.vue --| work.vue --| contact.vue --| index.vue
This would automatically generate a router with routes that look like this:
router: { routes: [ { name: 'index', path: '/', component: 'pages/index.vue' }, { name: 'work', path: '/work', component: 'pages/work' }, { name: 'contact', path: '/contact', component: 'pages/contact' }, { name: 'me', path: '/me', component: 'pages/me/index.vue' }, { name: 'me-about', path: '/me/about', component: 'pages/me/about.vue' }, { name: 'dashboard', path: '/dashboard', component: 'pages/dashboard.vue', children: [ { name: 'dashboard-user', path: '/dashboard/user', component: 'pages/dashboard/user.vue' }, { name: 'dashboard-settings', path: '/dashboard/settings', component: 'pages/dashboard/settings.vue' } ] } ] }
Notice that the route name always follows a regular pattern:
name of the folder + '-' + name of the file
With this, you can be sure that each route will have a unique name.
Dynamic Routes
Dynamic routes are routes that are defined by a variable, this variable can either be a name, number or an
id gotten from client data on the app. This comes in handy when working with an API, where the
id will likely be the
id of the item coming from the database.
In Nuxt, dynamic routes are defined by appending an
_ to a file name or folder name in the pages folder. For instance, if you want a dynamic route whose variable name is id, all you need is to name your file
_id.vue and Nuxt automatically creates a dynamic route for you. For example:
pages/ --| me/ -----| index.vue -----| about.vue -----| _routeName -------| index.vue -------| info.vue --| dashboard/ -----| user.vue -----| settings.vue --| dashboard.vue --| work.vue --| _id.vue --| contact.vue --| index.vue
This would automatically create a router file with the following routes,
{ name: 'work', path: '/work', component: 'pages/work' }, { name: 'contact', path: '/contact', component: 'pages/contact' }, { name: 'id', path: '/:id', component: 'pages/_id.vue' } { name: 'me', path: '/me', component: 'pages/me/index.vue' }, { name: 'me-about', path: '/me/about', component: 'pages/me/about.vue' }, { name: 'me-routeName', path: '/me/:routeName', component: 'pages/me/_routeName/index.vue' }, { name: 'me-routeName-info', path: '/me/:routeName/info', component: 'pages/me/route.vue' }, { name: 'dashboard', path: '/dashboard', component: 'pages/dashboard.vue', children: [ { name: 'dashboard-user', path: '/dashboard/user', component: 'pages/dashboard/user.vue' }, { name: 'dashboard-settings', path: '/dashboard/settings', component: 'pages/dashboard/settings.vue' } ] } ] }
Although some of the Vue.js router tags work in Nuxt and can be used interchangeably, it is recommended that we use Nuxt router components. Here are some of the differences between the Nuxt Router tags and Vue.js Router tags.
Difference between vue.js router and nuxt.js router
At this point, Here’s what your app should look like this, with the navigation shown at the top.
Now that we understand how Nuxt pages and Routes work, let’s add our first page and route
about.vue. This page would list some directories in the application with a link to a new page that shows more information about such directory.
Let us add the following code to: [ { id: 0, name: "The Assets Directory", info: "By default, Nuxt uses vue-loader, file-loader and url-loader webpack loaders for strong assets serving. You can also use the static directory for static assets. This folder is for un-compiled files such as images, font files, SASS, LESS or JavaScript files" }, { id: 1, name: "The Components Directory", info: "The components directory contains your Vue.js Components. You can’t use asyncData in these components." }, { id: 2, name: "The Layouts Directory", info: "The layouts directory includes your application layouts. Layouts are used to change the look and feel of your page (for example by including a sidebar). Layouts are a great help when you want to change the look and feel of your Nuxt.js app. Whether you want to include a sidebar or having distinct layouts for mobile and desktop" }, { id: 3, name: "The Middleware Directory", info: "The middleware directory contains your Application Middleware. Middleware lets you define custom functions that can be run before rendering either a page or a group of pages (layouts)." }, { id: 4, name: "The Pages Directory", info: "The pages directory contains your Application Views and Routes. The framework reads all the .vue files inside this directory and creates the application router. Every Page component is a Vue component but Nuxt.js adds special attributes and functions to make the development of your universal application as easy as possible" }, { id: 5, name: "The Plugins Directory", info: "The plugins directory contains your Javascript plugins that you want to run before instantiating the root Vue.js Application. This is the place to register components globally and to inject functions or constants. Nuxt.js allows you to define JavaScript plugins to be run before instantiating the root Vue.js Application. This is especially helpful when using your own libraries or external modules." }, { id: 6, name: "The Static Directory", info: "The static directory is directly mapped to the server root (/static/robots.txt is accessible under) and contains files that likely won’t be changed (e.g. the favicon). If you don’t want to use Webpack assets from the assets directory, you can create and use the static directory (in your project root folder)." }, { id: 7, name: "The Store Directory", info: "The store directory contains your Vuex Store files. The Vuex Store comes with Nuxt.js out of the box but is disabled by default. Creating an index.js file in this directory enables the store. Using a store to manage the state is important for every big application. That’s why Nuxt.js implements Vuex in its core." } ] }; } }; </script> <style> </style>
Starting from the
script section, we created an array which we store in the
directories variable. Each array contains an object with
id,
name, and
info. This is the data we’ll show to the user when this page is opened. We want to show it to the user such that the names are clickable.
We do that in the
template section, using
v-for to loop through the array. This makes it possible to get each item in the array, which we can access using
directory. In the loop, we use
nuxt-link to handle the linking of each time. Using
nuxt-link, we pass the details (
id,
name and
info) of each directory item via nuxt router. We do this because we want to be able to display this on the show page when the user clicks on an item.
If you navigate to the
/about route using your browser, you should see something like this:
Now, let’s create a new file and name it
_id.vue. This would automatically create a dynamic route that takes the
id param from the link display a little information about any directory clicked on from the About page.
Let us add this to our file:
<template> <section class="directory"> <h1 class="directory__name">{{ directory.name }}</h1> <p class="directory__info">{{ directory.info }}</p> </section> </template> <script> export default { name: "directory-info", data() { return { directory: this.$route.params.dir }; } }; </script> <style> </style>
What we have done is to create a page that fetches data from the route param
dir using the
this.$route.params. This gets us the
name and
info of the clicked directory, which we then display to the user.
So if you click on any directory link (e.g. store directory), you should see this.
But there’s a problem, if you refresh this page, your directory info gets lost and you get an error. This would be fixed using our Vuex Store so let’s dive into it.
Using Vuex Store In Nuxt
Vuex can be accessed in Nuxt using two modes:
- Classic mode (deprecated).
- Modules mode.
Modules mode
Nuxt automatically creates a Store folder upon the creation of your app. In Modules mode, Nuxt would treat every file inside this folder as a module but
index.js is required for Vuex store to be activated in your app. So let’s create an
index.js file in our store folder and set it up for use. Let us add the following to our file.
index.js
export const state = () => ({ }) export const getters = { } export const mutations = { } export const actions = { }
All we have done is to set up the store for our file with all we might need; the
state for storing data,
getters for performing extra manipulation to our
state,
mutations for modifying our
state and
actions for committing mutations.
Nuxt also allows users to separate each core concept into different files which means we can have
store.js,
getters.js,
mutation.js and
action.js and this is good as it makes for easy maintainability. Now, we fix the problem of directory disappearing on refresh, we’ll use the store, but first, we need to install and set up
Vuex persist for our store.
Install
Vuex persist from npm using either command below, depending on your preference.
$ npm install --save vuex-persist
or
$ yarn add vuex-persist
After installing, we’re going to create a
vuex-persist.js file in our plugins folder and add the following:
import VuexPersistence from 'vuex-persist' export default ({ store }) => { window.onNuxtReady(() => { new VuexPersistence({ storage: window.localStorage }).plugin(store); }); }
Here, we import our plugin from
node-modules and configure it to save your store in
localStorage. This plugin allows you to choose other storage options such as
sessionStorage too so feel free to explore their documentation for more info.
Remember to add it to your
nuxt.config.js file.
/* ** Plugins to load before mounting the App */ plugins: [{ src: '~/plugins/vuex-persist', mode: 'client' }],
Here, we added the file path to our plugin and told Nuxt to only run this plugin on the
client side of this application.
Now, we can set our store up to accept and store directory info. Update your store to handle directory info like this:
export const state = () => ({ directory: '' }) export const getters = { } export const mutations = { saveInfo(state, payload) { state.directory = payload.directory } } export const actions = { }
What we’ve done is to add a
directory state to our store and a mutation function
saveInfo that modifies the value of the
directory state we added to our store in anticipation of the data we’d be passing it soon.
Next, in your
about.vue file, update it to look like: [ //remains the same ] }; }, methods: { storeDirectoryInfo(dir) { this.$store.commit("saveInfo", { directory: dir }); } } }; </script> <style> </style>
Now, we’ve added a click event to every directory container that passes the directory info as an argument to the
storeDirectoryInfo. In this function, we commit the directory object to our store.
Finally, we would go back to our
_id.vue file and replace the directory variable with our data from the store like this:
<template> <section class="directory" v- <h1 class="directory__name">{{ directory.name }}</h1> <p class="directory__info">{{ directory.info }}</p> </section> </template> <script> import { mapState } from "vuex"; export default { name: "directory-info", computed: { ...mapState(["directory"]) } }; </script> <style></style>
Here, we refactor our code to use directory object directly from our store by first importing
mapState from Vuex.
import { mapState } from 'vuex';
Instead of first checking if
this.$route.params.dir is
undefined before accessing the data from our store, we decide to use our store by reading the data that’s in the store.
<script> import { mapState } from "vuex"; export default { name: "directory-info", computed: { ...mapState(["directory"]) } }; </script>
Then we update our template to make sure it doesn’t render while
directory is undefined.
<template> <section class="directory" v- <h1 class="directory__name">{{ directory.name }}</h1> <p class="directory__info">{{ directory.info }}</p> </section> </template>
On doing this, no matter how many times we refresh our app, our directory object is safe in our store and can be easily accessed using the
…mapState(['stateVariable']) method.
Deploying To Heroku
Now that our
nuxt-tutorial-app app is complete, what’s next? Deploying our shiny new app to production.
We’ll be deploying our Nuxt.js app to Heroku using Github for easy deployment so if you’ve not set up a repository for your app, now would be a time to do so. The next thing would be to open Heroku and create a new app, choose a name and connect it to GitHub and the repo created above. Next, go to your settings, you should see something like this.
Now, add the following config variables.
NPM_CONFIG_PRODUCTION=false HOST=0.0.0.0 NODE_ENV=production
The next thing we have to do is to create a
Procfile in the root folder of our app (same level as
nuxt.config.js) and enter this command:
web: nuxt start
This will run the
nuxt start command and tell Heroku to direct external HTTP traffic to it.
After adding the
Procfile to your app, commit and push your changes to your repo. If you have automatic deploys enabled for your app, your app should be live and accessible from its URL. If you can see your app live, congratulations! 🎆 you have successfully built and deployed your first Nuxt.js application.
Conclusion
Now that we know how to create a basic Nuxt application and deploy to Heroku, what’s next? Here are some resources that cover things like using Axios in Nuxt and implementing authentication in your app.
- Using the axios module.
- Implementing Authentication in Nuxt.
- Nuxt.js official documentation.
nuxt-tutorial-appGithub repo.
| https://www.smashingmagazine.com/2020/04/getting-started-nuxt/ | CC-MAIN-2021-21 | refinedweb | 4,180 | 56.96 |
Verify and Debug Linux Infrared Remote Control (LIRC) Daemon Configurations
Introduction: Verify and Debug Linux Infrared Remote Control (LIRC) Daemon Configurations
Introduction
After training LIRC daemon to recognise the signals of my infrared (IR) remote control unit and configuring LIRC client to respond accordingly, sometimes stuff didn't happen as expected when you click on the IR remote control unit.
irw program can be used to verify and debug why LIRC clients don't respond as expected. The program "irw" is a type of LIRC client and it is provided by LIRC package.
Scope
This instructable will show how to use irw program to verify and debug why LIRC clients don't respond as expected.
Target Readers
Anyone with a Raspberry Pi running on RaspbianOS
Step 1: Verify the Mapping of Button Click to LIRC Event
Open terminal emulator in Raspberry Pi
$sudo service lirc start $irw<br>
Point the infrared remote control unit at the Raspberry Pi.
Click a button or buttons.
irw will display IR codes and its mapped LIRC events as shown in the screenshot
Open another terminal emulator in Raspberry Pi
Open the LIRC daemon configuration as shown in the screenshot
vi /etc/lirc/lircd.conf
Compare the entries in /etc/lirc/lircd.conf with the output of program irw
The program irw will display the LIRC event (KEY_STOP, KEY_RESTART) that corresponds to the IR code sent by the remote control unit, /etc/.lirc/lircd
Verify that this LIRC event matches what you or the LIRC client is expecting.
Hi Mirza,
Not sure if you can help me to debug a problem that I have after installing
lirc in my Raspbery pi. I checked your above. It works fine. When I press a key
from remote it output some as follow.
0000000000ff4ab5 00 key_0 /home/pi/lircd.conf
which I think is correct.
Fyi, I configured lirc following this url.-...
I want to use IR by a python program I created.
The python code is as follows
--------------------------------------------------------
import lirc
sockid = lirc.init("ir_test3, blocking = False)
codeir = lirc.nextcode()
print codeir # test point 1
if codeir:
if codeir[0] == 'ONE':
print ONE # test point 2
--------------------------------------------------------------
the lircrc is as follows
--------------------------------------------------
begin
button = key_1
program = ir_test3
config = ONE
end
------------------------------------------------
I ran the ir_test3 python and then I expected if I press key_1 of the remote
it to goto lircrc and look for key_1 and come back to ir_test3 and print ONE.
But it prints [] which I assume NULL. That is from test point 1 of ir_test3.
It never goes to test point 2
Could you please help to troubleshoot what went wrong.?
Regards
Ziath Nazoordeen | http://www.instructables.com/id/Verify-and-Debug-Linux-Infrared-Remote-Control-LIR/ | CC-MAIN-2017-51 | refinedweb | 437 | 71.44 |
Start with a new project
We’re going to extend the new React + Web API project template, and build a really simple Twitter style app, using React. when we all decide to switch to Blazor ;-)).
Here are the two features we’re going to build:
- Show a list of tweets
See? I said we’d keep it dead simple!
Prerequisites
You’ll need the latest version of Visual Studio 2019 or Visual Studio Code and I think you can probably follow along if you’re using JetBrains Rider too.
Make sure you have the latest version of .NET Core 2.x or 3.x SDK installed (either will work). If you have VS 2019 the SDK should already be installed for you, if not, go grab it here.
We can’t get very far without a project so if you haven’t already, create a new .net core React project now…
If you’re using Visual Studio, use the ASP.NET Core Web Application project template…
Choose a folder location etc. then, when prompted, select React.js as the web application type.
Leave the other settings as the are (make sure you have No Authentication selected) and you should be good to go.
Alternatively, you can also create this project via the command line…
dotnet new react
This will create the new project in whichever folder you’re in when you run the command…
I called my project “MyTweets”…
You should end up with a project which looks like this…
Run this now and you’ll get the starter project running in your browser.
What is React really for?
React.js is a UI library.
The word “Library” is important here; the React team would point out it isn’t a “framework”.
You won’t get dependency injection, custom controls or routing “out of the box”.
But you do get a really handy toolkit for managing the state of your user interface.
There may be a little bit of logic in your React components, but this is presentation logic (show this, hide that) not business logic.
Your business logic lives elsewhere.
This is good news! It means, once you master how to build your application reliably, using clean architecture that adapts and scales, you’re free to try different UI options without breaking your business logic every time a hot new JS framework comes along.
A simply be the tweet’s contents (text).
If you look at your new React ClientApp folder you’ll notice a subfolder called src. Inside here you’ll find a components folder.
Add a new directory to this called Tweets.
Add a new javascript file to this Tweets folder (in Visual Studio you can click Add Item, or just create a file with a .js extension).
Call this new component List.js.
Now, to turn this into a React component, we need to add the following boilerplate.
import React from 'react'; export default class List extends React.Component { render() { return (<h1>Hello world</h1>); } }
That’s it; your first component!
This is about as simple as a React component can get; we’ve got a javascript class which extends
React.Component and exposes a
render method.
The
render method is responsible for, well, rendering our user interface; in this case a simple heading which says “Hello World”.
But wait a minute, we’ve created a nice simple component, but until it’s rendered somewhere we have no way to see it in action.
To remedy that we can turn our component into a “page” and make it possible to route directly to it; for example, by navigating to
http://<your-app-here>/tweets.
Head over to App.js and you’ll find this render method…
render() { return ( <Layout> <Route exact path='/' component={Home} /> <Route path='/counter' component={Counter} /> <Route path='/fetch-data' component={FetchData} /> </Layout> ); }
Every path mentioned here is configured to render a specific component. So if you navigate to
/counter in your application you’ll end up seeing the
Counter component and so on…
Let’s add a route for our tweets list…
render() { return ( <Layout> <Route exact path='/' component={Home} /> <Route path='/counter' component={Counter} /> <Route path='/fetch-data' component={FetchData} /> <Route path='/tweets' component={List} /> </Layout> ); }
React won’t magically know where our component lives (in the components/Tweets folder) so we can give it a helping hand using an
import statement.
Add this
import statement to the top of App.js.
import List from './components/Tweets/List';
With that in place, run your app and navigate to
/tweets to see your work come to life in the browser!
Show me some tweets
Hello World is all well and good, but what about that list of tweets we promised?!
Replace the contents of List.js with the following markup…
import React from 'react'; export default class List extends React.Component { render() { return ( <> <h3>Tweets</h3> <div className="card mb-2"> <p className="card-body"> This is a tweet </p> </div> <div className="card mb-2"> <p className="card-body"> This is a tweet </p> </div> </>); } }
We have some hardcoded duplication for now, but essentially this is the UI we’re aiming for; a list of tweets using Bootstrap’s
card styles to render the contents of a tweet.
The React project template includes Bootstrap CSS hence we are able make this look half decent simply by referencing a few CSS classes.
NB:
class is a reserved word in javascript and so we have to use
className instead whenever we want to specify a CSS class, but otherwise this is pretty much standard HTML.
Test it out in the browser to see how we’re shaping up.
What’s in a component?
React is all about components.
We’ve made it possible to navigate directly to our Tweet List component using a route, but we could just as easily render it on any other “page” (component) in our application.
Try it now; head over to Home.js and update it to include a reference to our
List component.
import React, { Component } from 'react'; import List from './Tweets/List'; export class Home extends Component { static displayName = Home.name; render () { return ( <div> <p>Hello World - here are some tweets!</p> <List /> </div> ); } }
Try running this and navigate to your application’s root URL in the browser…
Nice! We have successfully mangled our homepage and crowbarred in a list of tweets!
Who said UI design was hard ;-)
Next up we’ll look at refactoring this component and driving it from state (instead of hardcoded markup). | https://jonhilton.net/react/new-project/ | CC-MAIN-2022-05 | refinedweb | 1,090 | 63.9 |
In my first article of SharePoint webpart
(Developing and Deploying Custom Web Parts for SharePoint Portal 2007) CustomWebpartSharepoint.aspx
I have discuss how to make the custom web part, in that case you have to make the class library project and do all work at code behind, even you have to write the code to render the controls. This really a very cumbersome and time taking task. But not need to worry at all, SharePoint has introduce one new way to make the webparts, which is very easy, in that you just need to make user control in asp.net and deploy that usercontrol in SharePoint, so my this article will show you all steps of development and deployment of usercontrol.
B. Developing
1. To get started with creating Usercontrol in Microsoft Visual Studio 2005, Open the IDE and create a new C# project, Select Asp.net web application as Project Type. Name It as UserControl_WebPart.
2. Add the usercontrol (ascx) and web page (aspx) in the project and provide the name for usercontrol – ‘UsercontrolWebPart’, now do what you want to do with, I have just putted the Login control in my example. After that test your usercontrol by running it with the web page.
3. Add the reference of Mirosoft.sharepoint.DLL to the project.
4. Add new class into the project named – UCwebpart.cs, which basically deploy the Usercontrol into the SharePoint.
5. Following is the description of the code.
a. A a. add following these two Namespaces.
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
b. Inherit the class from the WebPart class.
public class UCwebpart : WebPart
c. Provide the following two variables, which provide the address of the usercontrol.
private UsercontrolWebPart usercontrol;
private string error = "";
private string Pathofusercontrol = @"/";
d. Add the method ‘CreateChildControls’, which load the usercontrol in the sharepoint.
protected override void CreateChildControls()
{
try
{
string tooldir = this.Page.Request.MapPath(Pathofusercontrol);
string[] textArray1 = null;
try
{
textArray1 = Directory.GetFiles(tooldir);
}
catch (Exception exception1)
{
error += string.Format(exception1.ToString());
return;
}
usercontrol = (UsercontrolWebPart)this.Page.LoadControl(Pathofusercontrol + @"UsercontrolWebPart.ascx");
Controls.Add(usercontrol);
}
catch (Exception CreateChildControls_Exception)
{
error += "CreateChildControls_Exception 2: " + CreateChildControls_Exception.Message + " - Path is" + Pathofusercontrol.ToString() + "--End";
}//end catch
base.CreateChildControls();
}
e. Add the methid ‘RenderContents‘, which render the contents of the usercontrol.
protected override void RenderContents(HtmlTextWriter writer)
{
try
{
base.RenderContents(writer);
}
catch (Exception RenderContents_Exception)
{
error += RenderContents_Exception.Message;
}
finally
{
if (error.Length > 0)
{
writer.WriteLine(error);
}
}
}
6. Give your assembly a strong name. Just go into the Project Properties and then go to the "Signing" tab (see Figure 1) to do this. Alternatively, you can use the sn.exe command line tool to generate strong names for you.
7. Add new one xml file to the project and provide the following contents to it.
<?xml version="1.0" encoding="utf-8" ?>
<pre><webParts>
<webPart xmlns="">
<metaData>
<type name="UserControl_WebPart.UCwebpart, UserControl_WebPart, Version=1.0.0.0,Culture=neutral,
PublicKeyToken=#################" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">Web Part</property>
<property name="Description" type="string">
</property>
<property name="ChromeType">TitleOnly</property>
<property name="ChromeState"><city w:<place w:Normal</place /></city /></property>
<property name="ItemLimit" type="int">15</property>
<property name="ItemStyle" type="string">Default</property>
</properties>
</data>
</webPart>
</webParts>
NOTE: change the value public key token, which you will find when deploy the dll into the GAC folder.
The final contents are here of the project.
C. Deployment
1. Deploy the assembly to the Assembly Folder (GAC) (requires the assembly to be strong named). Drag and Drop the assembly (dll) file, Named UserControl_WebPart.dll from source folder to the Gac Folder (C:\WINDOWS\ASSEMBLY).
2.The Assembly (dll), UserControl_WebPart.dll will be copied in to GAC folder.
3. Now take the public key token for the UserControl_WebPart.dll assembly (dll), select the file first and then click mouse right button, and select the properties.
4. The properties will open and then select the public key token, copy it, and paste the key into any text file.
5. Drag Drop the UsercontrolWebPart.ascx User Control.
\C:\Inetpub\wwwroot\wss\VirtualDirectories\80
6. Open the web.config file of the SharePoint application from the following path.
7. Add the following attribute, in the last of <sharepoint><safecontrols> element.
>
8. Now replace the public key token, copied from GAC, with the existing key highlighted in yellow color.
>
9. Run the SharePoint application and open the Home Page and go to SiteAction->SiteSetings, then click the on the Modify all site Settings link.
10.Click on the Web Parts link under the Galleries section.
11. After opening the web part gallery click on new button, highlighted in the following figure.
12. Click on the upload button.
13. A new screen window will appear, where you have to provide the XML file, which you have created in the project before, and yes please change the value of attribute PublicKeyToken in the xml file.
14. After clicking on ok button of the previous screen, again new window will appears, where you can provide the value of webpart.
15. After clicking on ok button, you will go back to the webpart gallery, where you can check that your web part name appears with small new icon.
16. Click on SiteNavigation->EditPage.
17. Now click on “Add Web Part” link, as shown in the following figure.
18. Then a new window will appear from where you can add your web part.
19. Mark the check box of your web part and click on add button, after you will go back to you page, where you will find your web. | https://www.codeproject.com/Articles/43574/SharePoint-Asp-net-user-control-as-a-Webpart?fid=1551559&df=90&mpp=25&sort=Position&spc=None&noise=1&prof=True&view=None | CC-MAIN-2017-22 | refinedweb | 929 | 50.63 |
Quite a few powerful vector graphics formats were available before SVG was first imagined around 2001. Postscript and its cousin PDF are widely used in many applications. More application-specific formats include Postscript-based Adobe Illustrator (.ai), CorelDRAW (.cdr), Computer Graphics Metafile (.cgm), Windows Metafile (.wmf), Autocad (.dxf), Hewlett-Packard Graphics Language (.hpgl), WordPerfect (.wpg), and many others. For vector drawings that can even incorporate animation, sound, and interactivity, Macromedia's SWF/Flash is common for content distributed on the World Wide Web.
The main thing that distinguishes SVG from all these other formats is that it is an application of XML. While this means that an equivalent graphic will probably be described considerably more verbosely in SVG than in most other vector formats, it also means that SVG is more versatile to programmatic manipulation. In particular, you can manipulate SVG within Web browsers (or other applications) using ECMAScript and the Document Object Model (DOM). And just as importantly, you can transform and produce SVG using familiar XML techniques like XSLT, or with XML support libraries. You can mix SVG with other XML formats using namespaces. Moreover, you can even stylize SVG using Cascading Style Sheets (CSS). Overall, SVG is a friendly player in XML and Web space.
Beyond being an XML format, SVG is also a fully open standard published by the W3C (see Resources). Unlike most of the vector formats mentioned above, SVG is free of any patent or copyright restrictions, and its specification is fully documented. Like other W3C standards, the specification document itself is copyrighted -- but under W3C's non-restrictive terms that allow for widespread and no-cost reproduction and utilization (for example, no non-disclosure agreements are attached to reading the specification).
A nice thing about SVG is that you can view it in most modern Web browsers, either natively or through plug-ins. The exact state of support is somewhat in flux, but with the right mojo you should be able to view SVG using Firefox/Mozilla, KHTML (Konqueror and Safari), Opera, or Amaya. Using plug-ins from Adobe or Corel you can even coax Internet Explorer into displaying SVG. A number of standalone viewers for SVG also exist, especially utilizing the Free Software Batik SVG Toolkit (part of the Apache XML project -- see Resources).
In many cases, you will view SVG files as standalone documents. In such instances, these files will be served as MIME type
image/svg+xml, and will generally have the file extension .svg. Gzip compressed SVG files should have the extension .svgz, and are directly supported by most SVG-enabled tools. An SVG file is just an XML file with an appropriate DTD. You will see this declaration in several examples below.
However, perhaps even more commonly, you can embed an SVG document within a larger document, particularly within an XHTML page. Other compound XML formats, such as OASIS OpenDocument, also do (or will support) embedding SVG within them. You can include an SVG graphic within an (X)HTML page in three ways:
- Through the
<object>tag
- Through the
<embed>tag
- As an embedded namespace
Unfortunately, exactly which of these actually works depends on your browser and version. For example, I created the following XHTML document (with a doctype intended to support namespace nesting):
Listing 1. XHTML document (svg-nested.html)
Safari/KHTML does the best of the browsers I tried. Even so, the results are better if the file is named with an .html extension than with an .xml extension. Overall,
<embed> seems like the most successful approach. You might see the document rendered something like this:
Figure 1. Web browser displaying svg-nested.html
Incidentally, the examples I present in this article are rather simple combinations of basic shapes, text, colors, and such -- but SVG is fully capable of representing complex and attractive drawings. Just to comfort readers, here is the famous PostScript tiger picture that's included with Ghostscript nd other tools, rendered using SVG (I only touched up its overall sizing):
Figure 2. Web browser displaying tiger image as SVG
Features of SVG documents
The prior XHTML example (see Listing 1) showed you a very basic SVG drawing. The external file that is referenced (standalone.svg) contains the same elements as those embedded in the XHTML, minus the extra namespace qualifier in the tags. SVG gives you a number of graphic primitives, and each primitive has various XML attributes that further specify the graphic: color, size, position, fill, outline, and so on. However, explicit graphic primitives, such as ellipses, rectangles, or polygons -- or more sophisticated
<path> elements that might include cubic or quadratic Bezier curves -- are often included within
<g> elements to group several primitives together. The nice thing about a
<g> group is that you can scale, move, style, and otherwise modify it as a whole. Modifications to the group generally apply to the collection of shapes within them (including nested
<g> groups). This is especially useful when SVG documents are scripted.
One thing to notice about SVG documents is that they are not really XML all the way down. Syntactically, SVG is indeed XML, but a significant portion of the information content of an SVG drawing is contained within comma- and space-delimited data inside SVG attributes. When I mention information content, I am not speaking of XML Infoset, but only of the more informal concept of What does it contain? Doing it this way is a reasonable compromise, since using child elements for every point or handle that defines a curve would make SVG even more verbose. But XML-level processing techniques like XSLT can thereby not really do much with path data. For example, this is a quadratic Bezier path element:
And this is a polygon describing a pentagram:
Earlier, I mentioned that you can use CSS selectors and syntax to modify the appearance of SVG drawings. As with HTML and other CSS-supporting formats, you can either specify CSS information inline or as a reference to an external stylesheet. A very simple example of inline CSS is:
Listing 2. A simple CSS example (inline-styled.svg)
While you can certainly style an entire tag using CSS, you'll probably find that using class selectors is a better use of CSS and SVG. For example, you might define a variety of types of rectangles within a stylesheet, then attach a
class XML attribute to each one in your drawing, rather than repeat the full list of colors, fills, strokes, and other attributes that you define for the class. By simply changing the stylesheet, you can change the overall look of your diagram to make it more suitable for a different context.
Beyond the use of CSS, Listing 2 illustrates another nice feature of SVG: You can include predefined content within an SVG document -- content that is defined either within or outside of the document being rendered.
One way to use predefined content as part of an SVG drawing is with the
<image> element. In concept,
<image> in SVG is very similar to
<img> in HTML: The element simply instructs the rendering client to draw the content of an external image -- which may itself be either SVG or a raster image in JPEG or PNG format -- inside the current SVG context. You can size and position the external image almost as if it were a regular graphic element. For example:
Listing 3. Include an external SVG drawing within the current image
Perhaps more interesting than the
<image> tag are the complimentary elements
<defs> and
<use>. The first, which you saw with the CSS example,
lets you create SVG elements that are not directly rendered when defined -- normally the SVG rendering model draws
each object in exactly the order it occurs within an SVG document, each overlaying the last. But
<style> is a bit atypical in that you cannot really render it later, per se.
You can include whatever graphic elements you like in a
<defs> section, including
<g> groups and
<symbol> elements (symbols are similar to groups; this article does not have room to address that distinction). Outside the definition, you can
<use> the graphic elements defined in a
<defs>
section -- even the
<defs> section of an external SVG document. For example:
Listing 4. Using predefined graphic elements
In Listing 4, the same defined rectangle is rendered with two different transformations, then an externally defined element is also rendered (the
id name suggests it is also a rectangle, but you do not know for sure from this fragment -- in fact, the external content might change between renderings).
As I mentioned, SVG is scriptable using ECMAScript. In principle, this lets SVG documents interact with user actions. To aid the Web-application space, SVG also contains an HTML-like
<a> element for hyperlinks. A simple interaction in SVG modifies a document based on mouse clicks on particular graphic elements. The example in Listing 5 is trivial, but you could easily let an SVG graphic respond, for example, to clicks on regions of a map or objects in a flow chart:
Listing 5. Let an SVG shape respond to clicks
You can also use ECMAScript and the DOM to animate SVG graphics. For example, the code in Listing 6 produces a nice looking effect of text that grows and changes opacity:
Listing 6. Animate SVG with JavaScript
Using ECMAScript gives you full programming flexibility, but if all you want is animation, SVG has
<animate> and related tags (such as
<animateMotion> or
<animateColor>). These are quite flexible, and allow you to animate each element of an SVG document independently and in various ways. For example, the code in Listing 6 produces the same grow-and-become-opaque effect as the technique shown in Listing 5:
Listing 6. Animating with SVG alone
This article has touched on just a few basics of the SVG format. Writing it has been enough to make me quite excited about SVG as a format. The Web really needs a vector format for efficiently conveying complex graphics in a scale-independent way. Throwing in scripting, animation, linking, and all the rest just makes SVG that much more useful. And luckily, most Web browsers now have pretty good SVG support, so no real obstacle exists to deploying graphics and simple Web applications based on SVG.
- Explore the W3C's full specification of for SVG; it's quite readable as standards documents go.
- Want more details on SVG? Take a look at these articles and tutorials on developerworks:
- "Introduction to Scalable Vector Graphics" (March 2004)
- "Interactive, dynamic Scalable Vector Graphics" (June 2003)
- "Add interactivity to your SVG" (August 2003)
- "Bring Scalable Vector Graphics to life with built-in animation elements" (June 2003)
- Visit SVG.org, a community Web site that aims to bring all SVG users, developers, and enthusiasts to a single place on the Web.
- Read Wikipedia's entry on SVG. This is a good place to find updated links to many of the tools that support or utilize SVG, including most of those mentioned in this article.
- Visit the OASIS page for the OpenDocument format. This open format is currently supported by OpenOffice.org, and will become the standard format for KOffice as well. An earlier installment of XML Matters discussed the use of XML in office or word processor documents. Uche Ogbuji also covered the OpenOffice file format in his Thinking XML column here on developerWorks.
- Check out Graphviz, a free software tool for creating circle-and-arrow diagrams (such as hierarchical, directed, or entity-relationship) from an elegant abstract language for describing diagrams. Graphviz includes an SVG export capability.
- Download Batik a Java technology-based SVG Toolkit from Apache.
- Try Skencil, a free software interactive vector drawing application written in Python that supports import and export of SVG (as well as many other formats).
- Find all previous installments of David's XML Matters column on the column summary page.
- Browse for books on these and other technical topics.
- Learn how you can become an IBM Certified Developer in XML and related technologies.
>>IMAGE. | http://www.ibm.com/developerworks/xml/library/x-matters40/ | crawl-003 | refinedweb | 2,004 | 52.7 |
Duplicates a series of connected edges (edgeLoop)
Turn the construction history on or off (where applicable). If construction history is on then the corresponding node will be inserted into the history chain for
the mesh. If construction history is off then the operation will be performed directly on the object. Note:If the object already has construction history then
this flag is ignored and the node will always be inserted into the history chain.
Defines how to evaluate the node. 0: Normal1: PassThrough2: Blocking3: Internally disabled. Will return to Normal state when enabled4: Internally disabled. Will
return to PassThrough state when enabled5: Internally disabled. Will return to Blocking state when enabledFlag can have multiple arguments, passed either as a
tuple or a list.
Choose between 2 different types of splits. If this is set to 0 then the split type will be absolute. This is where each of the splits will maintain an equal
distance from the associated vertices. If this set to 1 then the split type will be relative. This is where each split will be made at an equal percentage along
the length of the edge.
Derived from mel command maya.cmds.polyDuplicateEdge
Example:
import pymel.core as pm
pm.polyTorus()
pm.polyDuplicateEdge( 'pTorus1.e[121:126]', of=0.5 )
pymel.core.modeling.polyDuplicateAndConnect
pymel.core.modeling.polyEditUV
Enter search terms or a module, class or function name. | http://www.luma-pictures.com/tools/pymel/docs/1.0/generated/functions/pymel.core.modeling/pymel.core.modeling.polyDuplicateEdge.html#pymel.core.modeling.polyDuplicateEdge | crawl-003 | refinedweb | 231 | 59.4 |
Tasklist error in Windows Server 2008 R2 .
- Thursday, November 15, 2012 1:24 PM
Hi
When trying to list the tasks list in command prompt through tasklist.exe , got an error like "Error : Not Found " .
Also found that none of the WMI dependent components is working . Eg : msinfo32 , systeminfo failed to load the information .
Looks like WMI repository is corrupted .
Any help is much appreciated .
Regards,
Raja.
All Replies
- Thursday, November 15, 2012 3:13 PM
the command
winmgmt.exe /verifyrepository
will tell you the state of your WMI.
winmgmt /? will also give you options to correct if anything is wrong.. if you get the output for the above command as inconsistent.. then the following switch will help.
. MOF files that contain the
#pragma autorecover preprocessor statement are restored to the
repository.
regards,
paras pant.
- Friday, November 16, 2012 3:56 AM
Paras - Thanks for your response .
WMI was inconsistent and Now fixed the issue .
But I would like to know what would be the cause for inconsistency and is there any impact on rebuilding the WMI in a production server.
Do you have any idea on this .
Regards,
Raja.
- Friday, November 16, 2012 12:22 PM
that's a tricky one.. WMI is a component that is used by multiple applications/components both built in Windows and the ones that you install.
trying to find as to what caused the issue will be tricky.. but if the issue continues to happen then tracking may be done... there are multiple methods to track this and we cannot have a generalised troubleshooter. however starting with the event viewer is always good.
WMI is based on WBEM and built on DCOM. so you should also check if there are issues with DCOM on your server.
I would advice you to open a support ticket with Microsoft if the issue is persistent.
ideally rebuilding the repository should not cause fatal issues with the server OS, but you may notice errors with application which have registered or compiled there MOF's and namespaces.
these can be later re-compiled manually.
regards,
paras pant.
- Monday, November 19, 2012 7:16 AMThanks paras for the information. | http://social.technet.microsoft.com/Forums/en-US/winservergen/thread/721d7109-9097-4049-b740-c4fefa3de230 | CC-MAIN-2013-20 | refinedweb | 360 | 68.47 |
Java method readInt
Provide a Java class named "Input" containing the method "readInt" (prototype given below) that displays the prompt string, reads an integer, and tests whether it is between the supplied minimum and maximum. If not, it prints an error message and repeats the entire process.
public static int readInt(Scanner in, String prompt, String error, int min, int max)
Use the following class as the main class for testing the implementation.
import java.util.Scanner;
/**
This program prints how old you'll be next year.
*/
public class AgePrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int age = Input.readInt(in, "Please enter your age",
"Illegal Input--try again", 1, 150);
System.out.println("Next year, you'll be " + (age + 1));
}
}
Solution Preview
Please rename the attached 470518-AgePrinter.java to AgePrinter.java before compiling and executing it.
A sample session with given program looks like following.
$ java AgePrinter
Please enter your age
200
Illegal Input--try again
Please enter your age
-1
Illegal Input--try again
Please enter your age
99
Next year, you'll be ...
Solution Summary
Provided code has been tested with command line version of Java binaries from Java SDK v1.7.0_u3 . | https://brainmass.com/computer-science/java/java-method-readint-470518 | CC-MAIN-2017-39 | refinedweb | 203 | 57.37 |
- Actors: A Short Tutorial
Created by phaller on 2007-05-24. Updated: 2008-08-28, 09:46
Introduction.
The Scala Actors library provides both asynchronous and synchronous message sends (the latter are implemented by exchanging several asynchronous messages). Moreover, actors may communicate using futures where requests are handled asynchronously, but return a representation (the future) that allows to await the reply.
This tutorial is mainly designed as a walk-through of several complete example programs that can be readily compiled and run using Scala 2.4 or newer.
First Example
Our first example consists of two actors that exchange a bunch of messages and then terminate. The first actor sends "ping" messages to the second actor, which in turn sends "pong" messages back (for each received "ping" message one "pong" message).
We start off by defining the messages that are sent and received by our actors. In this case, we can use singleton objects (in more advanced programs, messages are usually parameterized). Since we want to use pattern matching, each message is a case object:
case object Ping case object Pong case object Stop
The ping actor starts the message exchange by sending a Ping message to the pong actor. The Pong message is the response from the pong actor. When the ping actor has sent a certain number of Ping messages, it sends a Stop message to the pong actor.
All classes, objects and traits of the Scala actors library reside in the scala.actors package. From this package we import the Actor class that we are going to extend to define our custom actors. Furthermore, we import all members of the Actor object since it contains many useful actor operations:
import scala.actors.Actor import scala.actors.Actor._
Actors are normal objects that are created by instantiating subclasses of the Actor class. We define the behavior of ping actors by subclassing Actor and implementing its abstract act method:
class Ping(count: int, pong: Actor) extends Actor { def act() { var pingsLeft = count - 1 pong ! Ping while (true) { receive { case Pong => if (pingsLeft % 1000 == 0) Console.println("Ping: pong") if (pingsLeft > 0) { pong ! Ping pingsLeft -= 1 } else { Console.println("Ping: stop") pong ! Stop exit() } } } } }
The number of Ping messages to be sent and the pong actor are passed as arguments to the constructor. The call to the receive method inside the infinite loop suspends the actor until a Pong message is sent to the actor. In that case the message is removed from the actor's mailbox and the corresponding action on the right side of the arrow is executed.
In the case where pingsLeft is greater than zero we send a Ping message to pong using the send operator !, and decrement the pingsLeft counter. If the pingsLeft counter has reached zero, we send a Stop message to pong, and terminate the execution of the current actor by calling exit().
The class for our pong actor is defined similarly:
class Pong extends Actor { def act() { var pongCount = 0 while (true) { receive { case Ping => if (pongCount % 1000 == 0) Console.println("Pong: ping "+pongCount) sender ! Pong pongCount = pongCount + 1 case Stop => Console.println("Pong: stop") exit() } } } }
There is one interesting point to notice, however. When receiving a Ping message, a Pong message is sent to the sender actor, which is not defined anywhere in our class! In fact, it is a method of the Actor class. Using sender, one can refer to the actor that sent the message that the current actor last received. This avoids having to explicitly pass the sender as arguments to messages.
After having defined our actor classes, we are now ready to create a Scala application that uses them:
object pingpong extends Application { val pong = new Pong val ping = new Ping(100000, pong) ping.start pong.start }
Analogous to Java threads, actors have to be started by calling their start method.
Let's run it!
The complete example is included in the Scala distribution under doc/scala-devel/scala/examples/actors/pingpong.scala. Here is how you compile and run it:
$ scalac pingpong.scala $ scala -cp . examples.actors.pingpong Pong: ping 0 Ping: pong Pong: ping 1000 Ping: pong Pong: ping 2000 ... Ping: stop Pong: stop
Make it Thread-less!
Actors are executed on a thread pool. Initially, there are 4 worker threads. The thread pool grows if all worker threads are blocked but there are still remaining tasks to be processed. Ideally, the size of the thread pool corresponds to the number of processor cores of the machine.
When actors call thread-blocking operations, such as receive (or even wait), the worker thread that is executing the current actor (self) is blocked. This means basically that the actor is represented as a blocked thread. Depending on the number of actors you want to use, you might want to avoid this, since most JVMs cannot handle more than a few thousand threads on standard hardware.
Thread-blocking operations can be avoided by using react to wait for new messages (the event-based pendant of receive). However, there is a (usually small) price to pay: react never returns. In practice, this means that at the end of a reaction to a message, one has to call some function that contains the rest of the actor's computation. Note that using react inside a while loop does not work! However, since loops are common there is special library support for it in form of a loop function. It can be used like this:
loop { react { case A => ... case B => ... } }
Note that react calls can be nested. This allows to receive several messages in sequence, like this:
react { case A => ... case B => react { // if we get a B we also want a C case C => ... } }
To make our ping and pong actors thread-less, it suffices to simply replace while (true) with loop, and receive with react. For example, here is the modified act method of our pong actor:
def act() { var pongCount = 0 loop { react { case Ping => if (pongCount % 1000 == 0) Console.println("Pong: ping "+pongCount) sender ! Pong pongCount = pongCount + 1 case Stop => Console.println("Pong: stop") exit() } } }
Second Example
In this example, we are going to write an abstraction of producers which provide a standard iterator interface to retrieve a sequence of produced values.
Specific producers are defined by implementing an abstract produceValues method. Individual values are generated using the produce method. Both methods are inherited from class Producer. For example, a producer that generates the values contained in a tree in pre-order can be defined like this:
class PreOrder(n: Tree) extends Producer[int] { def produceValues = traverse(n) def traverse(n: Tree) { if (n != null) { produce(n.elem) traverse(n.left) traverse(n.right) } } }
Producers are implemented in terms of two actors, a producer actor, and a coordinator actor. Here is how we can implement the producer actor:
abstract class Producer[T] { protected def produceValues: unit protected def produce(x: T) { coordinator ! Some(x) receive { case Next => } } private val producer: Actor = actor { receive { case Next => produceValues coordinator ! None } } ... }
Note how the producer actor is defined! This time we did not bother to create an extra subclass of Actor and implement its act method. Instead, we simply define the actor's behavior inline using the actor function. Arguably, this is much more concise! Moreover, actors defined using actor are started automatically--no need to invoke their start method!
So, how does the producer work? When receiving a Next message, it runs the (abstract) produceValues method, which, in turn, calls the produce method. This results in sending a sequence of values, wrapped in Some messages, to the coordinator. The sequence is terminated by a None message. Some and None are the two cases of Scala's standard Option class.
The coordinator synchronizes requests from clients and values coming from the producer. We can implement it like this:
private val coordinator: Actor = actor { loop { react { case Next => producer ! Next reply { receive { case x: Option[_] => x } } case Stop => exit('stop) } } }
Note that inside the handler for the Next message, we use reply to return a received Option value to some requesting actor. We are going to explain this in the next section, so stay tuned...
The Iterator Interface
We want to make producers usable as normal iterators. For this, we implement an iterator method that returns--surprise!--an iterator. Its hasNext and next methods send messages to the coordinator actor to accomplish their task. Take a look:
def iterator = new Iterator[T] { private var current: Any = Undefined private def lookAhead = { if (current == Undefined) current = coordinator !? Next current } def hasNext: boolean = lookAhead match { case Some(x) => true case None => { coordinator ! Stop; false } } def next: T = lookAhead match { case Some(x) => current = Undefined; x.asInstanceOf[T] } }
We use a private lookAhead method to implement the iterator logic. As long as the next value has not yet been looked-up, the current variable has value Undefined which is simply a place-holder object:
private val Undefined = new Object
The interesting bit is in the lookAhead method. When the current value is Undefined it means we have to get hold of the next value. For this, we use the synchronous message send operator !?. It sends the Next message to the coordinator, but instead of returning like a normal (asynchronous) message send, it waits for a reply from the coordinator. The reply is the return value of !?. A message that was sent using !? is replied to using reply. Note that simply sending a message to sender does not work! That's because !? waits to receive a message from a private reply channel instead of the mailbox. This is necessary to distinguish "true" replies from "fake" ones resulting from old messages that happen to be in the mailbox.
The producers example is also included in the Scala distribution under doc/scala-devel/scala/examples/actors/producers.scala. | https://www.scala-lang.org/old/node/242 | CC-MAIN-2020-16 | refinedweb | 1,643 | 64.81 |
Steam-Powered DOTA on Rails
After writing a couple of “serious” articles on building authentication systems with Rails, I decided to have a break and play some games. I just Googled for online games and stumbled upon Dota 2. Dota 2 is an immensely popular (more than 10,000,000 unique players last month) battle arena game developed by Valve.
The game is quite complex and some web services like DotaBuff were created to help players track their progress. After visiting DotaBuff and seeing all of its beautiful tables and graphs, I just couldn’t stop myself from searching for information about the Dota 2 API. The Ruby thing to do is to share my research with you!
In this article, we are going to work with Dota 2 API. We’ll create an app that borrows basic functionality from DotaBuff: a user logs in via Steam and sees a list of his recent matches and statistics. I’ll pinpoint all the gotchas I faced during development of this app and give some advice on how this can be implemented in production.
Source code is available on GitHub.
Working demo can be found at sitepoint-dota.herokuapp.com.
What is Dota?
According to Wikipedia, Dota 2 is a free-to-play multiplayer online battle arena video game. It is the stand-alone sequel to the Defense of the Ancients modification for Warcraft III: The Frozen Throne. Its mechanics are quite complex, so I will just give you a quick overview.
Originally, DotA (Defense of the Ancients) was a custom map for Warcraft III developed by a person called IceFrog. After a couple of years, it became so popular that Valve decided to hire IceFrog and create a standalone version of the game, which they called it Dota 2. It was released in 2013 and now is considered one of the most popular online games in the world. Many professional competitions with money prizes are being held and streams by experienced players are being watched by hundreds of people.
Talking about gameplay, there are two teams (Radiant, good, and Dire, evil) with (typically) 5 players each. At the start of the game, each player picks one hero from a pool containing more than 100 heroes and enters the game. Each team has their base and the ultimate goal is to destroy the main building on the enemy’s base while protecting your own. Players can buy various artifacts (each hero may take up to 6 items at once), kill creeps (creatures, controlled by AI) or enemy heroes to earn gold and experience. Each hero has unique set of abilities that players use to help their teammates or wreck havoc upon enemies. That’s Dota in a nutshell.
Let’s proceed and see what goodies the Dota 2 API present.
Preparations
As always we will do some preparations before proceeding to the interesting part. Create a new Rails app called Doter:
$ rails new Doter -T
I will use Rails 4.2.1 throughout this article, but the same solution can be implemented with Rails 3.
If you wish to follow along, hook up the
bootstrap-sass gem for styling:
Gemfile
[...] gem 'bootstrap-sass' [...]
Run
$ bundle install
and drop these lines into application.scss:
application.scss
@import 'bootstrap-sprockets'; @import 'bootstrap'; @import 'bootstrap/theme';
Now, tweak layout like this:
views/layouts/application.html.erb
<nav class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <%= link_to 'Doter', root_path, class: 'navbar-brand' %> </div> <div id="navbar"> </div> </div> </nav> <div class="container"> <% flash.each do |key, value| %> <div class="alert alert-<%= key %>"> <%= value %> </div> <% end %> <div class="page-header"><h1><%= yield :page_header %></h1></div> <%= yield %> </div>
Add a
page_header helper method to provide content for the
yield block:
application_helper.rb
module ApplicationHelper def page_header(text) content_for(:page_header) { text.to_s.html_safe } end end
Lastly, set up the routes. I’d like to display user’s matches on the main page of the site, so create an empty
MatchesController:
matches_controller.rb
class MatchesController < ApplicationController end
The corresponding model will be added a bit later. Now, the actual routes:
config/routes.rb
[...] root to: 'matches#index' [...]
Don’t forget to create a view for the
index action:
views/matches/index.html.erb
<% page_header 'Your matches' %>
Great, preparations are done and we can move forward!
Authenticating via Steam
Steam, like many other web platforms, supports the OAuth protocol and you can authenticate your user to get their details, like uID, nickname, avatar etc. (you can read my Rails Authentication with OAuth 2.0 and OmniAuth article to learn more about this protocol). You do not have to do that to actually perform Steam API calls, but we need the user’s id to show the list of matches. Therefore, we will use the gem by Rodrigo Navarro that adds a Steam authentication strategy to OmniAuth:
Gemfile
[...] gem 'omniauth-steam' [...]
Don’t forget to run
$ bundle install
Now create Omniauth initializer file:
config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do provider :steam, ENV['STEAM_KEY'] end
Okay, where is this key? Visit this page (you will need Steam account to proceed) and simply register a new key. Among all web platforms supporting OAuth, Steam provides the fastest way to register your application.
Now let’s decide what user information do we want to store. Actually, Steam provides a pretty minimalistic set of data, so we have don’t have many options to choose from. I’m going to stick with the following:
uid(
string, index, unique) – User’s unique identifier.
nickname(
string) – User’s nickname (Steam also provides name).
avatar_url(
string) – Link to user’s avatar. By the way, we can’t choose avatar size.
profile_url(
string) – User’s profile URL on Steam.
Run the following command:
$ rails g model User uid:string nickname:string avatar_url:string profile_url:string
Open the migration file and add this line:
db/migrations/xxx_create_users.rb
[...] add_index :users, :uid, unique: true [...]
after the
create_table method.
Apply the migration:
$ rake db:migrate
Add some routes:
config/routes.rb
[...] match '/auth/:provider/callback', to: 'sessions#create', via: :all delete '/logout', to: 'sessions#destroy', as: :logout [...]
The first one is the callback route where the user will be redirected after a successful authentication. I had to use
match here because, for some reason, Steam seems to be sending a POST request instead of a GET (that’s what most other platforms do). The second route will be used to log the user out.
Now, the controller to handle those routes. I’ll start with the
create action:
sessions_controller.rb
class SessionsController < ApplicationController skip_before_filter :verify_authenticity_token, only: :create def create begin @user = User.from_omniauth request.env['omniauth.auth'] rescue flash[:error] = "Can't authorize you..." else session[:user_id] = @user.id flash[:success] = "Welcome, #{@user.nickname}!" end redirect_to root_path end end
That
skip_before_filter is another gotcha with authentication via Steam. It sends a POST request, but of course it does not provide the CSRF token. Therefore, by default, you will get an error saying that someone is trying to potentially sending malicious data. As such, we have to skip this check for the
create action.
The
create action itself is simple. Fetch the user’s data stored inside
request.env['omniauth.auth'] and create a new user or find an existing one based on said data (we’ll introduce the
from_omniauth method in a moment). If everything is okay, store the user’s id inside the session, set the welcome message, and redirect to the main page.
Now the
from_omniauth method:
models/user.rb
[...] class << self def from_omniauth(auth) info = auth['info'] # Convert from 64-bit to 32-bit user = find_or_initialize_by(uid: (auth['uid'].to_i - 76561197960265728).to_s) user.nickname = info['nickname'] user.avatar_url = info['image'] user.profile_url = info['urls']['Profile'] user.save! user end end [...]
Find a user by his uID or create a new one and then simply fetch all the necessary data. But what is that
76561197960265728 number? This is the third gotcha. While authenticating via Steam, the user’s 64-bit uID will be returned. However, when listing Dota 2 matches, the user’s 32-bit ids are used, instead. There is surely a reason for that, but I wasn’t able to find any explanation. Anyway, we have to convert the 64-bit id to 32-bit and the easiest way to do that is to subtract this large number. Don’t worry, Ruby takes care of BigInt numbers for us transparently, so you don’t have to perform any additional actions.
The
destroy action is even simpler:
sessions_controller.rb
def destroy if current_user session.delete(:user_id) flash[:success] = "Goodbye!" end redirect_to root_path end
We need the
current_user method to check if the user is logged in:
application_controller.rb
[...] private def current_user return nil unless session[:user_id] @current_user ||= User.find_by(id: session[:user_id]) end helper_method :current_user [...]
The
helper_method ensures that this method can be called from the views, as well.
Modify the layout:
views/layouts/application.html.erb
[...] <nav class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <%= link_to 'Doter', root_path, class: 'navbar-brand' %> </div> <div id="navbar"> <% if current_user %> <ul class="nav navbar-nav pull-right"> <li><%= image_tag current_user.avatar_url, alt: current_user.nickname %></li> <li><%= link_to 'Log Out', logout_path, method: :delete %></li> </ul> <% else %> <ul class="nav navbar-nav"> <li><%= link_to 'Log In via Steam', '/auth/steam' %></li> </ul> <% end %> </div> </div> </nav> [...]
I’ve already mentioned that Steam does not allow changing the avatar size, so we have to apply some styling to make look it nice:
application.scss
[...] nav { img { max-width: 48px; } }
You may now restart the server and see this all in action!
Integrating with the Steam API
The next step is integrating with the Steam API. If you need to access the basic Steam Web API, you may use either steam-web-api by Olga Grabek or steam-api by Brian Haberer. However, as long as we are going to work specifically with Dota 2-related stuff, it would be nice to have a separate gem that provides some convenient methods. Fortunately, there is dota gem by Vinni Carlo Canos that provides many useful features (though it is not 100% finished). Before proceeding, you may want to read up on the Dota 2 API. Unfortunately, there is no page with comprehensive and up-to-date documentation on it yet, but here are some resources:
When you are ready, drop the new gem into the Gemfile:
Gemfile
[...] gem 'dota', github: 'vinnicc/dota', branch: 'master' [...]
At the time of writing I had to specify the master branch, because recently we have revealed that some changes were made to Dota 2 API and they are accounted for in the latest pull request, however a new version of the gem is not released yet. By the way, I wanted to warn you that some aspects of Dota 2 API may change from time to time and you should watch out for it.
Run
$ bundle install
Create an initializer:
config/initializers/dota.rb
Dota.configure do |config| config.api_key = ENV['STEAM_KEY'] end
Put the Steam key that you’ve obtained earlier in this file.
Basically, that’s it. You are now ready to perform API requests.
Getting User Matches
I want to get the list of user matches as soon as they authenticate via Steam. However, before we proceed, I wanted to point out one thing. The solution described in this article is implemented for demonstration purposes only. If you want to build a real world application similar to DotaBuff, you will have to implement a more complex system with some background process that constantly checks if there are any new matches played by the specific user (or even if there are any new matches at all) and loads the corresponding data. Then when a user logs in, you simply provide a list of all matches from you local database, not by sending a synchronous call to the Dota 2 API. Loading information for even 40 matches can take up to 1 minute – and users typically have hundreds of them.
It will require loads of storing capacity (just imagine how many matches are being played every day) and obviously I can’t afford to set up such an environment. However, when you do have fair amount of data, you can display really interesting statistical information like what is provided by DotaBuff.
Okay, moving on, what info about a single match can we fetch? Here is the list of available methods that you can utilize. We will store the following:
uid(
string, index) – Unique identifier of the match.
winner(
string) – Which team won the match. Actually, this will either be “Radiant” or “Dire”.
first_blood(
string) – When first blood (first hero kill) occurred. Dota 2 API returns a number of seconds since the match started, but we’ll store a formatted value instead. Feel free to make this column integer and store the raw value instead.
started_at(
datetime) – When the match was started.
mode(
string) – Match mode. Here is the list of all available modes. We are going to store the title of it, but you may also store its ID (Dota 2 API provides both).
match_type(
string) – Type of the match. Here is the list of all available types. Again, you can either store its title or id. Don’t call this column
typebecause it is reserved for single table inheritance!
duration(
string) – Duration of the match. Again, API provides a number of seconds, but we’ll store a formatted value.
user_id(
integer, index) – Foreign key to establish one-to-many relation between matches and users.
Create and apply the migration:
$ rails g model Match uid:string winner:string started_at:datetime mode:string match_type:string duration:string user:references $ rake db:migrate
Make sure you have these lines inside model files:
models/user.rb
[...] has_many :matches [...]
models/match.rb
[...] belongs_to :user [...]
On to the actual match loading. I want to do this as soon as user has logged in:
sessions_controller.rb
[...] def create begin @user = User.from_omniauth request.env['omniauth.auth'] rescue flash[:error] = "Can't authorize you..." else @user.load_matches!(1) session[:user_id] = @user.id flash[:success] = "Welcome, #{@user.nickname}!" end redirect_to root_path end [...]
1 is the number of matches to load. Here is the
load_matches! method:
models [...]
First of all, load matches for the provided player (don’t forget that we use the 32-bit Steam ID here, not 64-bit). Of course, the
matches method does not actually load everything – it has a
limit option set to 100 by default, but we override it with our own value. This method accepts some other options, read more here.
Next we check if a match with that id was already loaded, and, if not, load its data. Why do we have to call the
matches method again, but this time providing the exact match id? The gotcha here is that the first call will return a limited number of fields for performance reasons, so to get the full info we have to query for a specific match.
After that we simply save all the necessary info to the table.
parse_duration formats number of seconds like
xx:xx:xx:
models/user.rb
[...] private [...]
Now just load all the matches:
matches_controller.rb
[...] def index @matches = current_user.matches.order('started_at DESC') if current_user end [...]
and render them:
views/matches/index.html.erb
<% page_header 'Your matches' %> <% if @matches && @matches.any? %> <table class="table table-striped table-hover"> <% @matches.each do |match| %> <tr> <td> <%= link_to match.started_at, match_path(match) %> </td> </tr> <% end %> </table> <% end %>
I’ve decided to provide a minimal set of data on this page and use the
show action to display more detailed info. Let’s introduce a new route:
config/routes.rb
[...] resources :matches, only: [:index, :show] [...]
The controller’s action:
matches_controller.rb
[...] def show @match = Match.find_by(id: params[:id]) end [...]
And now the view:>
Here we provide all the available info. It would be nice to use different colors for Radiant and Dire teams, so I’ve introduced two CSS classes:
application.scss
[...] $radiant: #92A524; $dire: #C23C2A; .dire { color: $dire; } .radiant { color: $radiant; } [...]
That’s pretty nice, but not very informative. Did the user win the match? What hero did they play? What items did they have? How many kills did they have? It would be great to display this info as well, so let’s proceed to the next step and improve our app further!
We can answer all those questions by simply loading information about the players participating in the match. The
radiant and
dire methods called on the
match instance return an array of player objects, each having its own methods. There is a lot of info available here and we are going to store most of it:
match_id(
integer, index) – Foreign key to establish one-to-many relation.
uid(
string) – Player’s 32-bit unique id.
hero(
text) – Player’s hero. This is going to be a serialized attribute storing hero’s id, name and a link to its picture.
level(
integer) – Hero’s level by the end of the match.
kills(
integer) – Player’s kills.
deaths(
integer) – Player’s deaths.
assists(
integer) – player’s assists.
last_hits(
integer) – Player’s last hits (how many creeps has they killed).
denies(
integer) – Player’s denies (how many allied creeps has he denied not allowing enemies receive gold for killing them).
gold(
integer) – Amount of gold player was having by the end of the match.
gpm(
integer) – Gold per minute gained.
xpm(
integer) – Experienced per minute gained.
status(
string) – Status of the player by the end of the match. They may have stayed till the end of the game, abandoned for some reason, left safely (for example, if poor network connection was detected) or never connected to the game.
gold_spent(
integer) – Total amount of gold spent during the match by the player.
hero_damage(
integer) – Total amount of damage dealt to enemy heroes.
tower_damage(
integer) – Total amount of damage dealt to enemy towers.
hero_healing(
integer) – Total amount of healing inflicted to allied heroes.
items(
text) – Serialized attribute containing an array of items that player had by the end of the game. We will store each item’s id, name, and a link to its picture.
slot(
integer) – Player’s slot in the team (from 1 to 5).
radiant(
boolean) – This indicates the player’s team. In the simplest scenario, there are only two possibilities (
radiantor
dire, however it seems that you can be marked as
observer), so I’ve used a boolean attribute, but you may use your own method of storing this info.
That’s a lot of data to store! Create and apply the appropriate migration:
$ rails g model Player match:references uid:string hero:text level:integer kills:integer deaths:integer assists:integer last_hits:integer denies:integer gold:integer gpm:integer xpm:integer status:string gold_spent:integer hero_damage:integer tower_damage:integer hero_healing:integer items:text slot:integer radiant:boolean $ rake db:migrate
Add the following lines to our model files:
models/match.rb
[...] has_many :players, dependent: :delete_all [...]
models/player.rb
[...] belongs_to :match serialize :hero serialize :items [...]
Alter the
load_matches! method like this:
model [...]
The
load_players! method will accept two separate objects with info about Radiant and Dire teams.
model/match.rb
[...] def load_players!(radiant, dire) roster = {radiant: radiant, dire: dire} roster.each_pair do |k, v| v.players.each do |player| self.players.create({ uid: player.id, items: player.items.delete_if { |item| item.name == "Empty" }.map { |item| {id: item.id, name: item.name, image: item.image_url} }, hero: {id: player.hero.id, name: player.hero.name, image: player.hero.image_url}, level: player.level, kills: player.kills, deaths: player.deaths, assists: player.assists, last_hits: player.last_hits, denies: player.denies, gold: player.gold, gpm: player.gpm, xpm: player.xpm, status: player.status.to_s.titleize, gold_spent: player.gold_spent, hero_damage: player.hero_damage, tower_damage: player.tower_damage, hero_healing: player.hero_healing, slot: player.slot, radiant: k == :radiant }) end end end [...]
Each object (
radiant and
dire) responds to a
players method that actually returns an array of players. Much of this method is pretty simple, so I’ll explain the possibly unclear bits.
items: player.items.delete_if { |item| item.name == "Empty" }.map { |item| {id: item.id, name: item.name, image: item.image_url} },
Here we call
items on the
player object to fetch the items that player had by the end of the match.
items returns another object that is an instance of a separate class. This object responds to three main methods:
id (item’s id),
name (item’s name) and
image_url (URL to an item’s picture stored on Dota 2 CDN). Each player has 6 slots to store items. If a slot was empty, the name “Empty” is specified. We don’t really need to save information about empty slots, so simply remove all those elements. After that, generate a hash containing all the info and store it inside the column. Thanks to serialization, later we can fetch this hash and use it normally.
hero: {id: player.hero.id, name: player.hero.name, image: player.hero.image_url},
The idea here is the same.
hero returns a separate object that responds to three main methods:
id (hero’s id),
name (hero’s name) and
image_url (hero’s picture).
Update 05/05/2015
I’ve found out that we can choose the size of hero’s portrait by providing an optional argument to the
image_url method. Here is the list of all possible values:
*
:full – full quality horizontal portrait (256x114px, PNG). This is used by default.
*
:lg – large horizontal portrait (205x11px, PNG).
*
:sb – small horizontal portrait (59x33px, PNG). I recommend using this one as we need the smallest portrait possible.
*
:vert – full quality vertical portrait (234x272px, JPEG). Strangely enough this can only be *.jpg*.
Load the players, grouping them by team –
true for Radiant,
false for Dire. By the way, this seems pseudo-philosophical: Radiant are the good, so they are “true” and Dire are bad, chaotic, so they are “false” :).
matches_controller.rb
[...] def show @match = Match.includes(:players).find_by(id: params[:id]) @players = @match.players.order('slot ASC').group_by(&:radiant) end [...]
Update the view, accordingly:> <h3 class="radiant">Team Radiant</h3> <%= render 'players_table', players: @players[true] %> <h3 class="dire">Team Dire</h3> <%= render 'players_table', players: @players[false] %>
I am using partial to avoid code duplication:
views/matches/_players_table.html.er)</td> .titleize %>"><%= player.uid %></abbr> <% else %> <%= player.uid %> <% end %> </td> <td><%= render 'player_hero', hero: player.hero %></td> <td><%= player.level %></td> <td> <% player.items.each do |item| %> <%= image_tag item[:image], alt: item[:name], title: item[:name] %> <% end %> <>
Let’s move from top to bottom.
info-table is a CSS class to apply some special styling to images inside this table:
application.scss
.info-table { img { width: 30px; } }
The idea here is that all the pictures returned by Dota 2 API are pretty big, so we just make them smaller.
abandoned_or_not_connected? is the method that does pretty much what is says – checks if the players left the game or haven’t connected at all:
models/player.rb
[...] def abandoned_or_not_connected? status != 'played' end [...]
If the player hasn’t stayed till the end of the match, we take note.
player_hero is yet another partial:
views/matches/_player_hero.html.erb
<%= image_tag hero[:image], alt: hero[:name], title: hero[:name] %>
Great! Now this looks much more informative. However, the user still has no easy way to check if they won a match. Let’s fix this!
Who Won?
To find this out, simply have to find out what team a user played for and which team won the match. I’ll tweak the view like this:
views/matches/index.html.erb
<% if @matches && @matches.any? %> <table class="table table-striped table-hover info-table"> <% @matches.each do |match| %> <tr> <td> <%= link_to match.started_at, match_path(match) %> <% if current_user.won?(match) %> <span class="label label-success">won</span> <% else %> <span class="label label-danger">lost</span> <% end %> </td> </tr> <% end %> </table> <% end %>
Introduce the
won? method that accepts the only argument – the
match object:
models/user.rb
[...] def won?(match) player = find_self_in(match) (player.radiant? && match.winner == 'Radiant') || (!player.radiant? && match.winner == 'Dire') end private def find_self_in(match) match.players.find_by(uid: uid) end [...]
Nice! How about showing the player’s hero? Here you go:
views/matches/index.html.erb
<table class="table table-striped table-hover info-table"> <% @matches.each do |match| %> <tr> <td> <%= render 'player_hero', hero: current_user.played_for_in(match) %> <%= link_to match.started_at, match_path(match) %> <% if current_user.won?(match) %> <span class="label label-success">won</span> <% else %> <span class="label label-danger">lost</span> <% end %> </td> </tr> <% end %> </table>
models/user.rb
[...] def played_for_in(match) find_self_in(match).hero end [...]
For production, it is absolutely imperative to use caching here. For example, you could use model caching like this:
def played_for_in(match) Rails.cache.fetch(self.uid + '_played_for_in_' + match.uid) { find_self_in(match).hero } end
Just don’t forget to set up the appropriate flush caching conditions.
Conclusion
We come to the end of this article. We’ve employed basic Dota 2 API methods and created an app to present a user with basic information about their recent matches. Feel free to expand this demo further and share the results!
Working with Dota 2 API is fun and I hoped you liked it, too! Are you interested in seeing the second part on this topic? If so, in the next article I will cover fetching data for live Dota 2 matches.
Thank you for reading. Good luck and have fun (as Dota players say)!
Another awesome article. Great piece of writing
.
Thank you!
Hi. You get it when loggin in I suppose?
Hi. Right
Well, I've browsed logs and seems that the problem is here: Looks like you have no matches therefore
matchesreturns
nil. Could you try logging in once again? If this does help, I'll update the article accordingly.
Ok, login works. But it doesn't show any matches. Maybe because my profile in dota closed
Ah, of course that's the reason. To see some info you have to make it public and allow 3rd party services to access it (it should be somewhere in Dota settings). The code is updated however I've opened this issue to discuss if it is okay for matches to return nil in some scenarios. | https://www.sitepoint.com/steam-powered-dota-on-rails/ | CC-MAIN-2017-51 | refinedweb | 4,373 | 59.8 |
Linearization of Differential Equations
Linearize the nonlinear differential equations and compare the linearized model simulation to the original nonlinear model response.
Exercise 1 - Automobile
Linearize the momentum balance for the velocity of an automobile at steady state conditions when the gas pedal is maintained at 40%.
$). Simulate a step change in the gas pedal position, comparing the nonlinear response to the linear response. Comment on the accuracy of the linearized model.
Solution Help
Python can calculate either analytic (exact) or numeric (approximate) derivatives. This problem is not very complicated but see this video tutorial for SymPy and NumPy tutorials on derivatives.
import sympy as sp
sp.init_printing()
# define symbols
v,u = sp.symbols(['v','u'])
Fp,rho,Cd,A,m = sp.symbols(['Fp','rho','Cd','A','m'])
# define equation
eqn = Fp*u/m - rho*A*Cd*v**2/(2*m)
print(sp.diff(eqn,v))
print(sp.diff(eqn,u))
from scipy.misc import derivative
m = 700.0 # kg
Cd = 0.24
rho = 1.225 # kg/m^3
A = 5.0 # m^2
Fp = 30.0 # N/%pedal
u = 40.0 # % pedal
v = 50.0 # km/hr (change this for SS condition)
def fv(v):
return Fp*u/m - rho*A*Cd*v**2/(2*m)
def fu(u):
return Fp*u/m - rho*A*Cd*v**2/(2*m)
print('Approximate Partial Derivatives')
print(derivative(fv,v,dx=1e-4))
print(derivative(fu,u,dx=1e-4))
print('Exact Partial Derivatives')
print(-A*Cd*rho*v/m) # exact d(f(u,v))/dv
print(Fp/m) # exact d(f(u,v))/du
The differential equation in linear form becomes:
$$\frac{dv(t)}{dt} = \alpha \left(u(t) - 40\right) + \beta \left(v(t)-v_{ss}\right) $$
with the following definitions from the partial derivatives
$$\alpha = \frac{F_p}{m} = 0.042857$$
$$\beta = -\frac{A \, C_d \, \rho \, v_ss}{m} = constant$$
Complete the remainder of this exercise by calculating the steady state velocity `v_{ss}`, the constant `\beta`, and simulating a step response with the linearized and nonlinear models.
Steady State Velocity
The steady state velocity is determined by setting the time derivative to zero, plugging in other steady state conditions, and solving for `v_{ss}`.
$$m\frac{dv(t)}{dt} = F_p u(t) - \frac{1}{2} \rho \, A \, C_d v(t)^2$$
$$0 = F_p u_{ss} - \frac{1}{2} \rho \, A \, C_d v_{ss}^2$$
$$v_{ss} = \sqrt{\frac{2 \, F_p u_{ss}}{\rho \, A \, C_d}}$$
$$v_{ss} = \sqrt{\frac{2 \times 30 \frac{N}{\%} \times 40 \%}{1.225 \frac{kg}{m^3} \times 5 m^2 \times 0.24}} = 40.406 \frac{m}{s}$$
Nonlinear Model Simulation
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# define model
def vehicle(v,t,u,load):
# inputs
# v = vehicle velocity (m/s)
# t = time (sec)
# u = gas pedal position (0%
# for storing the results
vs = np.zeros(nsteps)
# simulate with ODEINT
for i in range(nsteps-1):
u = step[i]
v = odeint(vehicle,v0,[0,delta_t],args=(u,load))
v0 = v[-1] # take the last value as initial condition
vs[i+1] = v0 # store the velocity for plotting
# plot results
plt.figure()
plt.subplot(2,1,1)
plt.plot(ts,vs,'b-',linewidth=3)
plt.ylabel('Velocity (m/s)')
plt.legend(['Velocity'],loc=2)
plt.subplot(2,1,2)
plt.plot(ts,step,'r--',linewidth=3)
plt.ylabel('Gas Pedal')
plt.legend(['Gas Pedal (%)'])
plt.xlabel('Time (sec)')
plt.show()
The next step is to include the linearized model and compare to the nonlinear model response.
Exercise 2 - Thermocouple
Linearize an energy balance that describes the temperature of a thermocouple bead `T_t` given a change in the surrounding gas temperature `T_g`. Include the flame temperature `T_f` as a variable in the linearization. Simulate a cyclical gas temperature change and a step change in flame temperature in both the linear and nonlinear versions of the model.
Some advanced combustion systems operate in a pulsed mode where an acoustic wave resonates in the combustor in order to enhance heat and mass transfer. The frequency of the wave is approximately 100Hz (cycles/sec). As a result, the temperature at any given spatial location in the combustor fluctuates with time. The fluctuations can be approximated as a sine wave with an amplitude of `75^oC` for the system of interest. The objective is to measure the fluctuating temperature at a given point in the reactor with use of a thermocouple.
Heat is transferred to the thermocouple by convection and radiation. Heat transfer by radiation is approximated by `q = A \epsilon \sigma (T_f^4-T_t^4)` where `A` is the surface area, `\epsilon` is the emissivity, and `\sigma` is the Stefan-Boltzmann constant `(W/(m^2 K^4))`. The thermocouple bead is approximated as a sphere (e.g. ignore conduction along connecting wires).
Use the following values with subscript t as the thermocouple, subscript f as the flame, ss indicating steady-state, h as the heat transfer coefficient, cp as the heat capacity, `\rho` as the density, and dt as the diameter of the thermocouple bead.
$$h=2800 \, \frac{W}{m^2 \, K} \quad \rho_{t} = 20 \, g/cm^3 \quad \sigma = 5.67e-8 \, \frac{W}{m^2\,K^4}$$ $$\epsilon=0.8 \quad T_{t,ss} = 1500 \, K \quad T_{f} = 1500 \, K$$ $$c_{p,t} = 0.4 \frac{J}{g\,K} \quad d_t = 0.01 \, cm$$
A starting Python script is available in the solution help. Add the linearized balance equation in addition to the nonlinear balance equation that is already implemented. Simulate both for the cycling gas temperature and discuss whether the linearized model is a suitable approximation of the nonlinear model. What changes could be made to the thermocouple to improve the ability to measure gas temperature?
Solution Help
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# define thermocouple model
def thermocouple(x,t,Tg,Tf):
## States
Tt = x[0]
Tlin = x[1]
## Parameters
h = 2800.0 # W/m^2-K
rho = 20.0 # gm/cm^3
sigma = 5.67e-8 # W/m^2-K^4
eps = 0.8 #
Cp = 0.4 # J/gm-K
d = 0.01 # cm
r = d / 2.0 # radius
A = 4.0 * np.pi * (r/100.0)**2 # sphere area (m^2)
V = 4.0/3.0 * np.pi * r**3 # sphere volume (cm^3)
# acc = inlet - outlet
# acc = m * Cp * dT/dt = rho * V * Cp * dT/dt
# inlet - outlet from 2 heat transfer pathways
# q(convection) = h * A * (Tg-Tt)
# q(radiation) = A * esp * sigma * (Tf^4 - Tt^4)
q_conv = h * A * (Tg-Tt)
q_rad = A * eps * sigma * (Tf**4 - Tt**4)
dTdt = (q_conv + q_rad) / (rho * V * Cp)
dTlin_dt = 0.0 # add linearized equation
return [dTdt,dTlin_dt]
# Flame temperature
Tf0 = 1500.0 #K
# Starting thermocouple temperature
y0 = [Tf0,Tf0]
# Time Intervals (sec)
t = np.linspace(0,0.1,1000)
# Flame Temperature
Tf = np.ones(len(t))*Tf0
Tf[500:] = 1520.0 #K
# Gas temperature cycles
Tg = Tf + (150.0/2.0) * np.sin(2.0 * np.pi * 100.0 * t) #K
# Store thermocouple temperature for plotting
Tt = np.ones(len(t)) * Tf
Tlin = np.ones(len(t)) * Tf
for i in range(len(t)-1):
ts = [t[i],t[i+1]]
y = odeint(thermocouple,y0,ts,args=(Tg[i],Tf[i]))
y0 = y[-1]
Tt[i+1] = y0[0]
Tlin[i+1] = y0[1]
# Plot the results
plt.figure()
plt.plot(t,Tg,'b--',linewidth=3,label='Gas Temperature')
plt.plot(t,Tf,'g:',linewidth=3,label='Flame Temperature')
plt.plot(t,Tt,'r-',linewidth=3,label='Thermocouple')
plt.ylabel('Temperature (K)')
plt.legend(loc='best')
plt.xlim([0,t[-1]])
plt.xlabel('Time (sec)')
plt.show() | http://apmonitor.com/pdc/index.php/Main/LinearizeDiffEqns | CC-MAIN-2018-13 | refinedweb | 1,274 | 51.14 |
mojoPortal 2.1.6 Released mojoPortal 2.1.6 is now available from the download page. This release adds a new Site Statistics Module and some bug fixes. This will be an easy upgrade if you are running mojoPortal 2.1.x with no custom modules of your own because there are no schema changes in the db. If using MS SQL or PostgreSQL you need to re-run the script that creates stored procedures. If you have custom modules you have implemented yourself, you should test your code with the latest source code. There were some major namespace re-organizations that may have broken your custom code. See my previous blog post, and if you need help changing your code so it works with the new changes in mojoPortal, please post in the forums and I will try to help. If you have custom skins, you may also need to tweak the css for the menu, see the included skins css files for changes I made there. As always be sure and back up both your db and your site before attempting an upgrade. If you run into problems post in the forums and I will help. Joe Posted by mojoPortal Thursday, December 07, 2006 9:26:24 AM Categories: Releases Previous Post << >> Next Post Comments aleyush re: mojoPortal 2.1.6 Released Thursday, December 07, 2006 9:38:46 PM Please, tell about your plans on svn branches. As far as I remember, after this release you were going to implement some new features so that the latest code becomes unstable. What branch is recommended from now to develop custom modules on? Joe Audette re: mojoPortal 2.1.6 Released Friday, December 08, 2006 4:00:33 AM What I mean about unstable is I will be working on new features that require db schema changes and I may commit my changes for one data layer before I begin work on another data layer so depending on which data layer you are using it may not build. branches/2.x will always be kept stable branches/joesandbox2 is usually going to have the newest code but may not always be stable because this is where I work on new features Joe aleyush re: mojoPortal 2.1.6 Released Friday, December 08, 2006 10:40:26 PM May be, you shall write into svn commit comments when your commit is not compilable or require schema changes? Zak re: mojoPortal 2.1.6 Released Tuesday, December 12, 2006 4:07:57 AM Have you run MoMA () on mojoportal 2.1.6? Just wondering since I would really like to be able to move to the 2.x version, but I don't want to run on IIS. If there is any point in it, (I don't know since I am not very familiar with 2.1.6 yet) I might try to muck around with it this weekend. Zak Joe Audette re: mojoPortal 2.1.6 Released Tuesday, December 12, 2006 7:44:39 AM Hi Zak, No I haven't had time to try Moma. By all means if you have chance please do and let us know what it reports. I have been working with some folks on the Mono team to resolve issues preventing mojoPortal 2.x from running but I've just been working through them 1 at a time. If we could get a report identifying things needed that would be great. The things that are blocking right at the moment are actually implemented but just not working correctly. Once the current issue is fixed there will likely be others and maybe Moma can help identify those ahead of time. Thanks, Joe Comments are closed on this post. | https://www.mojoportal.com/mojoportal-216-released.aspx | CC-MAIN-2017-51 | refinedweb | 624 | 71.55 |
HP Inc (Symbol: HPQ). So this week we highlight one interesting put contract, and one interesting call contract, from the February 2018 expiration for HPQ. The put contract our YieldBoost algorithm identified as particularly interesting, is at the $15 strike, which has a bid at the time of this writing of 59 cents. Collecting that bid as the premium represents a 3.9% return against the $15 commitment, or a 5.9% annualized rate of return (at Stock Options Channel we call this the YieldBoost ).
Turning to the other side of the option chain, we highlight one call contract of particular interest for the February 2018 expiration, for shareholders of HP Inc (Symbol: HPQ) looking to boost their income beyond the stock's 3% annualized dividend yield. Selling the covered call at the $20 strike and collecting the premium based on the 56 cents bid, annualizes to an additional 4.8% rate of return against the current stock price (this is what we at Stock Options Channel refer to as the YieldBoost ), for a total of 7.8% annualized rate in the scenario where the stock is not called away. Any upside above $20 would be lost if the stock rises there and is called away, but HPQ shares would have to climb 13.8% from current levels for that to occur, meaning that in the scenario where the stock is called, the shareholder has earned a 17% return from this trading level, in addition to any dividends collected before the stock was called.
Top YieldBoost HP. | http://www.nasdaq.com/article/one-put-one-call-option-to-know-about-for-hp2-cm805230 | CC-MAIN-2017-43 | refinedweb | 257 | 60.35 |
I have an application with a servlet that uses @Inject to access a managed bean and @EJB to access an EJB:
@WebServlet("/test") public class CDITestServlet extends HttpServlet {@Inject ApplicationBean applicationBean;?
Answer by Roberto Sanchez Herrera (156) | Sep 09, 2013 at 11:57 AM
Hello,
This sounds similar to this:.
Answer by Gerhard Große (1) | Sep 09, 2013 at 12:08 PM
Yes, this sounds very similar. But although this topic is marked as answered, I do not see what the solution should be. I also tried "Run server with resources on server" but that did not change the behavior.
I'm using a fullprofile WAS 8.5 in developer mode, no liberty profile. And my bean (applicationBean) is not an EJB, so switching to @EJB instead of @Inject would not work.
Answer by ktsao (16) | Sep 10, 2013 at 09:59 AM
We're currently investigating the issue raised in . In the meantime, the only workaround is to deploy using the WAS admin console.
Answer by Gerhard Große (1) | Sep 10, 2013 at 10:14 AM
Thanks for the info!
No one has followed this question yet.
How to configure use of multiple wlp_user_dir with WDT 3 Answers
GPFS Quota implementation problem. 0 Answers
Rich Page Editor's dialogs appear behind the editor on MAC 1 Answer
Problem during installation of WDT for Luna via zip 2 Answers
Is it possible to display in WDT in console view to see full log message? 2 Answers | https://developer.ibm.com/answers/questions/5714/inject-and-ejb-not-working-together-in-a-servlet-when-deploying-through-was-developer-tools.html?smartspace=wasdev | CC-MAIN-2019-30 | refinedweb | 246 | 62.78 |
Bugzilla – Bug 19783
Math tests that use namespace prefixes in the assertions
Last modified: 2012-11-14 12:18:31 UTC.
Bug fixes done and committed to cvs.
(In reply to comment #1)
>"
Made the change as suggested by Mike Kay, i.e.:
<assert>abs($result - 7.38905609893065e0) lt 1e-14</assert>
> - .
Moved the assertion within the test cases using an eq operator.
Expected result for these tests is now <assert-true/>
There is an error in math-atan2-004.
In
<test>math:atan2(-0.0e0, -0.0e0)</test>
<result>
<assert>abs($result - 3.141592653589793e0) lt 1e-14</assert>
</result>
According to Wikipedia, atan2(−0, −0) = −π
So the assertion should be
<assert>abs($result + 3.141592653589793e0) lt 1e-14</assert>
(In reply to comment #3)
> <assert>abs($result + 3.141592653589793e0) lt 1e-14</assert>
Change done accordingly to comment #3
Please note that we take our specifications of trigonometrical functions from IEEE 754-2008, not from Wikipedia. In edge cases and at singularities, there are differences between different specifications of these functions. However, I have checked this one and IEEE also has atan2(-0, -0) = −π. | https://www.w3.org/Bugs/Public/show_bug.cgi?id=19783 | CC-MAIN-2014-10 | refinedweb | 187 | 67.25 |
Microsoft provides a great tool for both speech recognition and synthesis. It is called Microsoft Speech API. Here I'll introduce the various features you can use in the synthesis of speech with SAPI. Please find a full application in the downloads.
For speech synthesis, we get the System.Speech.Synthesis namespace. The main class is the SpeechSynthesizer which runs in-process. You can set its output to be the default audio device or a wav stream/file. Then you simply call speaking English ... very cool. Supposedly, you can get other voices by installing the MUI packs on Vista ... but I have yet to track any of these down to try it out. XP should have some other voices to use like 'Microsoft Mary' and 'Microsoft Sam'. For the synthesizer, you can also customize its volume and rate of speaking. For 'pitch', you can change a prompt's emphasis, or do this it SSML using the <prosody> tag.
System.Speech.Synthesis
SpeechSynthesizer
SpeakAsync()
<prosody>
Speaking, in general, is as simple as this:
SpeechSynthesizer synth = new SpeechSynthesizer();
synth.SpeakAsync("Hello World.");
Volume, by default, is 50 (range 0 to 100), and rate, by default, is 0 (range -10 to +10). You can change them with the variables synth.Volume and synth.Rate, respectively. If you are working with WPF or Silverlight, you can simply assign a slider for this. There are two methods in the SpeechSynthesizer class to speak:
synth.Volume
synth.Rate
Speak()
One of the coolest features is that we can directly use Wave files (.wav) as an I/O medium for the sound. You can set your output to anything like the default audio device, a wave file, an audio stream etc. This is an example for a wave file output.
synth.SetOutputToWaveFile("output.wav");
synth.Speak(textBox1.Text);
synth.SetOutputToDefaultAudioDevice();
MessageBox.Show("done");
Basically, what I've done here is, first set the output to a Wave file (it'll be created if not present), then made it to speak in the Wave file. Then put back the output to the default device for further operations.
Now, there is an XML based language called SSML by W3C that specifies the standards of speech delivery. You can completely specify how a speech should be spoken. Fortunately, SAPI supports this standard. We can generate a prompt from SSML to directly deliver a speech.
Some useful tags of SSML:
audio
emphasis
enumerate
It specifies a template that is applied to each choice in the order they appear in the menu element, or in a field element that contains option elements.
phoneme
prosody
You can speak out from an SSML file using PromptBuilder, like this:
PromptBuilder
PromptBuilder pb = new PromptBuilder();
pb.AppendText("Hello..");
try
{
pb.AppendSsml("SSML.xml");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
synth.SpeakAsync(pb);
Another interesting feature of this API is that we can get an XML output of whatever we speak. And the reason I say it's important is that SSML can work as an intermediate language for programs written in any platform. For example, you speak something on an ASP.NET website, then create an XML out of it and pass to a Web Service. This service will return the same file to its client based on Java. So you could achieve a good interoperability in two programs. Here's the way to work with it:
PromptBuilder myPrompt = new PromptBuilder();
myPrompt.AppendText(textBox1.Text);
MessageBox.Show(myPrompt.ToXml());
Well, in the next one, I'll write about sound. | https://www.codeproject.com/Articles/89608/Voice-synthesis-with-Microsoft-SAPI | CC-MAIN-2017-22 | refinedweb | 584 | 66.23 |
futimes, lutimes - change file timestamps
#include <sys/time.h> int futimes(int fd, const struct timeval tv[2]); int lutimes(const char *filename, const struct timeval tv[2]);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):.
On success, zero is returned. On error, -1 is returned, and
errno is set appropriately.
Errors are as for utimes(2), with the following additions for futimes():
fd is not a valid file descriptor.
The
/proc filesystem could not be accessed.
The following additional error may occur for lutimes():
The kernel does not support this call; Linux 2.6.22 or later is required.
For an explanation of the terms used in this section, see attributes(7).
These functions are not specified in any standard. Other than Linux, they are available only on the BSDs.
This page is part of release 4.15 of the Linux
man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://manual.cs50.io/3/lutimes | CC-MAIN-2020-45 | refinedweb | 166 | 68.87 |
In the last post you saw how we’d spun up a new React project that would eventually go on to connect to an existing ASP.NET Core Web API.
We’d got as far as one simple component and needed to finish off our basic interface and hook it up to some data.
Here’s a quick reminder of what we were aiming for.
And this is how far we’d got.
So where next?
Components all the way down
One of the pillars of React is that everything is a component.
Building any user interface in React boils down to deciding which components you need and what order to build them in.
Our simple list of users could be one big component with all the markup and logic in one file but React encourages you to break this down.
A better bet is to build several smaller components, each with one specific role, which you can develop in isolation and then arrange together to form your bigger all singing and dancing feature.
And when you stop to think about it, this makes perfect sense.
It’s flippin difficult to build an entire application in one go, but break it down into manageable chunks and you’ll find you blitz through the requirements like nobody’s business.
Building the user details row
With this in mind we set about building a simple component to show user details for each user (as rows in our My Users list).
Here’s what we ended up with.
UserRow.tsx
import * as React from "react"; function userRow() { return ( <tr> <td className="avatar">Avatar</td> <td className="name">Jon Hilton</td> <td className="summary">36 / Lead Developer</td> <td className="actions">Buttons here</td> </tr> ) } export default userRow;
Here we’re sticking with a simple ethos of getting the key elements in place first before worrying too much about appearance (hence using a simple table; I could easily get lost for days trying to make anything work using CSS!).
We’re still using hardcoded values and before moving on to real data needed to plug at least one of these rows into our MyUsers component.
MyUsers.tsx
import * as React from "react"; import UserRow from "./UserRow"; export default class MyUsers extends React.Component<any, any>{ public render() { return ( <div> <h1>My Users</h1> <table className="user-list"> <tbody> <UserRow /> </tbody> </table> </div> ); } }
A small tweak here to render everything using a table and to bring in our shiny new UserRow component.
We put some minimal css in
index.css…
.user-list { width: 600px; } .avatar { max-width: 100px; } .name { padding-left: 10px; max-width: 600px; } .summary { padding-left: 10px; max-width: 400px; } .actions { max-width: 100px; }
Checking our progress now gave us this…
So far so good, but what about driving this row from some actual data? (not just hardcoded values in the markup).
Props to you
We needed to take this…
import * as React from "react"; function userRow() { return ( <tr> <td className="avatar">Avatar</td> <td className="name">Jon Hilton</td> <td className="summary">36 / Lead Developer</td> <td className="actions">Buttons here</td> </tr> ) } export default userRow;
And make it possible to render multiple rows, each with their own values for each cell.
Now if you’re used to working with ASP.NET MVC and Razor, you’re no doubt used to referencing
@Model to render values…
<p>Hey @Model.FirstName!</p>
React’s equivalent is “props”…
import * as React from "react"; export default class UserRow extends React.Component<any, any>{ public render(){ return ( <tr> <td className="avatar">Avatar</td> <td className="name">{this.props.user.name}</td> <td className="summary">{this.props.user.summary}</td> <td className="actions">Buttons here</td> </tr> ) } }
Assuming we could somehow get that user object into our component, the “name” and “summary” values would be rendered in their correct locations within the markup.
Exercise caution when cheating with any
If you’ve used Typescript at all you’ve probably spotted a little bit of cheating going on here…
React.Component<any, any>
The first
<any, indicates what
type our props are.
By using
any we’re basically saying the props can be of any type. Doing this enables us to get something up and running quickly but also removes the type safety we’d otherwise get.
If we specified a type there instead, the typescript compiler would protect us from ourselves, ensuring we have to pass an object of the right “shape” to our component.
However this was enough to get us going and we could always add the types once we’d learned the ropes…
Now we could pass a “user” to our component like so…
let someUser = { id: 1, name: 'Jon', summary: '36 / Lead Developer' }; /// code omitted <UserRow user={someUser} />
But what we really needed was generate multiple rows for multiple users…
Map (a bit like Linq)
To loop over an array of user objects; rendering a
UserRow for each one we found we could use javascript’s
map function.
public render() { return ( <div> <h1>My Users</h1> <table className="user-list"> <tbody> {this.getUserData().map(user => <UserRow key={user.id} user={user} />)} </tbody> </table> </div> ); }
Not dissimilar to
Select in C#, this will loop through the value returned from
getUserData() and render a
UserRow for each one.
If you’re wondering what the
key attribute is, omit it and React will blow up. This is a special attribute which requires a unique value for each item in the array. React uses this to efficiently render each row and only re-render rows which have changed (when the source data changes).
Finally we could test this all out with a simple implementation of our
getUserData() function.
private getUserData() { return [ { id: 1, name: 'Jon', summary: '36 / Lead Developer' }, { id: 2, name: 'Janine Smith', summary: '32 / Senior Engineer' } ]; }
Summary
Now our component was coming together.
We could render as many user rows as we had users; the next step would be to hook this up to our ASP.NET Core Web API.
photo credit: Leo Reynolds book pile 2017 | https://jonhilton.net/building-a-ui-using-react-components/ | CC-MAIN-2022-05 | refinedweb | 1,012 | 61.46 |
.
What interns learned
We learned about the new React context API and built a silly little app that shows off two benefits of context: 1. Shared state between components 2. No prop drilling
Here’s the source on GitHub.
We used
React.createContext() to create a context:
const LockContext = React.createContext()```And a top level component to hold the state and callback we wanted to share. It's like a Redux or MobX store, you want your state and your callbacks to travel together.```javascriptclass ContextualThing extends React.Component {state = {locked: false};toggleLock = () =>this.setState({locked: !this.state.locked});render() {const { locked } = this.state;return (<div>This is a lock<p style={{ fontsize: "2em" }}>{locked ? <b>Locked!</b> : "Open"}</p><lockcontext class="provider" value={{ locked, togglelock: this.togglelock }}>{[1, 2, 3, 2, 1].map(n => <togglerow n={n}>)}</togglerow><table></table></lockcontext></div>);}}:
const ToggleRow = ({ n }) => (<row>{new Array(n).fill(0).map((_) => (<cell><locktoggle></locktoggle></cell>))}</row>);
Notice the lack of prop drilling.
<ToggleRow> gets only a number,
n. Nothing about callbacks or the locked state. It doesn't even pass any props into
<LockToggle>.
That's because
LockToggle is a smart context component 👇
const LockToggle = () => (<lockcontext class="consumer">{({ locked, toggleLock }) => (<button onclick={toggleLock} style={{ fontsize: "1.5em" }}>{locked ? "Unlock" : "Lock"}</button>)}</lockcontext>);️ | https://swizec.com/blog/intern-process-part-2-my-first-webinar-about-react-context/ | CC-MAIN-2021-43 | refinedweb | 215 | 54.08 |
I'd like to second Raymond's suggestion. With just a few additional methods, you could support a useful set of operations. One possible API:
def scaled(self, factor)
"""Returns a new Counter with all values multiplied by factor."""
def normalized(self, total=1)
"""Returns a new Counter with values normalized so their sum is total."""
def total(self)
"""Returns the sum of the values in the Counter."""
These operations would make it easier to use a Counter as a PMF without subclassing.
I understand two arguments against this proposal
1) If you modify the Counter after normalizing, the result is probably nonsense.
That's true, but it is already the case that some Counter methods don't make sense for some use cases, depending on how you are using the Counter (as a bag, multiset, etc)
So the new features would come with caveats, but I don't think that's fatal.
2) PMF operations are not general enough for core Python; they should be in a stats module.
I think PMFs are used (or would be used) for lots of quick computations that don't require full-fledged stats.
Also, stats libraries tend to focus on analytic distributions; they don't really provide this kind of light-weight empirical PMF.
I think the proposed features have a high ratio of usefulness to implementation effort, without expanding the API unacceptably.
Two thoughts for alternatives/extensions:
1) It might be good to make scaled() available as __mul__, as Peter Norvig suggests.
2) If the argument of scaled() is a mapping type, it might be good to support elementwise scaling. That would provide an elegant implementation of Raymond's chi-squared example and my inspection paradox example ()
Thank you!
Allen | https://bugs.python.org/msg316978 | CC-MAIN-2021-21 | refinedweb | 289 | 61.56 |
I put an HDD into an enclosure and plugged it into a usb slot. The light turns on, I hear it spin, and windows says something's plugged in, but the drive isn't showing up anywhere. What did I fuck up?
>>52277491
Check disk management and see if you see another drive.
>>52277491
Press win key and r (run dialog opens)
type and run diskmgmt.msc
In Diskmgmt right click unallocated space and create partition
Which hierarchy should I go for?
>>52277513
>>52277516
thanks guys, I see it.
someone said google but I don't wanna risk getting a virus. what to do for jailbreaking ios 8.4?
Are there any good cross-platform software raid solutions?
what linux server distro or repo is available to run nginx 1.9.9 mysql 10.1 and php 7.1?
>>52277580
TaiG jailbreak is what I wanted to download.
>>52277657
I'm running nginx 1.9.9 and mariadb 10.1 on debian 8.
though I compiled nginx myself, mariadb is from their repository.
no php yet.
how bad is this setup,
>>52277746
Everything looks good OP. Seems like a pretty solid build :)
>>52277711
i tried installing nginx from source, but its not working yes in centos 7.1 (what im currently using and probably keep using)
why do people think stabilty is that important
>>52277746
k
>>52277634
Intel fakeraid in bios?
>>52277417
What creates the rings in that webm? If it's like a sound barrier thing, why are there several? Does it explode like eight times?
I thought I'd encrypt my phone but it's been four hours since I started encrypting and it still isn't done.
Nexus 5 with stock android, rooted, latest build from google's site (2016 security update).
>>52277760
>>52277800
cpu fan doesn't push air in the same direction like case fans, does it matter?
>>52277764
It's a personal server, so I don't care about stability that much.
Though arch is too fast and centos too slow with updates.
I wanted to have http2, compiled it with./configure --user=www-data \
--group=www-data \
--prefix=/usr \
--conf-path=/etc/nginx/nginx.conf \
--pid-path=/var/run/nginx.pid \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-cc-opt='-O2' \
--with-file-aio \
--with-ipv6 \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_addition_module \
--with-http_xslt_module \
--with-http_geoip_module \
--with-http_sub_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_random_index_module \
--with-http_secure_link_module \
--with-http_degradation_module \
--with-http_stub_status_module \
--with-http_perl_module \
--with-mail \
--with-mail_ssl_module \
--with-google_perftools_module \
--with-pcre=../pcre-8.37 \
--with-zlib=../zlib-1.2.8 \
--add-module=../nginx-rtmp-module
used to run it from a raspberry first, now on real hardware.
>>52277836
Not really a big deal
How much stuff did you have on it? Obviously the more it has to encrypt the longer it'll take
>>52277824
>>52277817
Looking into it. Not sure if my mobo supports it, asus p8b75-v
How do I figure out of my HDMI cable is high speed?
>>52277838
nice, i want to fuck around with http2 too, also php7 promises more speed. I have a personal vps too but its 10 euros a year so i have raspberry-like performance
>>52277880
No it doesn't. I can't think of a program that can do what you want. Get a cheap raid card
>>52277417
Hey, I encoded that webm! Nice pick, anon.
#include <stdio.h>
int sumThroughIteration(int n);
int main()
{
int n;
scanf("%d", &n);
printf("%d", sumThroughIteration(n));
return 0;
}
int sumThroughIteration(int n)
{
int sum = 0;
for(;n>0;n--)
{
sum = sum + n;
}
/*also tried printing sum on this line*/
return sum;
}
I'm trying to make a simple iterative sum so that if user inputs n=5 it will return 5+4+3+2+1=15. Anyone can tell me why doesn't this work?
Not sure if this fits the board but is this online course any helpful if you're looking to get into IT as a career? And what do you guys think of this ALISON course? ()
I'm certain there's more to it (get it? hah) but the problem is I haven't got a clue where to start and how to go from there. So, I just want to know if there is anything I could do behind a computer that would make me learn IT properly and help me get a job or something.
Any links? Career advice? Tips from experience? Give me all you've got.
>>52277913
Tried that in the past with shit results. Thanks anyway.
Is raid 0 really worth all that much with only two disks? They're WD Blacks with 64m cache.
Is it possible to find a white themed AMD R9 290 anywhere or do I need to buy a GTX 970
I'm going to write a tool which will try to detect encryption being used for files in the future, particularly single files rather than full volumes
Would anyone recommend an encryption program for doing single files rather than full volumes, it's meant to be a scenario where you could encrypt the file > upload to dropbox > and then download and decrypt with the password
I've had a look at TrueCrypt which is discontinued and VeraCrypt seems to be the new one - but that looks like it does volumes only too? Any ideas?
>>52277950
Which board did you post it on?
>>52277970
I'd say yes but then you have the issue of losing your data. It's up to you. You could do it on just one OS. Use Linux in a VM
>>52277958
but it does work, what isn't working for you?
I'm completely new to programming, but I knew I wanted to start with C++
Got pic related on a whim and want to know if I fucked myself over.
>>52277965
It may take a long time, but would it be worth it in the end? How difficult is it to destroy the MBR?
>>52278063
language doesn't matter too much. Neither does /g/'s opinion at this point. Just get coding, and ask for help if your sources aren't helpful
I bought a blue switch DK2108 zero keyboard. Did I fuck up?
What are some good Google Cardboard-styled plastic phone headsets under 30$?
I'm trying to soften the blow with TrinusVR after
>$599
>>52278079
It depends on the size, condition, and speed of the drive. It can vary like crazy. I'd say your disk is damaged in some sectors.
Just rundd if=/dev/zero of=/dev/sdc bs=446 count=1
To destroy only the MBR. Takes two minutes. Unless you're some kind of recovery specialist you might get a file name alone or two, no data. Your drive is clean without the MBR
>>52277989
I have them in windows dynamic disks right now, created on a win7 install and imported to a ten installation. Have you ever noticed spin-up times when accessing it for the first time in a while?
>>52278127
> Have you ever noticed spin-up times when accessing it for the first time in a while?
If you're asking if it was slow for me, no even after a month (backup drives) I never noticed any speed decrease. Between one or more drives more is always faster for me
I've got two partitions on my hard drive, one WIndows and one Linux. If I want to clone them to another drive, is there anything special I need to keep in mind?
>>52278181
not a read/write deficiency. If I haven't accessed the RAID0 in a bit, it takes a moment for windows to come up with the file list.
You have two monitors to choose from. One is 24 inches, one is 27 inches; They both have the exact same specs otherwise, including refresh rate, response time, and resolution.
Which of the two would you personally buy, /g/?
>>52278222
Oh that. Yes that's just Windows refreshing the index or some bullshit
>>52277836
Not a huge deal but it'd be much better if you could have them all flow in the same direction
What program on Mac can sync music playlists to an SD card?
I have a Sandisk MP3 player that is only 8gb, and I can sync it with DoubleTwist, but I'd like to utilize the 32gb SD card by syncing (no drag and drop)
At what operating temperatures should I start worrying about my 1TB HDD?
>>52278259
24 obviously.. Why waste space and have such a low ppi screen
Can QT be used freely in any kind of project at no cost?
Is the Moto G 2nd Gen still a good option? I have the chance to buy one cheaper, since rd Gen recently came out.
>>52278303
It's safe up to 70C, but over 60C I think you might have a cooling/airflow issue
>>52278219
If I'm correct, I think you can only clone the whole disk, not just a partition, if that's what you're asking. Nothing really hard about it just watch a YouTube vid or something.
>>52278470
That's what I was hoping. I just want to make sure doing so doesn't mess up grub or boot records or anything if I try to boot with the new drive.
Why are wiki pages always broken? Is it on my end?
>>52278532
>Is it on my end?
Probably
>>52278572
Why? my internet?
apktool says it requires java 7
will java 8 work
I am a EE with a power systems focus. I'm fine working in the power industry, but am I basically shit out of luck if I ever wanted to work for a tech company?
I want to buy a scissor switch full size keyboard but I cant find them or only find extremely rare and shady ones.
It there a /g/ guide for them or does anyone know how to find some models? It'd be great if they were <100€
>>52278952
I have a logitech k800, love the keys..
Can I build a desktop from a removed laptop motherboard with CPU included?
>pic obviously related
>>52278973
I was looking at the logitec illuminated series too but seems like they suffer from ghosting, particularly you cant press space while holding W and shift
Which is a really bad thing
>>52277863
Can't check because the fucker is still going after almost 6 hours. I only flashed that ROM today and put my basic apps on it, no media on it whatsoever. I think around 10 GB are used, mostly by offline maps for OSMAND and maps.me?
I know encrypting takes an hour or more but I didn't think it'd take THAT much longer.
>>52279024
works for me.
>>52279013
With only 1 usb port? I think fucking not. Anyway you technically could if you had all the peripherals, the cooler for the laptop and a way to turn it on
>>52279024
just tested using
I can press WASD (all at same time) + shift + control + space at the same time.
>>52279044
I was also looking at the k740 model, as the k800 was 20€ pricier
>>52279048
Shit, didn't see the lack of USB ports. Is it still worth bidding $1 on eBay for?
>>52279048
>>52279094
USB hub maybe?
>>52279094
Depends on the boards specs
And if it comes with the cooler or not
Will a GT 630 run on the 300w PSU in my stock Inspiron 570?
>>52279071
I bought my k800 2012, the k740 is from 2013, damn.
The k740 is what I was looking for back then.
Wired flat scissor switch.
And I love the huge del key logitech has, the k800 has a normal one.
My previous was the keyboard from the "media desktop laser" set and I looked for something similar but wired.
The only thing that got close was the k800.
Need g approved best bang for buck 108pp monitor. Need it for gaymen
>>52279157
Here's the listing, that looks like the cooler on top.
>>52279065
>>52279044
Since it goes for 80-90€ I dont want to cross my fingers and hope my model works. Its a beautiful keyboard but that flaw would render it completely useless to me
Arent there more peopke making scissor switches? They are amazing yet nobody uses them
>>52277958
Make an array for your n+1s then print them.
>>52279181
This is a completely different model. Bid that dollar but dont suppose you will get it so easily, people will push the price up
WELP WELP
is cock.li down?
>>52279253
I believe it got taken down by government, or something like this a few months ago.
>>52279240
I bid, thanks for your help. All I'd need is peripherals, right?
>>52279272
What? I used it like 2 days ago.
>>52279272
yeah. German government seized the hard drives it was being hosted on.
Any good, free as in beer (preferably also free speech) apps for tethering android to windows?
I have f-droid and root, also I do not mind using a cable instead of wifi.
>>52279293
>>52279297
lolwut?
I have a credit card with a penalty APR on it because I was dumb and missed a payment one month. I immediately paid the card balance off in full to avoid paying 30% on the thing, and a few months later asked about whether they could lower the APR back to what it was, but they said they can only re-evaluate the APR only 6 months (which may have been bullshit but I don't know)
Anyway it's been more than 6 months since then, do I have to bug them about it, or will they automatically re-evaluate it when they feel ready to? It's not like it's hurting me since the card has zero balance (and will continue to until they lower the interest rate on it) but it is a shame I can't use it if I wanted to, even though I do have others I prefer.
>>52279316
I wanted to try out Plex, so I downloaded and installed it on my Windows machine.
When it finished installing and launched, it opened the web app and I logged into the account I created.
Now all it does is say "Server Unavailable We couldn't reach this server. Make sure it's online and try again"
Not sure what to do.
>>52279272
>>52279297
Wrong idiots, Germans only took 1 HDD, cock.li is down because of a ddos
>>52279407
but wasn't there a /g/ site that got taken down completely?
I'm not trying to incite any sort of brand war here, but is it just me or are Sony HDTVs really the only desirable ones? They aren't even more expensive, which is super weird.
I swear every single Samsung and LG review has huge problems. (Vizio's are at least cheap enough to warrant their flaws)
They all have terrible judder, motion blur, shit contrast, can't into chroma 4:4:4, bad input lag, and for some insane reason most of them have glossy panels.
My laptop stopped connecting to my router, and so did my phone. After resetting the router my phone connects and the router shows up in the lost of available connections on my laptop but it won't connect to it.
Am I missing something here or what?
Is there a Netflix addon for Kodi/XBMC?
All i seem to find are some outdated ones that dont even work.
I'm trying to get Windows 10 to erase everything on my C: drive and reinstall itself. Does the option to "remove all" only affect the C: drive or does it also affect the rest of my partitions?
Best free antivirus for retarded users?
>>52280034
Avira
>>52278340
Anyone? This is a dumb question, right? Asking because I have no idea how dual-licensing works
>>52280034
linux (seriously)
>>52278116
Im going to sound like a total pleb, but I have no choice.
Do I use this code in the command prompt? Or do I input it somewhere as my bios loads? What is required to run this code?
Best Distro for university? Will be moving in a week. I have a windows laptop but the battery died so it's tethered down. I have a qt lil X200 that I plan on using if I need to use a computer while on campus. Any recommendations? I was planning on Mint
>>52280704
mint or debian
Fucking seriously, encrypting a phone shouldn't take 7 hours, even if 10 GB of the 16 GB storage are used... right?
>>52281024
>encrypting
>a phone
If I'm connecting an amp to my computer, do I need a Y cable or can I use a stereo cable (both ends red and white)
is there anywhere for the red and white cable to plug into the back of my PC
I got a bunch of different color connects going on back there (green, blue, orange) but no red and white
t. retard
>>52280704
Mint only is you want Cinnamon.
Otherwise one of the *ubuntu flavors for easy access to PPAs.
To be honest, I'd advise against Mint even if you want Cinnamon because you can always install Cinnamon on something else. Mint comes with autistic repos that can be a bit of a pain to deal with.
Debian is good too, but accessing stuff outside the official repos isn't as easy as it is on *ubuntu. Not saying it isn't possible, you can definitely do it, it's just not as simple.
Do codecs still fuck up with your PC? I have installed CCCP and uninstalled it because I want PotPlayer and I'm not sure if it might have fucked everything up like it did ages ago.
>>52281072
You need a 3.5mm <-> phono cable or a 3.5mm <-> phono adapter, then you plug the 3.5mm end into the green port on your computer and the phono end in your amp.
>>52281167
God damn it I fucked up
>>52281036
Yeah thanks for that useful input. God forbid I don't want strangers to look through the data that accumulates on my phone over time.
I have a problem with Windows and Ctrl+Alt+C in Photoshop.
Basically, Photoshop won't register this key combination at all, not with my physical keyboard, not with the on-screen keyboard, not with a different keyboard, nothing.
How do I find out if something is hogging this particular combination of keys ? Nothing happens when I press Ctrl+Alt+C, it just seems like it isn't registered at all.
OS is Windows 8.1 btw.
>>52281186
Why ? Those things are cheap as fuck.
Is there a better ad blocker than Adblock Plus for Firefox?
>>52281267
Unlock or adblock edge
Dual boot in SSD, good or bad?
>>52281301
A VM is better
>>52281311
I have Windows because Steam. And I already VM but it's not very comfortable.
>>52277417
I haven't changed my water in 2 years, in those 2 years i've used one kill coil.
what can i expect to see when i clean it out?
I'm finally breaking off and getting my own cell plan to help build credit. I'm in midstate NY, anyone have suggestions as to which carrier would fuck me over the least but still have good coverage? So far I'm leaning towards T-Mobile.
>>52281290
Cheers.
Why has '4k resolution gaming' become such a thing lately? I really feel like going over 1080p is such overkill when you consider the cost in frames.
Maybe the fact that I like to play at 144 hz on fast-paced competitive multiplayer games and dont' really care about Crysis 8/Metro 3000 or whatever is part of it, but even from that perspective isn't higher framerate mor enjoyable than big resolution at less than 100 frames?
>have 290 tri-x
>overclock it
>completely stable in Heaven/Valley/Firestrike
>shut down pc, breakpoint exception
>restart pc a few hours later
>boots in then immediate black screen
>have to uninstall AMD drivers then undo the overclock
what's the deal here guys? how do I overclock without having to reinstall drivers every time I go too far?
>>52281493
Why would you play at meme frame rates? Your eye can only see 30 frames per second anyway.
>>52281239
Bought the wrong one, that's all. Still like $7 though
>>52281589
that is an epic meme you said it my friend
>>52281716
Oh. You can just pick up an adapter then, probably cheaper than a cable.
I paid $130 for crucial ecc ram and $230 for an SSD and Canada post left both in my mailbox in -21C temperatures. What the fuck? I assumed if I wasn't home I would get a note to pick up. This makes me so mad..
>>52282234
They always seem to fuck everything up. I use purolator whenever possible.
>literally the day after my warranty I get my first dead pixel on my monitor
Current monitors are complete garbage and LOL to any retard who buys expensive 4k ones, enjoy your single out of color pixel ruining the display
what's coming up that will make pixels bsolete?
>b-but you can ignore them
they look like shit and anybody who sees your dead pixels is laughing at you inside their head
>>52282511
now I'm wondering if I should return it or just let it thaw for a day. Wish this shit didn't happen ahhh
any way to sign into an old youtube account if you know your password and username but don't know the email associated with the account?
it used to pop up after i put in my username and password saying "this is your email address, use this to sign in" and then one day that stopped and now i can't sign in to it anymore
At what point should I start scouting for internships? I'm a first year CS major, just finished core Java/FX/FXML.
>>52282234
literally first world problems
>>52282822
This whole board, arguably this entire website, is first world problems.
>>52280460
This is linux terminal code
>>52281399
Maybe chunky fluid, nothing special
>>52282234
So they're not affected by extreme temps. I ordered a 780ti a year back and the box was covered in frozen condensation. I had to thaw out the GPU before I could open it. I still use it today
So I know what same of these are, but can sameone fill me in on the others?
dX and dY I get (difference in x and y directions) and Xv and Yv I get (velocity in the x and y directions) I get.
Could someone explain these three?
P: 0/1
Prs: 1.0
Size: 0.01
>>52282918
P: is screen being touched? [yes 1] [no 0]
Prs is touch pressure
Size is area touched
I have a Core I5 2430 M on my recently acquired memepad x220. What kind of games can I run on it? I know there are websites that can tell me but I'm looking for "personal experience". I know it runs nicely modern 2D games (like Aoe2 HD) but I want to know if it's worth downloading the many GB of Starcraft 2 or Napoleon Total War.
>>52282550
Just let it sit at room temperature for a day. The worst that could have happened is you got a little condensation on it and that's just distilled water.
Guys, I have a pretty shit phone, and I can only play larger, higher definition videos on VLC because of the hardware acceleration feature it has. The problem is that VLC doesn't have a loop feature for videos. So I can't watch porn Webms on loop using VLC. What is a good media player for android that uses hardware acceleration and can loop videos? I have tried many players, but most of them don't have a loop feature for video, and the few that do don't have hardware acceleration.
>>52283101
>porn webms on loop
why would you ever need that
>>52283011
>games
none. maybe csgo
>>52283167
Because some people apparently think that making a 2 second long SFM animation loop and saving it as a 1080p Webm is a good idea
you guys know a good site to stream TV shows? I used to have one but it sucked and I'd rather not torrent huge packs
Upgrade for Intel Pentium Processor G3250 (3.20 GHz 32 GB, FCLGA1.150) BX80646G3250 ?
Im bad at looking for compatible parts.
Preferably one thats good for games
>>52283011
I have an x220. I've read people say theirs ran lots of games, but I think they're lying cunts. If I run fallout 1 through WINE for example, my x220 is practically on fire a few minutes later.
N64 emulators only get like 20fps for me and also make my gpu hit temps hot enough to brew coffee. I would say anything past SNES emulation and DOSbox will blow hot air on your balls nonstop.
Is it possible for me to tag images on Windows so I can search by tag, like booru websites?
Is there an extension for Chrome that is similar to Watch with MPV for Firefox? I know there's youtube-mpv, but I just can't seem to get it to work.
If I set up port forwarding on port 22 for a certain device on the network, will all incoming ssh connections be routed to that device?
>>52278063
you kind of fucked yourself over by choosing c++
its easier to learn something more high level first, despite the people here who'll shit bricks, python and rube are a good starting point to get a general feel for things, then try moving onto c
Would I be able to do GTX 980s in SLI and two 512GB Samsung 950 Pros in RAID 0 on an Asrock Z97 EXTREME6?
I have three dead smartphones.
2 Galaxy S3s, 1 cheap Android device.
What's the best way to get rid of these, ideally while making a couple bucks off of them, if possible? Sell on Ebay? I can't run Perk or anything, because the S3s turn on but the screens don't work and the cheap one doesn't even turn on.
>>52277417
There was an open-source browser that was shilled here a while back last time I saw. It was something that took on the color scheme of the website it was on (i.e. the browser would be red if it was on youtube). Anyone know/remember what this was called?
error: failed to prepare transaction (could not satisfy dependencies)
:: lib32-sdl2_ttf: requires sdl2_ttf=2.0.12
how do I fix this
is there any way to get back the hide thread button back to where it was on the 4chan mobile site?
>>52284205
I'll give you $15 for the 2 s3 if they are gsm(verizon, tmobile or att)
>>52283622
on win7 you can tag pics in the explorer.
look in the details part of explorer when you click a pic or right click, properties, details, tag.
It might be similar on vista, win10 but I don't use them
>>52283307
vaughlive
>>52285039
>>52283622
that only works for some filetypes, I believe.
If you really want a local booru, look up hydrus network. It takes a decent time investment to get set up, but is well worth it in my opinion.
>>52280016
doesn't the installer give you an option to choose the drive you want to delete and format? I know xp, vista, win7 installers did with multiple partitions or drives on a pc
>>52279707
did you have a password on your wifi? after a router reset the password resets too. so maybe the laptop is trying to connect using the old password. I don't know what os you're using but have you tried deleting the connection in the connection manager and then try reconnecting
Why is alonvvear a meme?
Man, I'm starting to regret skimping out and getting a 128 gb ssd instead of 240, especially since I want to dual boot windows and linux. 20 GB would be enough for Linux, yeah?
>>52285250
Look at the prices of 500GB SSD, they're dropping drastically compared to summer.
Do you know any encryption software that lets you use a custom encryption algorythm?
>>52277417
Bombs seem so inefficient. Look at all that wasted energy going into the sky. We should be having bombs that cover huge areas instantaneously but stay low to the ground.
What's a better Photoshop alternative, GIMP or Krita?
>>52277417
I had a question about MD5 and Sha1 fingerprint check sums for SSL certificates.
I'm trying to setup my email in thunderbird however a window came up stating the certificate my email providing was "unknown".
The checksums provided were different when I checked online using and a few other websites.
Is there a reason for a SSL certificate for p0p3 to be different?
Do you know of anyway to confirm fingerprint checksums of SSL certificates?
>>52285324
GIMP is literally inspired by Photoshop, Krita is more user-friendly though, at least for me, I like it more. Maybe you should try both, Krita size is small anyway.
Stupid question here
With this whole business with non K skylake cpu OC is it an good idea to buy a z170 board with a i5 6600? also DDR4 21333 or DDR4 24000
what does amd overdrive use to measure thermal margin? i have an apu cpu and according to hardware monitoring my temps are all sorts of fucked up but according to amd overdrive everything is fine since it stays over 20 c
>>52285459
you should try speedfan, it is known to work with AMD Cpu's
How do I make my fonts smaller? The page isn't zoomed in.
>>52277417
Hey /g/eeks, I need some help here:
So I'm 2nd year into Computer Science at a University. My plan was to focus into Networking and Distributing Systems and upon graduation work towards being a network architect.. However, $$$ is the #1 objective here and I am starting to realize that focusing in networking might not be utilizing my degree to bring in as much money as Id like (I want to make 6 figures as quickly as possible).
What should I do? Networking is what I like a lot, but how realistic is it to meet these income goals?
No, dont say fucking game design please god.
I would also not prefer to be chained to a desk coding 12 hours a day either.
Robotics perhaps?
Please help.
>>52285469
i have no fucking clue which of these temps is supposed to be my cpu
>>52285469
>>52285683
yeah figured it out. at least the temps on speedfan are realistic. i get around 55-70 under load on a stock cooler. how fucked am I? should i just not play until i get another cooler?
The fingerprint scanner at my Lenovo B470 is abnormally hot to touch, this happens even if my computer is idling and the HD\D plate is only warm. Is something short-circuiting?
Is there anywhere I can get the Windows 8.1 drivers for the Chuwi Hi8? I want to install Windows Embedded 8.1 Industry Enterprise but I'm guessing the drivers are something Windows won't autodownload, or am I wrong?
So, I'm looking at buying a new PC for my mother, she doesn't need a gaming PC, it'll be mostly for Netflix, Youtube and browsing Facebook or whatever, possibly play Tibia, but that shit will work on any PC.
I already have a GPU (nVidia GTX 660 Ti), PSU (500W) and a chassis lying around. We'll also use her old harddrive for now (she'll upgrade later). Now, what I for now is a CPU, Motherboard and RAM.
For the CPU, I've been lookin at "AMD Athlon X4 860k Black Ed. Socket-FM2+", people seem to think it's fairly good for the price. Do any of you have any experience with it? Or do you know of any better CPUs for around the same price?
As for motherboard, I've been looking at "Gigabyte GA-F2A88XM-D3H, Socket-FM2+", it seems like a solid choice, fits with the CPU and has PCIe-x16 for the GPU.
And for the RAM, I'll go for the
cheap Crucial BallistiX 8GB, should be fine.
Any of you have any pointers on things I should replace etc? The budget maxes out at around $300.
>>52278580
your browser
dose anyone have a beginners guide or anything to making a rPi into a server? Specifically running nginx and mono (want to use C# instead of PHP), and MySQL (or is there anything better than that?)
I already used a free webhost with my own domain and using cPanel and the host's panels are easy enough, but I want to learn how to use a server so I can know what to do when using a VPS.
>>52285999
i have a 860k and that mobo. 860k is great since its decently powerful and cheap as dirt because it doesnt have integrated graphics. works fine but get an aftermarket cooler.
it gets to around 50-70 under load and the stock cooler is loud to the point where i thought it was overheating.
>>52286067
Oh, sweet! Do you have any tips on a reasonable aftermarket cooler?
My office chair squeaks when I rock back and forth, where do I spray the lube?
>>52286093
ive seen people recommend 212 evo. just make sure it fits in to the case. im getting one once i get my neetbux next month
>>52285548
If you're looking for six figures, start your own company or become a literal computer scientist.
>>52277417
anyone know any good guides on converting and burning movies to dvds in the highest possible quality they can link me?
>>52286101
I'm not sure, you could try to identify it by listening, although I think normally you'd turn the chair over and lube the piston-thingy so that it goes into the chair, and then like push it in and out.
I transferred a HDD from an old laptop to a newer one that had previously run win8.1. This laptop had a problem with the BIOS that made it unable to boot from any other OS but the original OEM image, but pulling the CMOS battery fixed that. The problem I am having is getting the nvidia drivers for the 840m to install and work alongside the intel graphics drivers. If I force windows to use the geforce driver it installs and should work but I cant actually use the GPU. Installing the Intel graphics drivers causes the 840m to have a code 43 in the device manager (googling this basically tells me "something went wrong"). I have tried uninstalling the drivers for both using DDU and reinstalling them a couple times. Windows updates didn't fix anything either.
Ive tried everything I can think of. any help is appreciated.
>>52286038
I have this setup.
It's a raspberry 2 with nginx 1.9.9, mariadb 10 (mysql a shit), and mono4 running asp.net applications.
I just installed debian8, compiled nginx myself, installed mariadb and mono4 with apt-get.
Then I made a systemd service which runs my asp.net service with fastcgi-mono-server4
For my discrete math class I need to prove that the quicksort algorithm will always produce a sorted list within at most n^2 iterations, for a list of n items. Anyone have any tips on how I can go about this?
>>52286110
Hmm, seems fairly big. I'll have to check the case. I think I have another case lying around that could fit it otherwise, worst case scenario I'll skip the aftermarket cooler and check how bad the sound is and make a decision after that. Thanks for the help man.
>>52286233
im sure there are other options if you just google around. i cant really enjoy vidya because i subconsciously keep thinking my cpu is going to melt even if the temp is like 60 c. its that fucking loud
>>52286128
Fuck, apparently I'd have to take apart a really annoying piece in order to get at the squeaky shit. feelsshitman.
How come there are so many fantasy novels where the world has more than one moon? What's the point? Isn't one enough?
How can I force myself to finish things and stop getting distracted halfway through or having an urge to start something else before I've finished what I was doing before?
>>52286347
buy some modafinil
>>52286135
I should also mention that on the OEM image the driver would handle switching from integrated to dedicated graphics when gaming. I think that has something to do with this, but I'm not sure.
So it's been 16 hours since I started to encrypt my phone. The whole time it's been showing the Android 6 boot animation (4 colourful dots). 10 GB of its storage are being used.
Nexus 5, stock Android 6 build mmb29s, rooted, custom recovery. I did everything like it said (fully charged, keep phone plugged in).
What the shit is going on? Should I just abort? Do I need to reflash the ROM afterwards?
>>52286493
Not familiar with encrypting a phone, but it should not take this long to encrypt a few GB of data. Something sounds wrong here.
grape soda or orange soda?
Help me /g/ :(
I have a filezilla ftp server and sometimes it kicks me off when there's too many files being transferred. Sometimes it happens while loading thumbnails. Only way to fix it is to restart the ftp server.
Any general tipas for performance and stability for home use?
>>52286730
what does the log file say?
any errors?
>>52285310 (cont.)
for either windows or linux I don't mind, I only need a base program to test out.
>>52286713
nigger detected
>>52286805
:(
No I like both tho anon! I can't choose.
>>52286816
orange
>>52286780
veracrypt lets you choose from a few
>>52285310
Whacha trying to hide Anon?
Are there any good troubleshooting books? also if I ring my ISP what are the chances I can get them to send me a t1 diagnostic guide or whatever they're called?
What does /g/ think of this? :^)
>>52286735
>250 CWD successful. "/directory" is current directory.
>PORT 192,168,0,18,172,105
>200 Port command successful
>LIST -a
>150 Opening data channel for directory listing of "/directory/"
>226 Successfully transferred "/directory"
>STAT
>500 Syntax error, command unrecognized.
>PORT 192,168,0,18,202,143
>200 Port command successful
>LIST /directory/
>150 Opening data channel for directory listing of "/directory/"
>226 Successfully transferred "/directory/"
>STAT
>500 Syntax error, command unrecognized.
Just this over and over
>>52286983
what ftp client are you using?
>>52287007
FX file explorer for Android but I've tried a few different ones and most do it after a few minutes of transfer.
Is there any reason why my upload speed is twice as fast as download speed over AC wifi? Have both Asus router and pcie adapter and the target is connected via Ethernet to the router. Tried shitloads of channels and quadruple checked the 5ghz settings.
What's a decent LAN messenger? Like realpopup, only, you know, free
>>52287145
Discordapp is amazing for this, it's not NSA'd and the devs actually answer their fans. I recommend it.
how trustworthy are the people on r/buildapc?
>>52286862
I already use TrueCrypt, will it create conflicts if installed together? (does it actually have any additional features that TC doesn't already have?).
Though, I think it's too bloated for what I wanted to do, I just need a basic program for individual files with support for custom algorythms, even a CLI program would be fine.
>>52286887
Not much tbqh, I'm studying encryption and I wanted to RE a program that's simple and not bloated like TC and similar.
>>52287285
not as trustworthy as /g/. the criticism you get here may be harsh, but at least it's honest. on reddit you get banned for calling out a shit tier build
>>52287337
i have gotten troll advice here on /g/ before (that i believed for a short while)
that isnt likely to happen over there but at the same time your point is still true.
ill just have to try my best. there arent any shills over there are there?
>>52287399
shills are every where, even here. just post your build on different days and different times and compare the responses, that's what i always do. after a while it gets easy to spot trolls
I have to make a 10-12 slide presentation about a topic I can choose myself. What's a tech topic I could choose that is understood by everyone and not only nerds?
>>52287486
online shills
>>52287486
how to blow the dust out of a Nintendo cartridge
C/C++/C#/Python for a first language?
>>52287514
I've been jumping from learning one language to another and I can say that C++ is a good one to start with. It's applied pretty commonly on Windows programming. C# would be the best for game design, since Unity and Unreal use them.
Not sure about Python but can be used for pretty much anything.
>>52287535
Learn shell scripting. It's easy to write and immediately useful.
>>52287535
Unreal uses C++ natively, don't know about c#
>>52287564
You're right, my bad. Unity is the one who uses C# natively, not Unreal. But you can use Mono for Unreal and code it with C#.
can i use a compressed air can more than once or do i have to use it in one go
How do I rice a plain old Arch Linux terminal? Just installed it to my laptop and have no idea what to do.
>>52287756
Like do you have to use all of it one go?
No. I just use a bit of one to clean out my PC and set it aside for whenever I need it.
But you should only spray in short bursts up-right, since it'll get cold real fast and might spray bitterant if held improperly.
numberrow= [2, 5, 6, 4]
index = 0
while index < len(numberrow):
number = numberrow[index]
print(number, sep="", end="")
index += 2
Can anyone explain why the result is 26? I can't seem to figure out where that number comes from.
If you leave out [index], it simply shows the numberrow twice.
>Got an ironkey
Two things:
1: The included malware scanner is broken, reporting an unknown error. Any way that I could fix it?
2: Any cool things I can do besides use it as a secure password manager?
In case you ask: I'm not able to get much support for it as the account on it expired. Company allowed me to keep it after they wanted to throw it away.
Does Black ops 2 support 144hz monitors? Will i see a difference?
>>52287893
it prints 2, then 6, so you see 26
add a linebreak or a space
>>52288028
why does it skip 5?
>>52288036
because you increment your index by 2.
c# vs c++ vs java which one to learn if I know python?
>there is no pcie 4x sata III controller card with 2 eSATA ports that support port multiplying and at least one internal SATA III port
Fuggen kill me
Why my upload is better with utorrent? I want to change it but the others have shit upload. So far I've tried qbittorrent and tixati. The settings are the same i think.
>>52278364
Yes. I have one.
> Okay battery life
> Fast
> Great custom ROMs
> Easily rootable
> 5 inches is the perfect size
On my animu files, I often see on more polished batches these letters and numbers at the end of them. I (at least think) they are hashes or something so that you can verify you have downloaded a non-corrupt or tampered with file.
My question is what hash algorithm are these using? Is it MD5, SHA1, something else? I have no idea?
And if they aren't that then what are they?
Can I just disable Google Services on my phone with no negative consequences?
Shit's draining my battery real hard, I've tried a couple of fixes but they didn't work and I'm officially assblasted, I want it gone.
I'm shit with computers so this is probably the only place on 4chan I could ask about this.
I got a new computer for christmas w/ windows 10. As soon as I turn it on the fan starts up like a hair dryer and will just continue to run until I turn the computer off. I checked task manager and my disk usage is hovering around 90%-96%
What should I do?
>>52288275
which fan?
is it plugged into a controller/motherboard?
what's the temperatures?
check with resource monitor what's actually accessing the disk.
could be first time indexing.
>>52282979
Thank you anon!
What is it that makes some software firmware?
The way I understand it firmware is software that's embedded in the hardware and meant to drive it.
is there away to connect my phone to wireless right away without doing the whole disconnecting and reconnecting cycle every time ?
>>52288013
if the game can run at over 60 FPS (don't see why it wouldn't), yes you will see a gigantic difference
>>52288392
>In electronic systems and computing, firmware is a type of software that provides control, monitoring and data manipulation of engineered products and systems
Good old google
>>52288041
Thanks, I get it now. It always starts at 2 because "2" is index 0.
Can you explain this one however?def do1(a):
a += 5
def do2():
global a
a *= 1
def do3(a):
a *= 2
return a
a = 50
do1(do3(a))
do2()
print(a)
why is the answer 50? What I see doing is, is this:
a = a + 5 = 55 * 2 = 110 * 1 = 110.
why is the answer 50 and not 110?
What is a specification?
Does HTML have a specification?
What's the difference between a specification and a standard?
If I were to get any version of Windows 10 I wanted for free, which one is the most feature rich (like Windows 7 Ultimate)?
>>52288687
enterprise N
>>52288664
not sure what language that is, so this might be wrong in your case.
numbers types like int, float etc are value types.
when you pass them down a function you basically pass down a copy of it, not the original object.
so when you change the value in your function, it does not change the original value.
compared to reference types like objects/structs where you pass a reference/pointer to the object.
so when you pass a reference type to a function and change it inside, it changes the original value.
if you want to do that pass your numbers as reference to them.
see this for better explanations
>>52288697
Thanks m8
>>52288664
>>52288711
thats obviously python.
you dont return values from the methods, you just assign local variables, except for do2() where you multiply a with 1.
>>52288749
>>52288711
Yep, stupid mistake of mine. It only takes do(2) because that variable is global.
Others are all local. Basically all it does is 50 * 1.
I thought the others grabbed from a = 50 because there's a (a) after the def code.
Thanks guys.
Does upgrading a fake Windows 7 Ultimate to a legitimate Windows 10 Pro still work?
>>52288849
Yes
>>52288861
Is it worth it?
>>52288866
I don't know, I have Windows 8 and it's the best thing I used so far.
If you don't give a shit about muh privacy, probably.
>>52288885
I am tempted, but still a little scared about the "trial"-thing every online paper is writing, but I guess they are payed to write it or something. You're very sure it works permanently and that it won't backfire after a couple months? Reinstalling is such a hassle when you are working on stuff.
I got a this card.
I put it in, and get no video output to either on-board or the card. The fans on the card spin up then immediately stop. With the card removed the on-board video works fine.
I've tried installing drivers using the disk but it didn't help.
What do?
>>52277417
how do i download more ram.
>>52288994
here
>>52289002
thanks
>>52288977
Are you sure you pushed it all the way in?
Are you sure your PSU can handle it? (You should have no lower than a 650W PSU today, and that's living on the edge)
Did you try another cable?
Did you try another output?
Did you try another screen?
Did you try another GPU to make sure it's not the PCIe port itself?
Did you try resetting BIOS to its default state?
Is it possible for me to upgrade this build without destroying the MOBO?
I have like 2000 bucks to waste on new parts, but replacing the motherboard would be such a pain that I'd rather avoid it if possible. All the cable placement is perfect already, and taking out the mobo would mean irreparably messing that up.
Would the mobo just bottleneck any CPU improvement I could make, or can I make things better here?
>>52289031
The only thing I can think of about the mobo is the chipset, but it's probably not gonna bottleneck you (do your own research tho). If it fits, go shopping.
best pdf reader on windows?
>>52289070
sumatra
>>52289052
Is there even anything aside the CPU that's making my computer slow though?
The GTX760 card should be able to handle anything on high nowadays, as far as games go, but I still get like 20FPS even with low settings.
Is it just the shitty CPU's fault? Even though it's old, the mobo is new enough to support the new RAM properly, so I can't think of anything else that could be the cause of slowdowns.
What's a good CPU in the high range?
>>52289086
>shitty cpu
>2600k
>his idle temps are 67c
That shit is overheating and throttling constantly
>>52289086
you already have the best CPU for LGA1155
if you want a better one you need a new motherboard.
i need a decent cheap cooler for the fm2 socket and also a new cheap case for my matx motherboard. i dont really plan on doing anything but light gaming and shitposting here so dont need anything too special, but the amd stock cooler is shit and extremely loud
>>52289031
you should use some of that money buy a higher refresh monitor
Came home from work last night and tried turning on my rig, nothing. Check cables and outlet, nothing. Checked switches and voltage. Switch out PSU cord, nothing.
I remember I have extra PSUs for this reason and remove the mobo completely from the case leaving only the CPU/CPU fan in. Plug in both PSUs and trip the power switch. Nothing.
Just for shits I check all of the PSUs to make sure they weren't fucked.
Emailed Gigabyte's RMA last night. I'm sure it's the mobo. Am I an idiot and did I forget anything?
>>52289031
m8 reapply thermal paste, your cpu is probably throttling if its near 70 c idle
>>52289111
This, buy a new CPU cooler and replace the paste
Are Earpods a good high audio quality choice? Is there any other earphone with more quality with same or lower price?
>>52289111
>>52289115
>>52289151
I just checked and indeed discovered my CPU was amazing despite being 4 years old.
Does thermal paste make that much of a difference? My CPU is always close to overheating, but its fan is perfectly functional, and I even has a huge case fan double its size right over it.
I'll go out and buy some now.
>>52289153
In my opinion, no. They are just for out of the house stuff. I'd rather have over the ears all the time but I don't want to look more like a autist outside.
>>52288248
Did you ever remove the CPU heatsink after building the computer?
Not even on my 9 years old computer the paste is that bad.
>>52289174
Misquote
>>52289031
>>52289163
if the thermal paste hasnt been changed in 4 years you should definitely do it. get a new cooler while you're at it
>>52289163
Recently I was having a similar issue. I looked insinde my case and realized I hadn't dusted in over a year. When I looked at my (stock) heatsink, the blades were clogged with dust. I just removed the dust and then my CPU temps dropped by like 30 degrees and performance was back to normal. So if there's dust at all, try that
>>52289125
Coolermaster tx3. Low price and keeps the heat down.
Was thinking about a thread for this but since I'm new (to /g/) I'll just put it here:
Is "powered armor" realistic/feasible? By that I mean, say, a powered exosleketon with shitloads of bullet/flame/etc. proof material strapped to it that would be far too heavy for a normal person to bear.
Pros:
>almost completely resistant to small-arms fire
>would be good for clearing out buildings and trenches
>can take a shitload of damage
>equipable with a variety of weapons, from machine guns to flamethrowers
Cons:
>would be extremely heavy and unable to walk on fragile structures
>would likely be very bulky and unable to fit into small spaces
>would be slow and difficult to get out of trouble
>>52289163
If you have NO thermal paste, it's no wonder you're overheating. The thermal paste is a thermal conductor and its job is to fill those VERY small air gaps between your CPU and your socket. The thermal paste conducts heat MUCH BETTER than air, so be sure to use it. You don't need much tho, just put a small dose on the middle and push the CPU down on it. If a thin layer filled all the air gaps between the CPU and socked, you did it right.
Also, changing thermal paste is a meme that has gone out of control. The thermal paste does NOT lose its thermal conducting properties over time, much like copper wires don't simply "stop conducting electricity because they are old". If you already have applied paste, don't bother with it anymore unless you think you did a poor job last time.
>>52289174
>>52289186
The CPU has a fan with an heatsink built in (At least I think the metal plate directly in contact with the CPU is the heatsink).
Why should I buy a new one? It already springs up a tornado even at low RPM.
>>52289192
Cleaning it always drops the temperature by like 10 degrees, but it's still too high to be just a dust issue.
>>52289169
Yes, I was talking about that: other earphones to go outside, not the on-head big earphones
Had to get my phone unlocked to use other sim cards, if I do factory reset on it or install custom firmware, will I lose the unlock?
>>52289212
? thats not fm2
>>52289240
if he never had thermal paste his cpu would be fried
>>52289265
Earbuds just blow honestly. You're not going to get quality with earbuds.
>>52289240
this is a great meme post 10/10
>>52289283
Funny because it says fm2 on the description
>>52289296
>what are Skullcandy Ink'd Supreme for 800 Alex?
>>52289296
Thank you <3
Is an Associate degree in Cybersecurity worth it? There is no CS (which would be my first choice) in my college.
>>52289315
well thats fucking weird. none of the stores in my country list it as fm2
>>52289349
Depends what you want to do. Honestly you can get the same sort of generic "software dev" opportunities no matter what course you're on, but later on in your career you'll find your skills should let you diverge into a more specific field.
Source: CS degree, have worked with various other disciplines of computing before.
>>52289241
You should buy a new one because
>idle CPU at 67 degrees
>on top of that it's not even OC'd
>it's a great CPU that doesn't need to be upgraded, as you've acknowledged
not only are your current temps likely hurting your performance, but if you get a new heatsink which fixes those temp issues, you can probably even OC it significantly beyond the stock speed.
the 2600k is meant to be overclocked after all
>>52289241
I'm not telling you to buy a new one, I'm telling you I doubt the CPU is getting that hot after 4 years due to the paste unless the one who built the computer fucked up something.
>>52289318
Okay what if I don't want some multicolored bullshit hanging out of my ears like I'm trying to be some jr high kid?
>>52289379
>>52289377
I just took it apart to check.
There is NO paste. There's a coin-sized mark of dried up grey sand, but nothing else.
>>52289415
I hope you realize removing heatsink requires re application of thermal paste before resetting it
also stock heatsinks come with the thermal paste pre-applied, you may be confused about what you're seeing
but you need new thermal paste now regardless
>>52289415
>There's a coin-sized mark of dried up grey sand
That's the paste.
If there was no paste temps will be higher.
>>52289374
I actually wanted a job that involved a lot of coding (or any kind of IT job, working for Walmart is really depressing). I was also considering Web Programming since it is the closest to what I want, I think. Thank you anon.
>>52289241
You don't have to buy a new CPU cooler if you're not overclocking.
Just buy some new thermal paste a remount the cooler.
You can look up a video on youtube on how to properly attach and remove an intel cooler. The intel pushpins can be tricky the first time. Make sure it's on properly, if it's not it will overheat again.
>>52289396
They have black and other less shit colors.
>>52289220
this actually deserves its own thread imo
i think were a long way before we see battle ready exoskeletons. but they're working on it
new thread?
>>52289718
>>52289718
>>52289718
>>52289718
>>52289718
>>52283186
>>52283470
>>52290543
thanks m8s | http://4archive.org/board/g/thread/52277417 | CC-MAIN-2016-44 | refinedweb | 9,897 | 81.02 |
ImportError: No module named IcePy in Raspberry Pi
Hello,
I'm newby with Ice and I'm trying to run the python "Hello World" in my RaspberryPi.
I build a core-image-base (Yocto) with the following BBLAYERS:
BBLAYERS ?= " \
/home/jon/software/yocto/poky-jethro-2.0/meta \
/home/jon/software/yocto/poky-jethro-2.0/meta-yocto \
/home/jon/software/yocto/poky-jethro-2.0/meta-yocto-bsp \
/home/jon/software/yocto/meta-openembedded/meta-oe \
/home/jon/software/yocto/meta-openembedded/meta-filesystems \
/home/jon/software/yocto/meta-openembedded/meta-networking \
/home/jon/software/yocto/meta-openembedded/meta-python \
/home/jon/software/yocto/meta-sdr \
/home/jon/software/yocto/meta-raspberrypi \
"
I have the Server demo running on a standardr PC (java) of the same network.
When a run the Client.py in my Raspberry I get the following Error:
Traceback (most recent call last): File "Client.py", line 1, in <module> import Ice File "/usr/lib/python2.7/site-packages/Ice.py", line 47, in <module> import IcePy ImportError: No module named IcePy
My sys.path print out:
[email protected]:~/development/python# python Python 2.7.9 (default, Oct 26 2016, 17:30:13) [GCC 5.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information.
import sys
sys.path
['', '/gtk-2.0']
What I'm doing wrong?
Best regards
PGaleas
Best Answer
joegeorge Jupiter, FloridaAdministrators, ZeroC Staff Joe GeorgeOrganization: ZeroC, Inc.Project: Ice ZeroC Staff
This is an issue with the meta-zeroc layer. The extension should be named
IcePy.soand not
IcePy.so.3.6.3. I've updated our layer with a fix for this.
Please let me know if this resolves your issue.0
Answers
Hi PGaleas,
It doesn't look like you are using our meta layer. You can find instructions for including our meta-layer on the Using Ice-E with Yocto page of our documenation.
You will also need to be sure you're including our python package as part of your build. Your
local.conffile should contain:
Cheers,
Joe
Hi Joe,
I actually followed the instructions you mentioned. I copied an old BBLayer definition in my last post (sorry for the confusion).
So, my actual BBLAYERS includes
meta-zerocat the end of the string":
I also include in following lines in the
local.conf
The Raspberry's folder
/usr/lib/python2.7/site-packagescontains the file
IcePy.so.3.6.3
But when I try to import the Ice library in the python console, I got the same error I mentioned before:
Any idea?
Thank you for the response.
Cheers
PGaleas
This is an issue with the meta-zeroc layer. The extension should be named
IcePy.soand not
IcePy.so.3.6.3. I've updated our layer with a fix for this.
Please let me know if this resolves your issue.
It works!
Thanks Joe. | https://forums.zeroc.com/discussion/46485/importerror-no-module-named-icepy-in-raspberry-pi | CC-MAIN-2021-21 | refinedweb | 480 | 52.05 |
Abstract
PHP Reader is a well documented small library written in PHP to read and write).
News
- Call for contribution: I have been thinking for some time now about how to make the library more available for everyone. Broader usage could be achieved by converting the library to a new proposal for addition to the Zend Framework.
In doing so the library would automatically get a meaningful namespace (issue 15) of Zend_Media or something similar instead of rather meaningless PhpReader. The code is already quite close to Zend coding conventions and the transformation should be relatively easy.
This is somewhat a large job, so I urge you to contribute to the project in the form of ideas, comments and help in the process of making the library part of Zend Framework.
Have a look at the current to do list, the issues list and think how to best transform this library to fit the requirements of Zend Framework. Contact me directly at sven at vollbehr dot eu using Gtalk or MSN messenger or post a comment to the groups or the issue tracker!
- 02.04.2009 I am excited to announce the next version of PHP Reader 1.7 with more than 30 000 lines of code, featuring:
- Full implementation of Microsoft Advanced Systems Format (ASF) used by Windows Media Audio (WMA), Windows Media Video (WMA) and many other file types
- Many fixes and improvements such as enhanced support for handling different file encodings
- 26.02.2009 I am pleased to announce that the project has got over 4000 downloads!
- 20.02.2009 The library API documentation is now accessible online.
- 06.12.2008 I am excited to announce the next version of PHP Reader 1.6, featuring:
- Full implementation of MPEG Audio Bit Stream (ABS, MP1, MP2, MP3) optimized for fast play duration estimation
- Partial implementation of MPEG Program Stream (MPG, VOB, EVO) used in MPEG movies, and DVD and HD DVD videos for determining play duration
- 01.12.2008 I am pleased to announce that the project has got over 2000 downloads!
Features
The table below lists the features found currently in the latest release. All the classes can also be used separately from each others. See the corresponding links to check the minimum set of required files.
There are also couple of classes used commonly by the above classes.
More
If you need a PHP class to read file information from a format other than what is provided here, please do contact me and I will see what I can do for you. You may post comments and feature requests to the issue tracker or the forum.
If you have passion to code, and would like to share your code to the world, you are always welcome to join the project! -Sven Vollbehr | http://code.google.com/p/php-reader/ | crawl-002 | refinedweb | 466 | 67.49 |
/>
You can calculate the Fibonacci Sequence by starting with 0 and 1 and adding the previous two numbers, but Binet's Formula can be used to directly calculate any term of the sequence. This short project is an implementation of that formula in Python. will consist on two Python files, one containing functions implementing Binet's Formula and the other containing a short piece of code to demonstrate them. Create a new folder somewhere convenient and within it create the following empty files. You can also download the source code as a zip or clone/download from Github if you prefer.
- binetsformula.py
- main.py
Source Code Links
Open binetsformula.py and type or copy/paste this code.
binetsformula.py part 1
import math def binets_formula(n): """ The central function implementing Binet's Formula """ # pre-calculate sqrt(5) as we use it 3 times sqrt5 = math.sqrt(5) F_n = int((( (1 + sqrt5) ** n - (1 - sqrt5) ** n ) / ( 2 ** n * sqrt5 ))) return F_n
After importing math for its sqrt and pow functions we have the function which actually implements Binet's Formula to calculate the value of the Fibonacci Sequence for the given term n. The formula uses √5 no less than three times so I have assigned it to a separate variable, both for efficiency and to make the code slightly more concise.
The next line is Binet's Formula itself, the result of which is assigned to the variable F_n - if you examine it carefully you can see it matches the formula in the form.
((1 + √5)n - (1 - √5)n) / (2n * √5)
Using √5 will force Python to evaluate the formula as a real number so the whole expression is cast to an integer using the int function. Lastly we just need to return F_n.
We can now move on to the second and last function in binetsformula.py.
binetsformula.py part 2
def print_fibonacci_to(n): """ Prints the Fibonacci Sequence to the given term using both addition of the previous two terms and Binet's Formula. """ if n < 2: print("term must be >= 2\n") else: F_n_minus_2 = 0 F_n_minus_1 = 1 F_n_seq = 0 F_n_Binet = 0 # print heading and first two hard-coded terms print("\n Term Sequential Binet OK?\n--------------------------------") print(" 0 {0:3d} ~ ~".format(F_n_minus_2)) print(" 1 {0:3d} ~ ~".format(F_n_minus_1)) for term in range(2, n): # calculate current term both ways F_n_seq = F_n_minus_2 + F_n_minus_1 F_n_Binet = binets_formula(term) print("{0:5d} {1:10d} {2:10d}".format(term, F_n_seq, F_n_Binet), end='') # Check both are the same! if(F_n_Binet == F_n_seq): print(" Y") else: print(" N") # Set previous two terms ready for nect iteration F_n_minus_2 = F_n_minus_1 F_n_minus_1 = F_n_seq
The print_fibonacci_to function calculates and prints the values of the Fibonacci Sequence up to and including the given term n. It does this using two methods, the conventional way of adding the two previous terms and also using Binet's Formula. It also checks the two match, as they always should.
After checking that n.
That's the main coding finished so we just need a short function to try it out. Type or copy/paste this code into main.py.
main.py
import binetsformula def main(): """ Binet's formula calculates any term of the Fibonacci Sequence. Here we just call a function to demo it. """ print("---------------------------") print("| codedrome.com |") print("| Calculating Any Term of |") print("| the Fibonacci Sequence |") print("| Using Binet's Formula |") print("---------------------------") binetsformula.print_fibonacci_to(16) main()
After printing a heading the main function simply calls the binetsformula.print_fibonacci_to function - don't forget to import binetsformula at the top.
The code is now finished so enter the following in your terminal to run it.
Run
python3.7 main.py
The output is
Program Output
---------------------------
| codedrome.com |
| Calculating Any Term of |
| the Fibonacci Sequence |
| Using Binet's Formula |
---------------------------
Term Sequential Binet OK?
--------------------------------
0 0 ~ ~
1 1 ~ ~
2 1 1 Y
3 2 2 Y
4 3 3 Y
5 5 5 Y
6 8 8 Y
7 13 13 Y
8 21 21 Y
9 34 34 Y
10 55 55 Y
11 89 89 Y
12 144 144 Y
13 233 233 Y
14 377 377 Y
15 610 610 Y | https://www.codedrome.com/fibonacci-binets-formula-python/ | CC-MAIN-2021-31 | refinedweb | 689 | 62.07 |
Labels are the simplest of all the AWT components. A label is a component that may contain uneditable text. They are generally limited to single-line messages (Labels, short notes, etc.). They are usually used to identify components. For example: In large GUI, it can be difficult to identify the purpose of every component unless the GUI designer provides labels (i.e. text information stating the purpose of each component).
Unlike any other component, labels do not support any interaction with the user and do not fire any events. So, there is no listener class for the labels .We can create label by creating an instance of Label class.The syntax for creating labels is as shown below:
Label label=new Label();
Label label=new Label(String str);
Label label=new Label(String str, int alignment);
The first form creates a blank label. The other two constructors create labels with the specified string; the third constructor specifies how text is aligned within the label. So, the second argument int.alignment will take the values LabeI.RIGHT, Label.LEFT and LabeI.CENTER, which are constants defined in the Label class. The string used in the label can be obtained using the method get Text(). To set a text for a label the method label.setText("First Label"); is used.
The Label has no surrounding border that might indicate that it's an editable text object. It also has virtually no use in user interaction. For example, you wouldn't normally attempt to detect mouse clicks or other events over the Label.
AWT Label Interface
import java.awt.*;
class Labelframe extends Frame
{
Labelframe()
{
setLayout(new FlowLayout());
Label lblText = new Label("Lable Text");
Label lblTextAlign = new Label("RightAlignment",Label.RIGHT);
add(lblText);
add(lblTextAlign);
}
}
class LabelJavaAwt
{
public static void main(String args[])
{
Labelframe frame = new Labelframe();
frame.setTitle("Label Component");
frame.setSize(150 | http://ecomputernotes.com/java/awt-and-applets/labeljavaawt | CC-MAIN-2020-16 | refinedweb | 310 | 51.65 |
I achived maxlength through ComponentPlugin.
I don't like to extend controls.
Did not yet decided which way is better.
Code:
public class MaxLengthComponentPlugin implements ComponentPlugin<ValueBaseField<?>> { int maxLength = -1; public MaxLengthComponentPlugin(int maxLength) { this.maxLength = maxLength; } @Override public void initPlugin(final ValueBaseField<?> component) { if (component.isRendered() && maxLength > 0) { getInputEl(component).setAttribute("maxLength", "" + maxLength); } component.addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(AttachEvent arg0) { if(maxLength > 0) { getInputEl(component).setAttribute("maxLength", "" + maxLength); } } }); } protected XElement getInputEl(ValueBaseField<?> component) { return XElement.as(component.getCell().getInputElement(component.getElement())); } }
The workaround on setting on the InputElement does not seem to work. I assume this is because the input element is overwritten every time the cell is rendered.
I delved down the Cell/Appearance rabbit hole and managed to get maxlength working with some very messy render overrides. This is definitely something that just belongs in the API.
The key would be adding maxlength to the FieldAppearanceOptions (or more correctly - a new text-specific subclass since this shouldn't affect some fields such as checkboxes). If the change is made there, it won't break anyone's existing code because it just adds getters and setters for maxlength on the options, cells, and fields. The default cell and appearance render methods would need to be updated to call setMaxLength() and getMaxLength() respectively to/from the FieldAppearanceOptions. But this still doesn't break anyone with custom cells and appearances. Even entirely custom render methods will still work - they just won't support maxlength without an update. So yes, you're still getting the "bad code" smell in that regard, but there's not much you can do to stay in sync when such a large and fundamental piece such as render() has to be overridden. Anyone who does so should know that changes at that level carry a certain level of risk and technical debt. Hence, this is why I'd like to reduce my own risk, and just see it in the API.
In any case, those are my thoughts. I can probably contribute code if I can get set up to do so.
- Join Date
- Sep 2011
- Location
- Superior, CO
- 411
- Answers
- 20
- Vote Rating
- 21
@traviter, we've been using the input element solution for several years now from beta2 to 3.0.5 and haven't had any issues.
It is possible that the way you are setting the max length attribute is being clobbered by a re-render. This could happen if you are doing it programmatically at some point in your code that would allow this behavior to occur.
As Colin noted, there are several (and I count at least three) solutions that work in this thread. Surely one of them will work for you. If not, please post your code and we would be happy to try and assist you further.
- Join Date
- Feb 2009
- Location
- Minnesota
- 2,732
- Answers
- 109
- Vote Rating
- 90
I'm not going to touch on the feasibility of the current solutions /workarounds without a code sample that follows one of those paths and *doesnt* work correctly (icfantv seems to be better versed than I on them anyway), but I wanted to comment again on including a solution in GXT itself. If you wish to propose a solution, make sure it works cross browser, and not just in one or two widgets - someone will eventually point out that the feature definitely needs to work in IE 6-8 and opera, and definitely needs to work on TextArea as well as TextField. Quoting from myself earlier in this thread:
First, my references for this:
[1]
[2]
MDN apparently indicates that this is a HTML5 feature [1], which makes me concerned that not all browsers will support this. I then tested a demo [2] in IE8, and found that while the <input> behaved as expected, the <textarea> did not. So for some browsers, our Cell will need event handlers specific to this, trying to make the behavior consistent.
Back to the demo [2] - this page indicates that Opera, which GXT supports, has an alternative implementation. Apparently instead of preventing the user from typing, an in-browser tooltip appears, warning the user that the entered (or pasted! there is another test case to have to handle, in all browsers...) text is too long and should be cut down.
So we're not avoiding this because we're lazy - we're targeting the bugs that are affecting users, and adding the features that won't break existing builds (at least for bugfix releases, 3.1 again may change some APIs), and we've got to take much more care with all browsers and all features than the answers provided in this section. If someone puts together a full solution dealing with all the addressed concerns (that I came up with testing two browsers and writing this in 20 minutes) and would like to sign a CLA to have it contributed, that is more than reasonable - it is welcomed!
Commonplace? Yes. Easy? No. Avoiding? No. No one wins if we just pepper in new features halfbaked and poorly executed, especially while we have a community that can present workarounds, as has happened here.
I was using NumberField and I wanted this maxLength feature like you all do.
My solution (all working so far) is this:
PHP Code:
new NumberField() {
@Override
public void setMaxLength(int m) {
super.setMaxLength(m);
if (rendered) {
getInputEl().setElementAttribute("maxLength", m);
}
}
@Override
public void onRender(Element target, int index) {
super.onRender(target, index);
getInputEl().setElementAttribute("maxLength", getMaxLength());
}
}; | http://www.sencha.com/forum/showthread.php?178262-Setting-max-length-on-TextField&p=944434&viewfull=1 | CC-MAIN-2014-42 | refinedweb | 922 | 62.78 |
Asked by:
Breakpoint on App::OnLaunched does not break
In a simplistic application, when setting the breakpoint on OnLaunched, it never gets there:
// // App.xaml.cpp // Implementation of the App.xaml class. // #include "pch.h" #include "App.xaml.h" #include "MainPage.xaml.h" using namespace Windows::UI::Xaml; using namespace HelloWinRTFromCpp; using namespace Windows::ApplicationModel::Activation; App::App() { InitializeComponent(); <-- It gets here } App::~App() { } void App::OnLaunched(LaunchActivatedEventArgs^ pArgs) { Window::Current->Content = ref new MainPage(); <-- but not here Window::Current->Activate(); }Friday, October 28, 2011 5:26 AM
Question
All replies
- Which template did you choose to build your app? And how are you activating your app? just F5 in the debugger?Friday, October 28, 2011 7:05 PM
- I used the Visual C++ | Windows Metro Style | Application template. This is the simplest application template. Debugging is set to Local Debugger. That's what is activated when I hit F5Friday, October 28, 2011 9:23 PM
- I have experienced situations where the breakpoint is indeed hit but the OS does not switch you to the desktop window, so you are stuck staring at the metro-desktop wondering what's happening. If you manually switch to the classic desktop, you may find VS 2011 waiting for you with the breakpoint hit., October 28, 2011 10:27 PM
- Been there. No breakpoint hit. I looked at some of the recommendations on the Internet to no avail. I'll move to a different machine, but so far it's happening on two of them--VirtualBox.Friday, October 28, 2011 11:08 PM
Can you verify whether the debugger is still attached by manually breaking? Perhaps the debugger is freezing up for some reason.
I know the earlier breakpoint worked. So I am assuming that it's a little later that the debugger dies on you., October 28, 2011 11:11 PM
Any update to Nishant's question? Once you hit your first breakpoint, how far do you get if you F10 from that point forward?
Thanks,
-DavidTuesday, November 1, 2011 5:03 PMModerator | https://social.msdn.microsoft.com/Forums/en-US/789d7878-afac-436f-87b3-c620bf60baab/breakpoint-on-apponlaunched-does-not-break?forum=winappswithnativecode | CC-MAIN-2018-30 | refinedweb | 340 | 58.18 |
).
In order to accommodate this and similar requests, Citrix provides a shared Access Gateway client API library for third party application integration. The shared library is located in the client’s installation folder (e.g.: C:\program files\Citrix\Secure Access Client\). The file name of the C++ library is nscltapi.dll. It exports the following functions to be used in any 3rd party code:
- connected
- setproxy
This blog post is not intended to cover all details about the API but to give you an overview how you can use it to create your own solution and/or what to ask Citrix Consulting for when the need arises. Using the below code snippets, adding a few extra lines of code to make it all look prettier it took some 20 minutes to get something basic as this:
Below examples are written in C# code. Outlined are the basic steps to introduce the exported functions from the Citrix API DLL to your project. After you told your environment that unmanaged code will be used within the project through this instruction,
using System.Runtime.InteropServices;
you can start importing the functions you need and use them afterwards. In the following, the four functions and a quick example on how you may use them will be documented. Not following best practices on how to import a DLL to your project I reference the library with its full path instead of importing it to the project. For your project I suggest to do it right from the beginning 🙂
Function: login
This API function is exported to log in to the NetScaler Access Gateway. It expects the following parameters:
- FQDN
- Username
The shared library defines the function as follows:
int login(char * url, char * username, char * password)
The function returns either a positive integer value indicating a successful tunnel initialization (the return value is then also the id for your VPN session) or it returns a value <=0. The relevant error codes are listed below
Example in C#
[DllImport (“C:/Program Files/Citrix/Secure Access Client/nscltapi.dll”)]
private static extern int login (String URL, String Username, String Password);
int SessionID = login(“”, “David”, “Citrix123”);
Function: logout
This API function is exported to logout from the SSL VPN. It expects the parameters
- SessionID
- Flag
where “SessionID” is the value returned from API login function and “Flag” sets the way the client is going to logout. Possible options are:
0: logout silently without warning prompt.
2: exit without prompt.
4: logout with prompt.
6: exit with prompt.
The shared library defines the function as follows:
int logout(int sessionid, int flag)
For a successful disconnect the logout function return 1, for a failure during logout it reports 0 back to the invoking context.
Example in C#
[DllImport (“C:/Program Files/Citrix/Secure Access Client/nscltapi.dll”)]
private static extern int logout (int SessionID, int flag);
int logout_flag = 0;
int logged_out = logout (SessionID, logout_flag);
Function: connected
This API function is exported to check the status of SSL VPN session. It has no parameters but returns whether or not the Access Gateway plug-in is connected.
Return values are expeted:
0: Not connected to SSL VPN.
1: Connected to SSL VPN.
The shared library defines the function as follows:
int connected()
Example in C#
[DllImport (“C:/Program Files/Citrix/Secure Access Client/nscltapi.dll”)]
private static extern int connected ();
int status = connected();
Function: setproxy
The setproxy function is used to set forward proxy information for the VPN connection.
Forward proxy information lives during the time the shared library is loaded. If the shared library has been unloaded while the program runs, the proxy has to be reset again.
It expects the parameters
- Proxy address
- Proxy dialog
- Authentication method
The shared library defines the function as follows:
int setproxy(char * proxy, int proxydlg, int prefermethod))
Possible formats for the proxy address are:
- domain
- ipaddress
- domain:port
- ipaddress:port
- domain:port:username:password
- ipaddress:port:username:password
Possible options for the proxy dialog, meaning whether to turn on/off the SSL VPN client dialog window for setting the forward proxy credentials:
0: turn on SSL VPN client prompt for forward proxy credentials. (default)
1: turn off SSL VPN client prompt for forward proxy credentials.
Possible methods for the proxy authentication are:
0: Pickup the first available choice from forward proxy returned list. Default.
1: preferred authentication method BASIC
2: preferred authentication method DIGEST
3: preferred authentication method NTLM
The functions returns “0” when setting the forward proxy information failed. This typically happens when the proxy string is longer than the allowed maximum 256 bytes. The value 1 is returned when the forward proxy information is set successfully.
Example in C#
[DllImport (“C:/Program Files/Citrix/Secure Access Client/nscltapi.dll”)]
private static extern int setproxy (String proxy_address, int proxy_dialog, int proxy_method);
int proxy_defined = setproxy (“192.168.0.1:8080”, 0, 0);
With these four functions from the client API of NetScaler Access Gateway it’s relatively easy to implement custom login utilities for very specific use cases. If the above description and examples aren’t of much help for you (despite my best intention), but you need to implement a solution where this API might be useful, please contact Citrix Consulting for guidance on how to use the provided library or of course find other possible ways to accomplish your task at hand.. | https://www.citrix.com/blogs/2013/01/11/build-your-own-vpn-client-with-the-shared-access-gateway-client-api-library/ | CC-MAIN-2017-47 | refinedweb | 892 | 50.06 |
one of your administrators terminates an instance it would be nice if the user identity of that person was recorded. In HAT it displays the fact that it was terminated by a user. This would be much more useful for auditing purposes if it showed which user.
Tracking execution across the BizTalk Group with HAT
Unless ive completely missed this, HAT does not show which server instances execute on within a group. It would be really useful to see for message flow which servers the ports or orchestration shapes run on. You can get scenarios where say a retry would succeed or a shape only faily intermittently and this ability would help with troubleshooting as you could confirm if it is a potential machine related issue.
Expose Maps as providers
Generally you hear mixed opinions about BizTalk mapping (some like it and some dont). Ive worked on projects before where a third party mapping tool was used and this was used. What would be a nice feature would be if maps were implemented in BizTalk using a provider style pattern. This would allow you to develop custom mapping components which could implement the same interface and then be loaded into BizTalk and used as if they were a normal BizTalk map.
At present when you use a third party or custom component you usually end up having to implement a custom pipeline component to call the mapping component. If a pattern as im suggesting was available it would allow these external map providers to implement their mapping capabilities in a way that would keep your BizTalk map implementations consistent
Do we really need the pipeline designer?
As we have per instance pipeline features I think the value of the pipeline designer is now limited. An interesting discussion is should we just get rid of the pipeline artifact and its designer. The alternative would be that the bindings would contain the list of pipeline components which would be used for a pipeline. This would mean you could at runtime add a new pipeline component without having to redeploy your pipeline.
I thought about this as an idea when using the Pipeline Component Test Library which can create a pipeline in code on the fly and then execute it. This is essentially what im saying here, you would specify the make up of the pipeline on a per instance basis in the port configuration which then create a pipeline at runtime as you specify and execute it.
Be interested in anyones thoughts on this - maybe ill try and knock up a sample pipeline component which could demonstrate the concept of this by executing a pipeline within a pipeline :-)
Nested artifacts in BizTalk projects
If you have a BizTalk project and add a folder in it then add a BizTalk artifact to the folder. The artifact does not include the folder name in its namespace (the way classes would in a C# project). I think it would be very useful if it did.
Solicit Response and Errors
I think the development pattern for consuming a solicit response port and being able to handle errors in an orchestration is overly complicated. In most cases you want to do the following scenarios:
The basic problems are as follows:
To be honest I think you just end up with an orchestration which looks a bit of a hack for a process flow which should be fairly simple
Adapter generated schemas create an orchestration
When you use the adapter metadata generation wizards to produce a schema to call your service (WCF, SQL, SOAP, etc) they always produce an emply orchestration file (which im guessing someone who has never done a BizTalk project thought would be very cool). This really annoys me because any real project is going to probably have orchestrations in a different assembly anyway. If it atleast contained a half implemented orchestration it might be useful but everyone I know just deletes them, so it would be useful if they just werent produced in the first place.
Passwords in BizTalk Admin Console/Exported Bindings
It would be really useful if you were in the BizTalk Administrator Group and you were viewing a ports configuration if you could have an option to see password type values in clear text. As you are the administrator you will have entered these credentials anyway but it allows you to confirm you have entered it correctly.
The same also applies to an administrator wanting to export the bindings, by default it should be as is, but I should have an option (if im in the BizTalk admin group) to be able to have the password type values in clear text. This saves me ages in having to go and manually change the file which I might get wrong.
These are the off the top of my head list of things for now. As things come up ill add more later.
Print | posted on Sunday, April 27, 2008 4:52 PM |
Filed Under [
BizTalk
BizTalk Wishlist
] | http://geekswithblogs.net/michaelstephenson/archive/2008/04/27/121686.aspx | crawl-002 | refinedweb | 835 | 53.55 |
Brief intro to regular expressions
Posted March 03, 2013 at 03:04 PM | categories: regular expressions | tags:
This example shows how to use a regular expression to find strings matching the pattern :cmd:`datastring`. We want to find these strings, and then replace them with something that depends on what cmd is, and what datastring is.
Let us define some commands that will take datasring as an argument, and return the modified text. The idea is to find all the cmds, and then run them. We use python's
eval command to get the function handle from a string, and the cmd functions all take a datastring argument (we define them that way). We will create commands to replace :cmd:`datastring` with html code for a light gray background, and :red:`some text` with html code making the text red.
text = r'''Here is some text. use the :cmd:`open` to get the text into a variable. It might also be possible to get a multiline :red:`line 2` directive.''' print text print '---------------------------------'
... ... >>> >>> Here is some text. use the :cmd:`open` to get the text into a variable. It might also be possible to get a multiline :red:`line 2` directive. ---------------------------------
Now, we define our functions.
def cmd(datastring): ' replace :cmd:`datastring` with html code with light gray background' s = '<FONT style="BACKGROUND-COLOR: LightGray">%{0}</FONT>'; html = s.format(datastring) return html def red(datastring): 'replace :red:`datastring` with html code to make datastring in red font' html = '<font color=red>{0}</font>'.format(datastring) return html
Finally, we do the regular expression. python stores so we can refer to them later.
import re regex = ':([^:]*):`([^`]*)`' matches = re.findall(regex, text) for directive, datastring in matches: directive = eval(directive) # get the function text = re.sub(regex, directive(datastring), text) print 'Modified text:' print text
>>> >>> ... ... ... >>> Modified text: Here is some text. use the <FONT style="BACKGROUND-COLOR: LightGray">%open</FONT> to get the text into a variable. It might also be possible to get a multiline <FONT style="BACKGROUND-COLOR: LightGray">%open</FONT> directive.
Copyright (C) 2013 by John Kitchin. See the License for information about copying. | https://kitchingroup.cheme.cmu.edu/blog/2013/03/03/Brief-intro-to-regular-expressions/ | CC-MAIN-2021-31 | refinedweb | 356 | 67.55 |
Backbone and archive it. In order to keep this post's length reasonable, we will not include any communication with a database. All the data will be kept on the client-side.
Setup
Here is the file structure which we'll use:
css └── styles.css js └── collections └── ToDos.js └── models └── ToDo.js └── vendor └── backbone.js └── jquery-1.10.2.min.js └── underscore.js └── views └── App.js └── index.html
There are few things which are obvious, like
/css/styles.css and
/index.html. They contain the CSS styles and the HTML markup. In the context of Backbone.js, the model is a place where we keep our data. So, our ToDos will simply be models. And because we will have more than one task, we will organize them into a collection. The business logic is distributed between the views and the main application's file,
App.js. Backbone.js has only one hard dependency - Underscore.js. The framework also plays very well with jQuery, so they both go to the
vendor directory. All we need now is just a little HTML markup and we are ready to go.
<!doctype html> <html> <head> <title>My TODOs</title> <link rel="stylesheet" type="text/css" href="css/styles.css" /> </head> <body> <div class="container"> <div id="menu" class="menu cf"></div> <h1></h1> <div id="content"></div> </div> <script src="js/vendor/jquery-1.10.2.min.js"></script> <script src="js/vendor/underscore.js"></script> <script src="js/vendor/backbone.js"></script> <script src="js/App.js"></script> <script src="js/models/ToDo.js"></script> <script src="js/collections/ToDos.js"></script> <script> window.onload = function() { // bootstrap } </script> </body> </html>
As you can see, we are including all the external JavaScript files towards the bottom, as it's a good practice to do this at the end of the body tag. We are also preparing the bootstrapping of the application. There is container for the content, a menu and a title. The main navigation is a static element and we are not going to change it. We will replace the content of the title and the
div below it.
Planning the Application
It's always good to have a plan before we start working on something. Backbone.js doesn't have a super strict architecture, which we have to follow. That's one of the benefits of the framework. So, before we start with the implementation of the business logic, let's talk about the basis.
Namespacing
A good practice is to put your code into its own scope. Registering global variables or functions is not a good idea. What we will create is one model, one collection, a router and few Backbone.js views. All these elements should live in a private space.
App.js will contain the class which holds everything.
// App.js var app = (function() { var api = { views: {}, models: {}, collections: {}, content: null, router: null, todos: null, init: function() { this.content = $("#content"); }, changeContent: function(el) { this.content.empty().append(el); return this; }, title: function(str) { $("h1").text(str); return this; } }; var ViewsFactory = {}; var Router = Backbone.Router.extend({}); api.router = new Router(); return api; })();
Above is a typical implementation of the revealing module pattern. The
api variable is the object which is returned and represents the public methods of the class. The
views,
models and
collections properties will act as holders for the classes returned by Backbone.js. The
content is a jQuery element pointing to the main user's interface container. There are two helper methods here. The first one updates that container. The second one sets the page's title. Then we defined a module called
ViewsFactory. It will deliver our views and at the end, we created the router.
You may ask, why do we need a factory for the views? Well, there are some common patterns while working with Backbone.js. One of them is related to the creation and usage of the views.
var ViewClass = Backbone.View.extend({ /* logic here */ }); var view = new ViewClass();
It's good to initialize the views only once and leave them alive. Once the data is changed, we normally call methods of the view and update the content of its
el object. The other very popular approach, is to recreate the whole view or replace the whole DOM element. However, that's not really good from a performance point of view. So, we normally end up with a utility class which creates one instance of the view and returns it when we need it.
Components Definition
We have a namespace, so now we can start creating components. Here is how the main menu looks:
// views/menu.js app.views.menu = Backbone.View.extend({ initialize: function() {}, render: function() {} });
We created a property called
menu which holds the class of the navigation. Later, we may add a method in the factory module which creates an instance of it.
var ViewsFactory = { menu: function() { if(!this.menuView) { this.menuView = new api.views.menu({ el: $("#menu") }); } return this.menuView; } };
Above is how we will handle all of the views, and it will ensure that we get only one and of the same instance. This technique works well, in most cases.
Flow
The entry point of the app is
App.js and its
init method. This is what we will call in the
onload handler of the
window object.
window.onload = function() { app.init(); }
After that, the defined router takes control. Based on the URL, it decides which handler to execute. In Backbone.js, we don't have the usual Model-View-Controller architecture. The Controller is missing and most of the logic is put into the views. So instead, we wire the models directly to methods, inside the views and get an instant update of the user interface, once the data has changed.
Managing the Data
The most important thing in our small project is the data. Our tasks are what we should manage, so let's start from there. Here is our model definition.
// models/ToDo.js app.models.ToDo = Backbone.Model.extend({ defaults: { title: "ToDo", archived: false, done: false } });
Just three fields. The first one contains the text of the task and the other two are flags which define the status of the record.
Every thing inside the framework is actually an event dispatcher. And because the model is changed with setters, the framework knows when the data is updated and can notify the rest of the system for that. Once you bind something to these notifications, your application will react on the changes in the model. This is a really powerful feature in Backbone.js.
As I said in the beginning, we will have many records and we will organize them into a collection called
ToDos.
// collections/ToDos.js app.collections.ToDos = Backbone.Collection.extend({ initialize: function(){ this.add({ title: "Learn JavaScript basics" }); this.add({ title: "Go to backbonejs.org" }); this.add({ title: "Develop a Backbone application" }); }, model: app.models.ToDo up: function(index) { if(index > 0) { var tmp = this.models[index-1]; this.models[index-1] = this.models[index]; this.models[index] = tmp; this.trigger("change"); } }, down: function(index) { if(index < this.models.length-1) { var tmp = this.models[index+1]; this.models[index+1] = this.models[index]; this.models[index] = tmp; this.trigger("change"); } }, archive: function(archived, index) { this.models[index].set("archived", archived); }, changeStatus: function(done, index) { this.models[index].set("done", done); } });
The
initialize method is the entry point of the collection. In our case, we added a few tasks by default. Of course in the real world, the information will come from a database or somewhere else. But to keep you focused, we will do that manually. The other thing which is typical for collections, is setting the
model property. It tells the class what kind of data is being stored. The rest of the methods implement custom logic, related to the features in our application.
up and
down functions change the order of the ToDos. To simplify things, we will identify every ToDo with just an index in the collection's array. This means that if we want to fetch one specific record, we should point to its index. So, the ordering is just switching the elements in an array. As you may guess from the code above,
this.models is the array which we are talking about.
archive and
changeStatus set properties of the given element. We put these methods here, because the views will have access to the
ToDos collection and not to the tasks directly.
Additionally, we don't need to create any models from the
app.models.ToDo class, but we do need to create an instance from the
app.collections.ToDos collection.
// App.js init: function() { this.content = $("#content"); this.todos = new api.collections.ToDos(); return this; }
Showing Our First View (Main Navigation)
The first thing which we have to show, is the main application's navigation.
// views/menu.js app.views.menu = Backbone.View.extend({ template: _.template($("#tpl-menu").html()), initialize: function() { this.render(); }, render: function(){ this.$el.html(this.template({})); } });
It's only nine lines of code, but lots of cool things are happening here. The first one is setting a template. If you remember, we added Underscore.js to our app? We are going to use its templating engine, because it works good and it is simple enough to use.
_.template(templateString, [data], [settings])
What you have at the end, is a function which accepts an object holding your information in key-value pairs and the
templateString is HTML markup. Ok, so it accepts an HTML string, but what is
$("#tpl-menu").html() doing there? When we are developing a small single page application, we normally put the templates directly into the page like this:
// index.html <script type="text/template" id="tpl-menu"> <ul> <li><a href="#">List</a></li> <li><a href="#archive">Archive</a></li> <li class="right"><a href="#new">+</a></li> </ul> </script>
And because it's a script tag, it is not shown to the user. From another point of view, it is a valid DOM node so we could get its content with jQuery. So, the short snippet above just takes the content of that script tag.
The
render method is really important in Backbone.js. That's the function which displays the data. Normally you bind the events fired by the models directly to that method. However, for the main menu, we don't need such behavior.
this.$el.html(this.template({}));
this.$el is an object created by the framework and every view has it by default (there is a
$ infront of
el because we have jQuery included). And by default, it is an empty
<div></div>. Of course you may change that by using the
tagName property. But what is more important here, is that we are not assigning a value to that object directly. We are not changing it, we are changing only its content. There is a big difference between the line above and this next one:
this.$el = $(this.template({}));
The point is, that if you want to see the changes in the browser you should call the render method before, to append the view to the DOM. Otherwise only the empty div will be attached. There is also another scenario where you have nested views. And because you are changing the property directly, the parent component is not updated. The bound events may also be broken and you need to attach the listeners again. So, you really should only change the content of
this.$el and not the property's value.
The view is now ready and we need to initialize it. Let's add it to our factory module:
// App.js var ViewsFactory = { menu: function() { if(!this.menuView) { this.menuView = new api.views.menu({ el: $("#menu") }); } return this.menuView; } };
At the end simply call the
menu method in the bootstrapping area:
// App.js init: function() { this.content = $("#content"); this.todos = new api.collections.ToDos(); ViewsFactory.menu(); return this; }
Notice that while we are creating a new instance from the navigation's class, we are passing an already existing DOM element
$("#menu"). So, the
this.$el property inside the view is actually pointing to
Adding Routes
Backbone.js supports the push state operations. In other words, you may manipulate the current browser's URL and travel between pages. However, we'll stick with the good old hash type URLs, for example
/#edit/3.
// App.js var Router = Backbone.Router.extend({ routes: { "archive": "archive", "new": "newToDo", "edit/:index": "editToDo", "delete/:index": "delteToDo", "": "list" }, list: function(archive) {}, archive: function() {}, newToDo: function() {}, editToDo: function(index) {}, delteToDo: function(index) {} });
Above is our router. There are five routes defined in a hash object. The key is what you will type in the browser's address bar and the value is the function which will be called. Notice that there is
:index on two of the routes. That's the syntax which you need to use if you want to support dynamic URLs. In our case, if you type
#edit/3 the
editToDo will be executed with parameter
index=3. The last row contains an empty string which means that it handles the home page of our application.
Showing a List of All the Tasks
So far what we've built is the main view for our project. It will retrieve the data from the collection and print it out on the screen. We could use the same view for two things - displaying all the active ToDos and showing those which are archived.
Before to continue with the list view implementation, let's see how it is actually initialized.
// in App.js views factory list: function() { if(!this.listView) { this.listView = new api.views.list({ model: api.todos }); } return this.listView; }
Notice that we are passing in the collection. That's important because we will later use
this.model to access the stored data. The factory returns our list view, but the router is the guy who has to add it to the page.
// in App.js's router list: function(archive) { var view = ViewsFactory.list(); api .title(archive ? "Archive:" : "Your ToDos:") .changeContent(view.$el); view.setMode(archive ? "archive" : null).render(); }
For now, the method
list in the router is called without any parameters. So the view is not in
archive mode, it will show only the active ToDos.
// views/list.js app.views.list = Backbone.View.extend({ mode: null, events: {}, initialize: function() { var handler = _.bind(this.render, this); this.model.bind('change', handler); this.model.bind('add', handler); this.model.bind('remove', handler); }, render: function() {}, priorityUp: function(e) {}, priorityDown: function(e) {}, archive: function(e) {}, changeStatus: function(e) {}, setMode: function(mode) { this.mode = mode; return this; } });
The
mode property will be used during the rendering. If its value is
mode="archive" then only the archived ToDos will be shown. The
events is an object which we will fill right away. That's the place where we place the DOM events mapping. The rest of the methods are responses of the user interaction and they are directly linked to the needed features. For example,
priorityUp and
priorityDown changes the ordering of the ToDos.
archive moves the item to the archive area.
changeStatus simply marks the ToDo as done.
It's interesting what is happening inside the
initialize method. Earlier we said that normally you will bind the changes in the model (the collection in our case) to the
render method of the view. You may type
this.model.bind('change', this.render). But very soon you will notice that the
this keyword, in the
render method will not point to the view itself. That's because the scope is changed. As a workaround, we are creating a handler with an already defined scope. That's what Underscore's
bind function is used for.
And here is the implementation of the
render method.
// views/list.js render: function() {) var html = '<ul class="list">', self = this; this.model.each(function(todo, index) { if(self.mode === "archive" ? todo.get("archived") === true : todo.get("archived") === false) { var template = _.template($("#tpl-list-item").html()); html += template({ title: todo.get("title"), index: index, archiveLink: self.mode === "archive" ? "unarchive" : "archive", done: todo.get("done") ? "yes" : "no", doneChecked: todo.get("done") ? 'checked=="checked"' : "" }); } }); html += '</ul>'; this.$el.html(html); this.delegateEvents(); return this; }
We are looping through all the models in the collection and generating an HTML string, which is later inserted into the view's DOM element. There are few checks which distinguish the ToDos from archived to active. The task is marked as done with the help of a checkbox. So, to indicate this we need to pass a
checked=="checked" attribute to that element. You may notice that we are using
this.delegateEvents(). In our case this is necessary, because we are detaching and attaching the view from the DOM. Yes, we are not replacing the main element, but the events' handlers are removed. That's why we have to tell Backbone.js to attach them again. The template used in the code above is:
// index.html <script type="text/template" id="tpl-list-item"> <li class="cf done-<%= done %>" data- <h2> <input type="checkbox" data-status <%= doneChecked %> /> <a href="javascript:void(0);" data-up>↑</a> <a href="javascript:void(0);" data-down>↓</a> <%= title %> </h2> <div class="options"> <a href="#edit/<%= index %>">edit</a> <a href="javascript:void(0);" data-archive><%= archiveLink %></a> <a href="#delete/<%= index %>">delete</a> </div> </li> </script>
Notice that there is a CSS class defined called
done-yes, which paints the ToDo with a green background. Besides that, there are a bunch of links which we will use to implement the needed functionality. They all have data attributes. The main node of the element,
li, has
data-index. The value of this attribute is showing the index of the task in the collection. Notice that the special expressions wrapped in
<%= ... %> are sent to the
template function. That's the data which is injected into the template.
It's time to add some events to the view.
// views/list.js events: { 'click a[data-up]': 'priorityUp', 'click a[data-down]': 'priorityDown', 'click a[data-archive]': 'archive', 'click input[data-status]': 'changeStatus' }
In Backbone.js the event's definition is a just a hash. You firstly type the name of the event and then a selector. The values of the properties are actually methods of the view.
// views/list.js priorityUp: function(e) { var index = parseInt(e.target.parentNode.parentNode.getAttribute("data-index")); this.model.up(index); }, priorityDown: function(e) { var index = parseInt(e.target.parentNode.parentNode.getAttribute("data-index")); this.model.down(index); }, archive: function(e) { var index = parseInt(e.target.parentNode.parentNode.getAttribute("data-index")); this.model.archive(this.mode !== "archive", index); }, changeStatus: function(e) { var index = parseInt(e.target.parentNode.parentNode.getAttribute("data-index")); this.model.changeStatus(e.target.checked, index); }
Here we are using
e.target coming in to the handler. It points to the DOM element which triggered the event. We are getting the index of the clicked ToDo and updating the model in the collection. With these four functions we finished our class and now the data is shown to the page.
As we mentioned above, we will use the same view for the
Archive page.
list: function(archive) { var view = ViewsFactory.list(); api .title(archive ? "Archive:" : "Your ToDos:") .changeContent(view.$el); view.setMode(archive ? "archive" : null).render(); }, archive: function() { this.list(true); }
Above is the same route handler as before, but this time with
true as a parameter.
Adding & Editing ToDos
Following the primer of the list view, we could create another one which shows a form for adding and editing tasks. Here is how this new class is created:
// App.js / views factory form: function() { if(!this.formView) { this.formView = new api.views.form({ model: api.todos }).on("saved", function() { api.router.navigate("", {trigger: true}); }) } return this.formView; }
Pretty much the same. However, this time we need to do something once the form is submitted. And that's forward the user to the home page. As I said, every object which extends Backbone.js classes, is actually an event dispatcher. There are methods like
on and
trigger which you can use.
Before we continue with the view code, let's take a look at the HTML template:
<script type="text/template" id="tpl-form"> <form> <textarea><%= title %></textarea> <button>save</button> </form> </script>
We have a
textarea and a
button. The template expects a
title parameter which should be an empty string, if we are adding a new task.
// views/form.js app.views.form = Backbone.View.extend({ index: false, events: { 'click button': 'save' }, initialize: function() { this.render(); }, render: function(index) { var template, html = $("#tpl-form").html(); if(typeof index == 'undefined') { this.index = false; template = _.template(html, { title: ""}); } else { this.index = parseInt(index); this.todoForEditing = this.model.at(this.index); template = _.template($("#tpl-form").html(), { title: this.todoForEditing.get("title") }); } this.$el.html(template); this.$el.find("textarea").focus(); this.delegateEvents(); return this; }, save: function(e) { e.preventDefault(); var title = this.$el.find("textarea").val(); if(title == "") { alert("Empty textarea!"); return; } if(this.index !== false) { this.todoForEditing.set("title", title); } else { this.model.add({ title: title }); } this.trigger("saved"); } });
The view is just 40 lines of code, but it does its job well. There is only one event attached and this is the clicking of the save button. The render method acts differently depending of the passed
index parameter. For example, if we are editing a ToDo, we pass the index and fetch the exact model. If not, then the form is empty and a new task will be created. There are several interesting points in the code above. First, in the rendering we used the
.focus() method to bring the focus to the form once the view is rendered. Again the
delegateEvents function should be called, because the form could be detached and attached again. The
save method starts with
e.preventDefault(). This removes the default behavior of the button, which in some cases may be submitting the form. And at the end, once everything is done we triggered the
saved event notifying the outside world that the ToDo is saved into the collection.
There are two methods for the router which we have to fill in.
// App.js newToDo: function() { var view = ViewsFactory.form(); api.title("Create new ToDo:").changeContent(view.$el); view.render() }, editToDo: function(index) { var view = ViewsFactory.form(); api.title("Edit:").changeContent(view.$el); view.render(index); }
The difference between them is that we pass in an index, if the
edit/:index route is matched. And of course the title of the page is changed accordingly.
Deleting a Record From the Collection
For this feature, we don't need a view. The entire job can be done directly in the router's handler.
delteToDo: function(index) { api.todos.remove(api.todos.at(parseInt(index))); api.router.navigate("", {trigger: true}); }
We know the index of the ToDo which we want to delete. There is a
remove method in the collection class which accepts a model object. At the end, just forward the user to the home page, which shows the updated list.
Conclusion
Backbone.js has everything you need for building a fully functional, single page application. We could even bind it to a REST back-end service and the framework will synchronize the data between your app and the database. The event driven approach encourages modular programming, along with a good architecture. I'm personally using Backbone.js for several projects and it works very<< | https://code.tutsplus.com/tutorials/single-page-todo-application-with-backbonejs--cms-21417?ec_unit=translation-info-language | CC-MAIN-2021-04 | refinedweb | 3,940 | 60.72 |
One of my pet peeves regarding PHP is the terseness of the error messages it throws. Not that they are unhelpful; the major headache it that one has to open the source file at the given error location to check for problems. Also the complete system context (the PHP system variables, cookies, session etc.) is not easily available.
Whoops is a nice little library that helps you develop and maintain your PHP projects better, by helping you deal with errors and exceptions in a user friendly way. Whoops is already a part of Laravel 4, and includes providers for Silex and Zend Framework 2.
Take the following simple code.
Executing this throws the following PHP error.
The same error with Whoops enabled is shown below (click for a larger view). The actual error page contains even more information than given here – session variables, cookies, HTTP headers etc.
Installing Whoops
Whoops can be easily installed by using Composer by adding the following lines to the
composer.json file. If you are unfamiliar with Composer you can do a manual install instead by downloading the Zip file.
Whoops uses PHP namespaces and includes many classes so it is better to use your frameworks auto-loading feature to load the Whoop libraries from your project files. Still, if you need to add Whoops to any applications that does not have auto-loading you can directly reference the relevant Whoops classes as shown in the following example.
You can even add some additional information to the error page with the following
There are many more options to Whoops, the details regarding which can be found here. The ones given above however will be enough for most projects. | http://www.codediesel.com/php/pretty-error-display-for-php/ | CC-MAIN-2017-04 | refinedweb | 283 | 62.17 |
NaN in C++ with examples
NaN is used for indicating a number that cannot be represented. For example, the square root of negative numbers, zero divided by zero, etc. NaN stands for “Not a Number”. In this tutorial, we will see some examples of nan in C++.
Have a look at this C++ program to understand what is nan.
#include <iostream> #include <cmath> using namespace std; int main() { int num=-2; cout << "sqrt(-2) = " << sqrt(num); return 0; }
Output:
sqrt(-2) = nan
As you can see in the example program, we have initialized a variable num with value -2. Now when we try to find the square root of this number using built-in sqrt() function, we get the result as nan(not a number).
Another example of nan in C++ can be given as the following program. See the below code.
#include <iostream> #include <cmath> using namespace std; int main() { float num = 0.0; cout << "(0.0/0.0) = " << (num/num); return 0; }
Output:
(0.0/0.0) = nan
How to check whether a number is NaN or not
We can check whether a number is a nan or not using the following approaches.
- using isnan()
- using comparison operator(==)
Method 1: using isnan()
This function returns true if the passed parameter is not a number i.e. a nan value. Have a look at the below-given example code to clear any doubt.
#include <iostream> #include <cmath> using namespace std; int main() { float num = 0.0; float res = num/num; if (isnan(res)) { cout << "(0.0/0.0) is not a number(nan).\n"; } else cout << "(0.0/0.0) is a number.\n"; return 0; }
The output for the above program is:
(0.0/0.0) is not a number(nan).
Method 2: using “==” operator
There is an interesting property of nan values and that is that they return false when compared to themselves. Which means the following expression will give the result as false.
(nan == nan)
See the following example program to check for a nan value using “==” operator.
#include <iostream> #include <cmath> using namespace std; int main() { float num = -5; float res = sqrt(num); if (res == res) { cout << "sqrt(-5) is a number.\n"; } else cout << "sqrt(-5) is not a number(nan).\n"; return 0; }
Output:
sqrt(-5) is not a number(nan).
I hope you understand what is NaN in C++ from this article.
Thank you.
Also read: Swapping two numbers using bitwise operator in C++ | https://www.codespeedy.com/nan-in-c-with-examples/ | CC-MAIN-2021-10 | refinedweb | 412 | 76.22 |
namespaces, classes and template friend functions
Discussion in 'C++' started by mojmir, Sep 12, 2008.
- Similar Threads
template functions calls within non template classes. How to do it?claude uq, Dec 18, 2003, in forum: C++
- Replies:
- 3
- Views:
- 725
- tom_usenet
- Dec 18, 2003
Friend functions and template classesAdam Parkin, Apr 22, 2004, in forum: C++
- Replies:
- 6
- Views:
- 697
- Victor Bazarov
- Apr 24, 2004
Template Member Functions of Template Classes, Feb 5, 2006, in forum: C++
- Replies:
- 2
- Views:
- 461
- Kai-Uwe Bux
- Feb 5, 2006
friend classes and functionsJess, May 20, 2007, in forum: C++
- Replies:
- 1
- Views:
- 369
- John Harrison
- May 20, 2007
How can I declare and define a friend template function in a template class?=?gb2312?B?wfXquw==?=, Jul 31, 2007, in forum: C++
- Replies:
- 10
- Views:
- 919
- Victor Bazarov
- Aug 1, 2007
Anonymous namespaces and friend functionsRonald Raygun, Apr 1, 2008, in forum: C++
- Replies:
- 5
- Views:
- 708
- James Kanze
- Apr 2, 2008
overloading non-template member functions with template member functionsHicham Mouline, Apr 23, 2009, in forum: C++
- Replies:
- 0
- Views:
- 631
- Hicham Mouline
- Apr 23, 2009
- Replies:
- 1
- Views:
- 696
- Alf P. Steinbach /Usenet
- Aug 25, 2010 | http://www.thecodingforums.com/threads/namespaces-classes-and-template-friend-functions.635058/ | CC-MAIN-2016-30 | refinedweb | 195 | 64.88 |
Snippets
Jason has posted 22 posts at DZone. View Full User Profile
JavaScript function that determines if a variable is a proper Date object including a valid date.
function isDate (x)
{
return (null != x) && !isNaN(x) && ("undefined" !== typeof x.getDate);
}
@Snippets Manager: thanks for the help -- this was better than the answers I found on SO!
Discover best practices and the most useful tools for building the ideal integration architecture.
DZone's 170th Refcard is an essential reference to Camel, an open-source, lightweight, integration library. This Refcard is authored by...
Charles Beebe replied on Tue, 2012/05/15 - 10:36am
@Snippets Manager: thanks for the help -- this was better than the answers I found on SO!
Jason McDonald replied on Wed, 2007/05/16 - 7:11pm
Snippets Manager replied on Sun, 2009/03/01 - 8:43pm | http://www.dzone.com/snippets/javascript-isdate-function | CC-MAIN-2014-52 | refinedweb | 137 | 65.93 |
Building a Safe Cracking Robot
Introduction.
We were able to crack our Craigslist safe in 40 minutes and 42 seconds! You can re-watch the live cracking, if you'd like. The magic moment occurs at 45:20, but start around 44:30 to get the full scope of what's happening..
Isn't this a bad.
Build Your Own!
We’ve documented and shared all the lessons we’ve learned in hopes that you can possibly build your own. You’ll need a 3D printer, soldering iron, and the ability to write code and modify 3D files to fit the type of safe you’re trying to open.
This is a complex build so here’s a list of documents:
- Eagle files for the PCB
- Schematic
- Arduino based firmware
- 3D files for the dial coupler and handle puller
- 3D model of the safe
- SparkFun parts list
- Additional Parts:
- $40 DC gearhead motor
- Three BCA6 magnets worked very well
- Custom PCB (order from your favorite fab house)
All in all, we've spent about $200 on our safe cracker, which is a fraction of what professional devices cost.
For the latest files, check out the repo here.
Dial and Coupler
The dial on our safe was modeled, and a coupler was 3D printed. This was attached to our motor with a 6mm clamping hub. We found that hubs with set screws would loosen quickly and wreak havoc with our control algorithms. Use a clamping hub!
We used a motor from Pololu for $40 that has the following specs
- 12V motor
- 350mA Free Run
- 5A stall
- 80RPM
- 8400 counts per revolution
The counts per revolution was most important. We wanted a lower cost motor that had LOTS of resolution to measure the internal indents in disc C (covered in a later section). 12V was good because we had used a similar power supply and display for our Speed Trap project.
The encoder uses two interrupt pins connected to the interrupt pins on the Arduino. Once we zero the dial, the step count is used to determine on which digit the dial is.
Quick example:
100 / 8400 = 84 ticks per digit 3226 steps = dial number 34
It’s worth noting that the tolerances of the coupler to dial and the rigidness of the hub and motor mounts are important. Any slack in the system will cause problems later.
Home Calibration
We tried a few different methods to calibrate the dial. Originally, we tried a reed switch with a magnet built into the 3D printed coupler. This was a horrible idea: reed switches detect relative proximity but are bad at detecting exact location. I had a few instances where the reed switch would open when the magnet was directly under the switch and close again when the magnet moved a few millimeters away. Don’t use a reed switch.
We ended up using a photogate with a small flag designed into the coupler. It’s straightforward to detect when the gate is broken by the flag. When the robot is magnetically attached to the safe, the dial is in an unknown position. There’s an offset variable that can be set so that when you say, "go home", the robot figures out that the flag is at dial position 43, and it needs to travel 57 more to arrive at home.
Once calibrated (and after lots of code revisions), we found that the control of the dial was very reliable. During cracking, we recalibrate every time we adjust disc A just to be safe.
Handle Puller
We tried a few different methods to non-permanently attach to the handle. First, we had to model the safe handle then design and print a connector. It’s basically a shroud with an idler pin to rotate around with a 40 lbs cord attached to the end of the shroud. A small spring is used to bring the shroud and handle back to return position when the servo returns to the rest position. You don’t want to let the handle rest under its own weight or it might fall onto the dials and get caught in the indents on disc C.
We really wanted to use an off-the-shelf servo for cost and ease of use. A basic 83 oz-in servo worked ok, but it didn’t have enough throw to guarantee that it could pull the handle down far enough to the open position. Rob had the breakthrough: using a nautilus design we can apply increasing torque to the handle as the servo head pulls on the string. It works extremely well.
Additionally, we modified our servo to give us analog feedback (there are good tutorials 1 and 2 on how to do this). Analog feedback is important; when you tell the servo head to go to position 175, did it actually get there? Doing an
analogRead() lets us know if we’ve arrived.
To detect if the safe is opened, we tell the servo to pull on the handle by going to PWM value 80. If we've dialed in the right combination, the the servo is free to fully pull down and move to this PWM value. The analog value when the handle is pulled down is approximately 273. If the servo gets blocked (wrong combination) the servo’s analog feedback will be less than 250. The
tryHandle() function does all this for us and returns true if the analog feedback goes above 260. The PWM and analog values will be different for each robot setup, so we've written a few functions to manually adjust the servo to get the opening conditions.
Brains
We used the trusty RedBoard to control everything. The Safe Cracker shield is a simple two layer PCB.
Bits on the shield:
- The 12V/5V power supply provides the power to the current sensor and motor controller.
- Current sensor: We originally planned on using the current sensor to detect motor stall when the edge of an indent in disc C was hit. It turned out being much faster and more accurate to detect the indent edge with the encoder; if the encoder had not changed in 5 milliseconds then the motor was stopped and we had hit the edge of the indent.
- Motor controller: 15A was more than enough to handle the motor’s 5A stall current
- Servo connector with feedback
- Photogate connector
- Display connector for the large 6.5” 7-segment display (needed only for our live stream event)
- Buzzer to announce when we’ve cracked it
- ‘GO’ button connector if we wanted to make the apparatus headless
Code
You can find the firmware here. While the code to control the SparkFun Safe Cracker got a bit large, it’s fairly straight forward. In essence, we go to a given dial location, pull on the handle, see if the handle moved far enough that we’re open, repeat. Additionally, we created functions to allow us to measure, as precisely as possible, the widths of the indents on disc C.
Frame
To build an apparatus that could be easily and quickly attached to our safe, we first modeled the safe in 3D.
The frame is built with Actobotics parts with magnets hot glued to the three feet. The magnets provide excellent adhesive strength while still being able to attach and detach the robot.
The handle cover, coupler, base plate to hold the electronics, and nautilus gear were printed on our trusty Taz 6 printer.
This frame is specifically designed for our model safe, but the variety of Actobotics parts and the ability to print custom parts means the SparkFun Safe Cracker could be modified to fit any particular model of safe.
How Combination Safes Work
In order to understand some of the shortcuts we took, you’ll need to know how the discs inside a combination lock operate. Here’s a quick primer!
If you’ve ever used a combination padlock you know the basics:
- Spin the dial a few times to reset everything
- Turn the dial in a certain direction until you get to the first combination number. Let’s call that AA.
- Turn the dial in the opposite direction one full turn, then continue until you get to the second number - BB
- Turn the dial in the opposite direction until get you get to the third number - CC
- Pull on the handle to open lock
The most common padlocks have a dial from 0 to 39 with a combination AA/BB/CC. Combination safes work exactly the same but with larger dials, usually 0 to 99. Some safes have additional combination numbers (for example: AA/BB/CC/DD/EE), but the general home-store fire safe is 3 numbers.
But, how do the internals of a combination safe actually work?
Here’s a video to show you the basics:
There are three discs, let’s call them discs A, B and C. Each disc has a notch in it called a gate. When you pull down on the handle, a rod (sometimes called the fence) hits the three dials. If the three gates are lined up correctly, the rod slides into the notches. This allows the handle to travel far enough to disengage the lock on the door, and the safe can be opened.
Turning the dial on the outside of the lock directly controls disc C (sometimes called the drive wheel). Twist it clockwise (CW) or counterclockwise (CCW), and you directly manipulating the C disc. But, how do you move the other two discs?
Each disc has a raised plastic tab. When the discs are next to each other, a disc can move freely for about 350 degrees until its raised tab hits the tab on the next disc and begins moving it.
If you turn disc C a full turn, the tab hits the tab on disc B and begins to turn it. Similarly, disc B has a tab on the opposite side of the disc that will hit disc A’s tab. Turn the dial far enough, and C will pick up and start turning B, which will then pick up and start turning A.
Clear as mud? Check out Woodgears. They have a great breakdown of the pieces and a video showing how the discs are manipulated.
The Problem Domain
The dial on our SafeSentry safe is 100 digits. If there are three discs, our domain is 100 * 100 * 100 or 1 million possible combinations. Testing on a safe at the store, we found it took about ten seconds on average to reset the dial then dial in the three solution numbers. So, worst case, it will take 115.74 days to try every combination. And 10 seconds is pretty fast; humans get tired and less precise over time. Luckily, there are some tricks we can do.
On some high-end, secure safes, if you turn the dial to 81.5 and the combination is 81, it won’t open. With these lower cost home-brand safes the manufacturing tolerances are much larger. On the safe we tried at the store if one of the numbers in the combination is 53 then 52 and 54 will also work.
The first part of this video will show you the tolerances on the combination dial are +/-1 digit.
This quickly reduces the domain to 33 * 33 * 33 = 35,937 combinations. That’s still over 4 days of trying.
One of the ways to pick a safe is by feel. Manufacturers know this, so, to prevent it, the last disc (we’ll call it disc C) has a series of indents. If you press down on the handle and spin the dial, the thing trying to push down into the notches on the dials, called the fence, will fall into these false indents and lock up the dials. Bummer. But, you quickly figure out that there are 12 indents. And, one of these ‘indents’ must be the correct slot when you dial in the combination.
The problem domain is now 33 * 33 * 12 = 13,068 combinations or 1.51 days. About the speed of paint drying.
The locations of these indents are found easily by hand. 100 / 24 (12 indents, 12 raised bits) = 4.17 dial positions per indent. It’s not super clean, but, if an indent ranges 21 to 25.2, then it’s safe to go to 24 to ‘test’ that indent to see if it’s actually a solution slot.
On our safe we located the indents as follows:
case 0: return (99); //98 to 1 on the wheel case 1: return (8); //6-9 case 2: return (16); //14-17 case 3: return (24); //23-26 case 4: return (33); //31-34 case 5: return (41); //39-42 case 6: return (50); //48-51 case 7: return (58); //56-59 case 8: return (66); //64-67 case 9: return (74); //73-76 case 10: return (83); //81-84 case 11: return (91); //90-93
Here's what disc C looks like:
Disc C has the following dimensions:
- Outer diameter: 2.815” (55.5mm)
- Width of solution slot: 0.239”
- Width of 11 indents: 0.249” +/- 0.002”
C = 2πr, so our circumference is 17.69”. Our motor has an 8400 tick encoder. Each encoder tick is therefore approximately 0.0021”. So, we’re looking for a difference of about 5 ticks. Eeek! That's not many.
If we can externally measure the widths of the various slots, we may be able to discern which slot is the skinniest and therefor the solution slot. This would reduce our combination domain to 33 * 33 * 1 = 1,089 and a crack time of 3 hours, worst case.
The function
measureDiscC() is designed to take a series of readings and add them together. The motor is a gear head motor and has a tremendous amount of torque, so, if there is any flexing or give in your apparatus, this will show up in the readings as noise. However, if we take many simultaneous readings, any flexion should be replicated to all indent measurements allowing the skinny slot to bubble to the top.
Set screws will not work. A hub that uses a set screw to connect to the D-shaft on a motor will not survive the constant torture of indent measuring. Once we switched to a 6mm clamping hub we had much less noisy readings.
Here’s the output from five
measureDiscC() tests on our Craigslist safe with no combination:
Measuring complete Smallest to largest width [Width]/[Depth] Indent 8: [1911] / [1130] Indent 1: [1925] / [1122] Indent 3: [1953] / [1091] Indent 0: [1955] / [1099] Indent 11: [1966] / [1105] Indent 2: [1992] / [1100] Indent 9: [1994] / [1126] Indent 7: [2011] / [1098] Indent 10: [2036] / [1096] Indent 4: [2077] / [1109] Indent 5: [2083] / [1100] Indent 6: [2114] / [1096]
Indent 8 bubbles to the top on almost all the tests we have run on our safe. We also output the depth measurements (how far does the handle go down), but I am much more suspicious of these readings.
We can’t be sure the smallest indent is the solution ident, or if we’ve even measured the indents correctly so the Safe Cracker firmware allows the user to control which indents are to be tested. Turn them all on, turn on 5, or turn on only one, it’s up to you. We recommend trying to crack your safe with the smallest four indents. If you fail to open the safe then turn these 4 off, turn the other 8 indents to true, and run again.
We are down to 33 * 33 * 4 = 4,356 or a little over 12 hours. Still not great. What other tricks can we do?
Quick Note: When we live streamed the safe cracking, we were conservative and selected four indents to try. The winning indent was indent 8, the skinniest indent. So with two data points, I’d say this vulnerability has potential. You can re-watch the stream if you'd like. The magic moment occurs at 45:20, but start around 44:30 to get the full scope.
Set Testing
If each three combination attempt takes 10 seconds, what can we reduce the time per attempt? We can dial faster of course. But, we can also get sneaky with how we adjust the dials. It takes me 10 seconds because I can’t back up a digit without fouling where the discs are sitting. The robot can be much more precise.
To crack our safe, we set discs A and B, test the indents on disc C, move backwards to adjust disc B, then test the indents again. We call this set testing as opposed to reset testing (where a full reset is done between tests).
The robot attempts combinations this way:
- Reset dials by spinning CCW, past zero, continue until we arrive at zero.
- Continue CCW to 3. This sets disc A to 3.
- Rotate CW to 3. Continue CW to 0. Disc B is now set to 0.
- Rotate CCW to the first allowed indent; ours is 8. Disc C is now set to 8.
- Try the handle. Failed? Continue…
- Rotate CCW to next allowed indent; ours is 24.
- Try the handle. Failed? Continue…
- Rotate CCW to next allowed indent; ours is 66.
- Try the handle. Failed? Continue…
- Rotate CCW to next allowed indent; ours is 74.
- Try the handle. Failed? Continue…
- Rotate CW to 6. Disc B is now set to 6.
- Loop to step 4.
- Rotate CW to 9. Disc B is now set to 9.
- etc...
Here’s a video of set testing, done by hand, to demonstrate what we’re talking about. Jump to 0:41 to see Set Testing in action.
Using this method we can test the AA/BB/xx combinations (set Disc B to 8 then test four indents) in approximately 8 seconds vs. 40 seconds (4 test @ 10s per test). Much faster!
Originally: 33 * 33 * 40s = 12.1 hours
Using Set Testing: 33 * 33 * 8.3s = 2.5 hours worst case!
And, if we’re confident in our single indent the test time comes down to approximately 4 seconds per test (it’s not linear because of the time to move disc B).
Set Testing with one indent: 33 * 33 * 4s = 1.2 hours.
Additional Resources
We hope you enjoyed reading about our safe cracking robot. If you have any questions or discover any other tricks, please let us know!
There are some great videos on how to crack safes, just have a poke around. Eric Schmiedl's talk Safecracking Without a Trace at DEFCON 14 was especially good. | https://learn.sparkfun.com/tutorials/building-a-safe-cracking-robot | CC-MAIN-2020-16 | refinedweb | 3,113 | 71.95 |
Friendly reminder we have
otel spec issue scrub 🧽 mtg tomorrow, Friday morning 8:30a PST.
Not many spec issues to triage, so if we have quorum with collector maintainers, we’ll also continue triaging collector and collector-contrib issues
Currently, our 3 outstanding P1
trace issues:
After a Span is ended, it usually becomes non-recording and thus IsRecording SHOULD consequently return false for ended Spans. Note: Streaming implementations, where it is not known if a span is ended, are one expected case where IsRecording cannot change after ending a Span.
When implementing this and writing the End method to set the recording state, how do I tell if the span is in a streaming implementation or not?
Don't set the span status description if the reason can be inferred from http.status_code.
Following on from our collector SIG issue scrub meetings from last week, we’ve completed:
Thanks to those who attended (see sig mtg doc).
Keeping the momentum, I propose 2 more sessions this week:
Which I’ll add to the otel calendar tomorrow with same people as invitees unless there is a more suitable time slot I should schedule.
@jsuereth here is where the spec says metric labels and span attributes must have identical meanings:
Semantic conventions exist for four areas: for Resource, Span and Log attribute names as well as Metric label keys. In addition, for spans we have two more areas: Event and Link attribute names. Identical namespaces or names in all these areas MUST have identical meanings. For example the http.method span attribute name denotes exactly the same concept as the http.method metric label, has the same data type and the same set of possible values (in both cases it records the value of the HTTP protocol's request method as a string).
Dears,
Appreciate your support for the below issue,
I built my open telemetry demo as the below steps,
Thanks for your time and consideration.
otel spec issue scrub 🧽at 8:30a PST, so we could use the remaining time to go over the metrics issues. i’ve added to the agenda cc @jmacd | https://gitter.im/open-telemetry/opentelemetry-specification?at=5fad55cf7cac87158fa13293 | CC-MAIN-2022-40 | refinedweb | 355 | 58.21 |
.
And this is relevant to which side of hate? How long was he on the waiting list? How does his wife feel about it? How would his children feel when he dies? Does he experience regret? Do you know his heart? (no pun intended). Until you walk in his shoes, don't judge. Forgiveness is always better and when your time comes, you may receive the same.
You know, Paul, there is a difference between seeking healthcare reform and turning our medical industry into a government entity. Maybe Cheney recognized what you want to ignore as you seek to make the government central to everything in our lives. Just maybe Dick Cheney believed that the government had no place in medicine or in interjecting itself into every aspect of individual life. If you truly want healthcare reform, do something to get the lawyers and their frivilous lawsuits out of the courtroom...you just might lower the costs of medicine at the individual level. You might note that all the lawyers in Washington who shoved ObamaCare down our throat ignored that need in creating this sham of healthcare reform. Maybe you'll feel the same way when Barney Frank needs a heart or liver or possibly Harry Reid is in dire need to stave off the end of his evil life. I fnd it rather disgusting that you would allow politics to be the determining factor in whether or not an individual with a bad heart deserves a transplant. Maybe this is the leading edge of the atttitude which has been associated with ObamaCare from the start. WB
I, along with 80% of the US population simply don't like the guy. Actually government ran healthcare is much more efficient than the private sector. In England, their healthcare system spends about $2300 per year, per patient where our US insurance companies spend well over $8000. This is simply because government ran services do not have to advertise or make a profit. We're paying a boatload of dollars for healthcare and recieving very little in return.
I can absolutely agree with you on the outrageous and often unnecessary costs of medical care in the U.S. I wonder if part of the low cost in England is because most of them are still on line waiting to get taken care of LOL. But seriously, we need to pay attention to taking care of ourselves instead of trying to fix our bodies after the fact, IMO.
The biggest complaint in England is a waiting list for non emergancy care. They recently brought it down from a year to 18 weeks. But the World Healthcare Ranking lists France #1, Italy #2, United Kingdom #18 and the US at #37 (between Slovenia and Costa Rica). Whoo hooo!
Well, I do agree with most of the comments that politics/whether we like someon shouldn't come into play when deciding whether or not to save someone's life.... On the other hand, Dick Cheney had a HEART???
Sticking that "Big" in there cracked me up. My apologies in advance to any pro Cheney folks.
HAHAHAHA!!!!!!
No doubt Big Dick was on the top of the list!
Plebians such as ourselves must wait-'tis the way of his world, eh??
Yes, peeps like Cheney are always first in line for transplants and life extension technology.
"Big Dick" as you people have chosen to refer to him as, was reported to be on the list for 20 months, almost two years. I hardly think that qualifies as being on the top of the list.
Now if it was his head that needed replacing it might inspire an even more apporopriate line !
If I die, I'll give my heart to Dick or Bush to balance out their missile sizes penis heads
I't's 3 sizes too small, he is a mean one.
In spike of his beliefs, nobody deserve to die, maybe he will have a change of heart himself
Apparently, it's heavy and is made of stone.
I consider myself an extremely far-left individual, Socialist, perhaps, but if Cheney needed that heart, he must have needed it desperately. I am glad he got it, if only for humanitarian purposes.
As for the man's politics, well, you must know what I think!!!
I agree that if he needed a new heart he should have one, providing there was no unfair queue jumping. And anyway, the possibilities are endless. Perhaps a new heart will infuse some compassion into the man.
Maybe having a new heart will change his perspective on what is important.
After all, regardless of one's beliefs, we are all human.
I'm a bit disappointed by people's comments- He's a human being and regardless of his policies that you dislike, have some compassion. He waited for 20 months for a heart just like anyone else.
If he were your father- even if you disagreed with him- would you want him to die? I dislike Joe Biden, but if he needed an organ transplant, I would wish him well and hope he gets one safely.
I actually agree. I am not a Cheney fan but I don't believe in others deciding who deserves a transplant or not.
That being said, he recently turned down a speaking engagement in Canada because he said he was worried about security. Obviously it was because he was on a waiting list for a heart.
I have no sympathy for this cretin! When Cheney asked Richard Clark--longtime security adviser for many presidents--about the possibility of Iraq being responsible for 911 Clark replied "Iraq? They had nothing to do wit the attack!"
Cheyney replied, "Yes, but they have better targets"! How many hearts were destroyed in that little Cheney fiasco?
He may have been given a new organ, but it doesn't come with compassion, empathy or any of those traits that makes one a leader or a statesmen.
He's the one reason I hope there's a God who'll settle the score with arrogant men of power for all of the sacrificed innocents on this planet. It's been estimated that the 20th Century had over a billion deaths resulting from war. What kind of egotistical insanity caused it?—Cheney is a perfect example of it!
What a loss! I can find a better use for his new heart! As a warmonger, he doesn't deserve a sweet death after all the crimes he committed!
What the man deserves is what he has dished out to countless people and families around the world for his own personal gain. Arraignment as the war criminal that he is would be more suitable than prolonging the life of this evil man.
In all fairness, Cheney is no more or less entitled to a transplant than anyone else, case in point Steve Jobs had to wait months for his new liver.
In fact if the organ matches then it is likely to be used on the nearest patient rather than the patient in most need, due to the time window issue.
Hearts have a "half life" measured in hours, because of the ischaemic damage that results from prolonged stoppage.
This is one of the big problems with organ donation, many perfectly good organs get wasted every day because hospitals aren't equipped for matching and/or harvesting.
#include "$0.02.h"
Liberals once again showing the tolerance and love for mankind that they profess to have.
You might note that some liberals on this thread were not against his having a transplant.
Then they were not included, but in the next post you just couldn't help yourself. But its ok.
That is not criticizing him for getting a heart transplant.
No it isn't, its just another example of liberal tolerance and compassion.
So, people who you perceive as liberals love everyone and put up with everyone and never criticize at all? You are sadly mistaken...you are thinking of dogs...
As opposed to Cheney who is a prince among men?
Cheney should be in jail for war crimes.
What are you worried about Dick Cheney for . . . you wanna-be Gomez? Get off of your dead ass and get involved in some positive change in your own community. Otherwise, just sit in the corner and play with yourself. You'll accomplish as much, and it will feel better.
The same could be said of some of those who seem to live in the political forums attacking everything liberal...
It's hard to ignore Cheney when he won't go away.
You have no idea what people are doing in their real lives... mike king 8 years ago
Dick Cheney blasting Bush. where is the loyalty? Jack Lee 11 dissenting GOP Senators on the Obamacare Repeal Reconciliation Act (ORRA) Wednesday.... Ralph Deeds | https://hubpages.com/politics/forum/95212/the-big-dick-cheney-gets-a-new-heart | CC-MAIN-2018-30 | refinedweb | 1,479 | 73.47 |
i completed all the beginner problems posted...after these what i need to do next?
i completed all the beginner problems posted...after these what i need to do next?
this will be really useful!!..thank you!!
i am stuck in this problem...not getting any idea...especially when numbers repeat..how to store them in array
i am stuck in this problem...the site is not accepting my code..the reason its giving is "no output file"
#include <iostream>#include <fstream>using namespace std;int main(){ifstream f("dishin.txt");ofstream g("dishout.txt");int n;f>>n;int *pt=new int[n];for(int j=0;j<n;j++){f>>pt[j];}int ma_x,mi_n,avg;int sum=0;ma_x=-99999;mi_n=99999;for(int i=0;i<n;i++) | https://www.commonlounge.com/profile/fbea0f08a29342b081bc5a3b3e0a5200 | CC-MAIN-2021-17 | refinedweb | 132 | 64.27 |
Hi, Am Mittwoch, den 25.02.2009, 20:42 +0000 schrieb erik: > klaas de waal <klaas.de.waal <at> gmail.com> writes: > > > > On Fri, Oct 10, 2008 at 2:36 AM, hermann pitton <hermann-pitton <at> arcor.de> > wrote: > > Hi, > > Am Donnerstag, den 09.10.2008, 22:15 +0200 schrieb klaas de waal: > >}, > > > #else > > > { .lomax = 395000000, .svco = 2, .spd = 1, .scr = 0, .sbs = > > > 3, .gc3 = 1}, > > > #endif > > > { .lomax = 455000000, .svco = 3, .spd = 1, .scr = 0, .sbs = > > > 3, .gc3 = 1}, > > > etc etc > > > > > Hi Klaas/Hermann > > Your fix works perfectly for me as well. Prior I could not get the channels in > the 386750000 freq. With Fix appied my Ziggo locking issues disappeared. > > Is there any chance to get it into the official version? > > Erik > | https://www.linuxtv.org/pipermail/linux-dvb/2009-February/031915.html | CC-MAIN-2016-30 | refinedweb | 123 | 86.71 |
Web.
The s:resource tag uses Seam’s DocumentStore to serve (or push) documents. You'll need to configure this servlet in to your web.xml:
web.xml
<servlet> <servlet-name>Document Store Servlet</servlet-name> <servlet-class>org.jboss.seam.document.DocumentStoreServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Document Store Servlet</servlet-name> <url-pattern>/seam/docstore/*</url-pattern> </servlet-mapping>
Alone in a page, s:resource will act as the file download provider by defining where to get the file data and meta-data. You use it in place of HTML (not inside of HTML) since the intent is to serve the document and not a web page. Thus, the page template should look something like this.
resources.xhtml
<s:resource
- data is the actual file data. It may be a java.util.File, an InputStream or a byte[].
- contentType (e.g.,
image/jpeg)
- filename (e.g., someFile.jpg) which will likely be displayed in the user's file download prompt
Other attributes are described in the Seam reference documentation.
If we want resources.xml to serve all of our documents (or at least those handled by the fileResourceProvider component), we need to pass one (or many) parameters to it such that it can load the document information and data for a given request. We do that by using request parameters (e.g.,). There are at least two ways of getting the parameter holding the file id into the fileResourceProvider component. You could use the @RequestParameter annotation;
@RequestParameter private Long fileId;
or inject it via pages.xml:
<page view-id=”/resources.xhtml”> <param name="fileId" value="#{fileResourceProvider.fileId}"/> </page>
Taking the first approach, the FileResourceProvider.java would then be defined as follows:
@Name("fileResourceProvider") @Scope(ScopeType.EVENT) public class FileResourceProvider { @RequestParameter private Long fileId; private String fileName; private String contentType; private byte[] data; @Create public void create() { FileItem item = em.find(FileItem.class, fileId); // Get document representation this.fileName = item.getFileName(); this.data = item.getData(); this.contentType = item.getContentType(); } //.. getters setters }
That's all that is needed to serve documents in a RESTful way. To make the creation of the download link even easier, you can use the s:download tag. Here's how it works:
<s:download src=”/resources.xhtml”> <f:param name=”fileId” value=”#{someBean.downloadableFileId}”/> </s:download>
The s:download tag is a variation on the Seam s:link tag. It will generate a bookmarkable link looking something like. You can then use Seam URL rewriting to translate the link into. See examples in the examples/ui in the Seam distribution for further guidance! | http://in.relation.to/daniel-roth/ | CC-MAIN-2016-36 | refinedweb | 430 | 51.04 |
I am primarily a Java Developer and have used IntelliJ for years. So I set up my project and moved all my php files under ./src and create a PHPUnit test under ./test. I used the IDE "Mark Directory As" feature to mark the sources and test sources. I am using composer to pull in PHPUnit. I created a phpunit.xml file in the root of my project and configured PHPUnit to use it.
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true">
<testsuites>
<testsuite name="Application Test Suite">
<directory>./test/</directory>
</testsuite>
</testsuites>
</phpunit>
When I run my test, it cannot find the source PHP class it is testing. I get an error:
PHP Fatal error: Class 'com\acme\RFPHelper' not found in C:\Users\frederickb\Documents\Projects\ProjectService\Configurator\test\RFPHelperTest.php on line 17
PHP Stack trace:
PHP 1. {main}() C:\Users\frederickb\AppData\Local\Temp\ide-phpunit.php:0
The test class and the class being tested have the same namespace "com\acme". I also have a test data file that is failing to be loaded using file_get_contents(). It would be nice if there were a "test resources" directory that could be marked. It isn't clear what the "current directory" is when tests are being run. I apologize that I am not more conversant with the PHP ecosystem, but the "Mark Directory As" feature implies that the unit test framework would be able to load php files from both the marked "src" directory and the "test" directory. What am I misunderstanding? Thank you.
Fred
Hi there,
With PHPUnit you are responsible for making sure that PHP is able to find your (source) classes.
Since you are using Composer already, you can configure it (via composer.json) to do that for you. For example (quick edit):
Or, if you have your own autoloader -- use it in your bootstrap.php which will be used by PHPUnit to load your dependencies/do global initialisation etc (if you tell PHPUnit to use it, of course; be it via phpunit.xml or as part of IDE integration).
Hi Andriy,
I tried the composer.json autoload. I even added an autoload-dev to the tests/ directory, but same error. I tried removing the use of the phpunit.xml file from the test's Run/Debug configuration. I switch from Test scope "Directory" to method. Same error. Then removed the check from TestRunner Default configuration file. No change. The PHPUnit library is "Load from include path". What other configuration might I be missing? Thank you for the help.
Fred
Hi Andriy,
I followed your link and made one more change, which I had missed, that of "Use custom loader" and specifying the autoload.php in vendor for the "Path to script". Same error. Thank you.
Fred
If you are using this then most likely composer's autoloading functionality is not used. In this case you most likely need to require composer's "path/to/your/vendor/autoload.php" in your bootstrap.php file manually.
If you would use "Custom loader" option (which makes much more sense, since you are using Composer to get your PHPUnit) then it should use autoloader automatically.
----
I personally prefer and use PHAR version of PHPUnit (a bit less space/faster sync; does not contain tests and other not needed to run files that would usually come if installed via Composer).
This is very simplified project structure of what I use in couple of projects.
In bootstrap.php I have (the important part)
In composer.json (important part)
If composer's autoloading does not work for some reason (e.g. you have dumped autoloading info into an array so it only takes info from there and does not do "dynamic" loading (searching actual file system for files each time)) .. you can always write and register your own autoloader (few lines of code).
My suggestion here: try going via bootstrap file and require_once autoload.php file there -- that's if autoloader as it is now does not work.
Unfortunately I cannot tell why it still does not work for you -- you may want to debug execution (set breakpoints in composer's autoloader) and see where it looks for files/classes when PHP is asking where to find you classes.
Your links led me to solve the problem. I did not end up using psr-4, although I am going to read more about it. I ended up trying classmap based on a Net Tuts video.
"autoload":{
"classmap":[
"src","src/com/acme"
]
},
"autoload-dev":{
"classmap":[
"tests/com/acme"
]
},
I was also missing the bootstrap="vendor/autoload.php" attribute in the phpunit XML element. Andriy, thank you very much!
Fred | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206318559-PHPUnit-and-Mark-Directory-As-?page=1#community_comment_206824495 | CC-MAIN-2021-49 | refinedweb | 780 | 66.54 |
-- ALT constructs. An ALT (a term inherited from -- occam) is a choice between several alternate events. In CHP, we say that an event -- must support alting to be a valid choice. Events that /do/ support alting are: -- -- * 'Control.Concurrent.CHP.Monad.skip' -- -- * 'Control.Concurrent.CHP.Monad.stop' -- -- * 'Control.Concurrent.CHP.Monad.waitFor' -- -- * Reading from a channel (including extended reads): that is, calls to 'Control.Concurrent.CHP.Channels.readChannel' -- and 'Control.Concurrent.CHP.Channels.extReadChannel' -- -- * Writing to a channel (including extended writes): that is, calls to 'Control.Concurrent.CHP.Channels.writeChannel' --). module Control.Concurrent.CHP.Alt (alt, (<->), priAlt, (</>), every, every_, (<&>)) where import Control.Applicative import Control.Arrow import Control.Concurrent import Control.Concurrent.STM import Control.Monad.Reader import Data.List import qualified Data.Map as Map import Data.Maybe import Data.Monoid import qualified Data.Set as Set import Data.Unique import System.IO import Control.Concurrent.CHP.Base import Control.Concurrent.CHP.Event import Control.Concurrent.CHP.Guard import Control.Concurrent.CHP.Monad import Control.Concurrent.CHP.Parallel import Control.Concurrent.CHP.Poison import Control.Concurrent.CHP.Traces.Base -- | An alt between several actions, with arbitrary priority. The first -- available action is chosen (with an arbitrary choice if many actions are -- available at the same time), its body run, and its value returned. alt :: [CHP a] -> CHP a alt = priAlt -- |' and 'Control.Concurrent.CHP.Monad.stop') -- -- There exists priority when comparing dummy guards to anything else. So for -- example, -- -- > priAlt [ skip, x ] -- -- Will always select the first). priAlt :: [CHP a] -> CHP a priAlt = unwrapPoison . priAlt' . map wrapPoison -- | A useful operator to perform an 'alt'. This operator is associative, -- and has arbitrary priority. When you have lots of guards, it is probably easier -- to use the 'alt' function. 'alt' /may/ be more efficent than -- foldl1 (\<-\>) (<->) :: CHP a -> CHP a -> CHP a (<->) a b = alt [a,b] -- | A useful operator to perform a 'priAlt'. This operator is -- associative, and has descending priority (that is, it is -- left-biased). When you have lots of actions, it is probably easier -- to use the 'priAlt' function. 'priAlt' /may/ be more efficent than -- foldl1 (\<\/\>) (</>) :: CHP a -> CHP a -> CHP a (</>) a b = priAlt [a,b] infixl </> infixl <-> infixl <&> -- |'). -- -- * 'Control.Concurrent.CHP.Monad.skip', the always-ready guard. -- -- * 'Control.Concurrent.CHP.Monad.stop', the never-ready guard (will cause the whole 'every' to never be ready, -- since 'every' has to wait for all guards). -- -- * A call to 'Control.Concurrent.CHP.Monad.syncBarrier'. -- -- * A sequential composition where the first item is one of the things in this -- list. -- -- * A call to 'every' (you can nest 'every' blocks inside each other). -- -- Timeouts (e.g. 'Control.Concurrent.CHP.Mon every :: forall a. [CHP a] -> CHP [a] every [] = skip >> return [] every xs = liftPoison (AltableT (liftM ((:[]) . flip (,) (return True)) $ gs >>= foldM1 merge) (return False)) >>= \b -> if b then runParallel (map (unwrapPoison . liftTrace) bodies) else alt [every xs] where both :: Either String [(Guard, TraceT IO (WithPoison a))] both = mapM (checkSingle . pullOutAltable . wrapPoison) xs gs :: Either String [Guard] gs = liftM (map fst) both bodies = map snd $ fromRight both fromRight (Right x) = x fromRight _ = error "Reached unreachable code in every; bodies executed after bad guard" checkSingle (Left err) = Left err checkSingle (Right []) = Left "Bad guard in every" checkSingle (Right [x]) = Right x checkSingle (Right _) = Left "Alt inside every" merge :: Guard -> Guard -> Either String Guard merge SkipGuard g = return g merge g SkipGuard = return g merge StopGuard _ = return StopGuard merge _ StopGuard = return StopGuard merge (EventGuard recx actx esx) (EventGuard recy acty esy) = return $ EventGuard (\n -> recx n ++ recy n) (actx `mappend` acty) (esx ++ esy) merge _ _ = badGuard "merging unsupported guards" foldM1 :: Monad m => (b -> b -> m b) -> [b] -> m b foldM1 f (y:ys) = foldM f y ys foldM1 _ _ = error "Reached unreachable code in every; guards empty in non-empty case" -- | Like 'every' but discards the results. -- -- Added in version 1.8.0. every_ :: [CHP a] -> CHP () every_ ps = every ps >> return () -- | A useful operator that acts like 'every'. The operator is associative and -- commutative (see 'every' for notes on idempotence). When you have lots of things -- to join with this operator, it's probably easier to use the 'every' function. -- -- Added in version 1.1.0 (<&>) :: forall a b. CHP a -> CHP b -> CHP (a, b) (<&>) a b = merge <$> every [Left <$> a, Right <$> b] where merge :: [Either a b] -> (a, b) merge [Left x, Right y] = (x, y) merge [Right y, Left x] = (x, y) merge _ = error "Invalid merge possibility in <&>" -- ALTing is implemented as follows in CHP. The CHP monad has [Int] in its -- state. When you choose between N events, you form one body, that pulls -- the next number from the head of the state and executes the body for the -- event corresponding to that index. Nested ALTs prepend to the list. -- So for example, if you choose between: -- -- > (a <-> b) <-> c -- -- The overall number corresponding to a is [0,0], b is [0,1], c is [1]. The -- outer choice peels off the head of the list. On 1 it executes c; on 0 it -- descends to the nested choice, which takes the next number in the list and -- executes a or b given 0 or 1 respectively. -- -- If an event is poisoned, an integer (of arbitrary value) is /appended/ to -- the list. Thus when an event-based guard is executed, if the list in the -- state is non-empty, it knows it has been poisoned. -- -- I did try implementing this in a more functional manner, making each event -- in the monad take [Int] and return the body, rather than using state. However, -- I had some memory efficiency problems so I went with the state-monad-based -- approach instead. priAlt' :: forall a. [CHP' (WithPoison a)] -> CHP' (WithPoison a) priAlt' items -- Our guard is a nested guard of all our sub-guards. -- Our action-if-not-guard is to do the selection ourselves. = AltableT flattenedGuards (selectFromGuards flattenedGuards) where -- The list of guards without any NestedGuards or StopGuards: flattenedGuards :: Either String [(Guard, TraceT IO (WithPoison a))] flattenedGuards = liftM (filter (not . isStopGuard . fst)) altStuff where altStuff :: Either String [(Guard, TraceT IO (WithPoison a))] altStuff = liftM concat $ mapM pullOutAltable items -- Performs the select operation on all the guards, and then executes the body selectFromGuards :: forall a. (Either String [(Guard, TraceT IO (WithPoison a))]) -> TraceT IO (WithPoison a) selectFromGuards (Left str) = let err = "ALTing not supported on given guard: " ++ str in liftIO $ do hPutStrLn stderr err ioError $ userError err selectFromGuards (Right both) | null (eventGuards $ map fst both) = join $ liftM snd $ liftIO $ waitNormalGuards both Nothing | otherwise = do let (guards, _bodies) = unzip both earliestReady = findIndex isSkipGuard guards recordAndRun :: WithPoison ([RecordedIndivEvent Unique], TraceT IO (WithPoison a)) -> TraceT IO (WithPoison a) recordAndRun PoisonItem = return PoisonItem recordAndRun (NoPoison (r, m)) = recordEvent r >> m guardsAndRec :: [(Guard, WithPoison ([RecordedIndivEvent Unique], TraceT IO (WithPoison a)))] guardsAndRec = map (second (NoPoison . (,) [])) both getRec :: (SignalValue, Map.Map Unique (Integer, RecordedEventType)) -> WithPoison ([RecordedIndivEvent Unique], TraceT IO (WithPoison a)) getRec (Signal PoisonItem, _) = PoisonItem getRec (Signal (NoPoison n), m) = case both !! n of (EventGuard recF _ _, body) -> NoPoison (recF (makeLookup m), body) (_, body) -> NoPoison ([], body) tv <- liftIO $ newTVarIO Nothing pid <- getProcessId tr <- ask tid <- liftIO myThreadId mn <- liftIO . atomically $ do ret <- enableEvents tv (tid, pid) (maybe id take earliestReady $ eventGuards guards) (isNothing earliestReady) either (const $ return ()) (\((sigVal,_),es) -> do recordEventLast (nub es) tr case sigVal of Signal PoisonItem -> return () Signal (NoPoison n) -> let EventGuard _ act _ = guards !! n in actWhenLast act (Map.fromList $ map (snd *** Set.size) es) ) $ liftIO $ waitNormalGuards both Nothing -- No events ready, no other guards ready either -- Events will have been enabled; wait for everything: (Left disable, Nothing) -> do (wasAltingBarrier, pr) <- lift' <- liftIO . atomically $ disable case mn' of -- An event overrides our non-event choice: Just pr' -> recordAndRun $ getRec pr' -- Go with the original option, no events -- became ready: Nothing -> recordAndRun pr | http://hackage.haskell.org/package/chp-2.1.0.1/docs/src/Control-Concurrent-CHP-Alt.html | CC-MAIN-2015-40 | refinedweb | 1,298 | 56.25 |
"Is NOT Raise User" Preconditionttippett Mar 21, 2017 11:53 AM
Hi all,
I'm looking to add a precondition to an action instance on my process. The objective is to prevent the Raise User from using this action, but allowing analysts to use it. I cannot solve this via taking away raise user privileges for that action, as the raise user will need to use the action at a later stage in the process.
Is it possible to create this precondition via a "Standard" condition type? Or will I have to utilize a calculation? If a calculation is needed, what is the simplest way of writing it?
I am on version 2016.3.
Thanks,
Tyler
1. Re: "Is NOT Raise User" PreconditionJulian Wigman Mar 21, 2017 12:46 PM (in response to ttippett)
1 of 1 people found this helpful
2. Re: "Is NOT Raise User" PreconditionJulian Wigman Mar 21, 2017 12:57 PM (in response to Julian Wigman)1 of 1 people found this helpful
..but.
If the action you are proposing IS available to end users as well then you'll need to switch to a calculated condition as you'll need to check on the state of two variables.
That calculation IMHO will look something like this (I've created as Request Condition but similar if another Business Object) with the comparison being equal to true.
import System
static def GetAttributeValue(Request):
// Get Current User and their Type
CurrentUser = Request.GetCurrentUserName()
UserName = Request.GetObjectByAttribute("System.User","Name",CurrentUser)
// If they are an Analyst that is OK
if UserName.UserType.Name == 'Analyst':
return true
// Or test if the Raise User IS NOT the Current User
elif Request.RaiseUser != null and Request.RaiseUser != CurrentUser:
return true
// Else they are not an Analyst and are the Raise User!
return false
3. Re: "Is NOT Raise User" Preconditionttippett Mar 21, 2017 1:55 PM (in response to Julian Wigman)
Thank you! I tested both methods and both worked. I think I will end up going with the calculation that ensures the current user is an analyst. For anyone else reading this, my final calculation came out to be:
import System
static def GetAttributeValue(Request):
Value = 'false'
CurrentUser = Request.GetCurrentUserName()
UserName = Request.GetObjectByAttribute("System.User","Name",CurrentUser)
if UserName.UserType.Name == 'Analyst':
return true
return Value
...with
Condition: Equals
Value Type: Specific Value
Value: True
Thanks again! | https://community.ivanti.com/thread/35237 | CC-MAIN-2017-51 | refinedweb | 396 | 57.67 |
You have now become a member of a domain that corresponds to the production environment. You have completed your work and now you want to leave the production domain.
To complete this recipe, you will need to have rhc installed on your machine. Please refer to the Installing the OpenShift rhc command-line client recipe in Chapter 1, Getting Started with OpenShift, for instructions.
To leave a domain, you should run the following command. All the users are allowed to leave the domain they are a member of:
$ rhc leave-domain --namespace prodosbook -l openshift.cookbook.test@gmail.com
The
rhc leave-domain command requires only one mandatory argument, which is
--namespace, the namespace ...
No credit card required | https://www.oreilly.com/library/view/openshift-cookbook/9781783981205/ch02s11.html | CC-MAIN-2019-26 | refinedweb | 118 | 57.37 |
How to pass value of business object attribut in the body of REST API
Hello,
I am a beginner on Bonitasoft and I am looking to do a fairly simple exercise: make a POST call to a REST API by passing in the body of values that I can retrieve from my business object (item) outstanding
So I use a REST connector and I would like to put a body like:
{
"id": "item.getId ()",
"actionCode": "item.getActionCode ()}",
"status": "item.getStatus ()"
}
How to do ?
Thank you
No answers yet.
For information, i am using communauty version
Hello,
I think i found how to do.
I used a script to fullfill the body with this code and I think i works
import groovy.json.JsonOutput
Map json = new HashMap();
json.put("id", orderItemPassed.getId());
json.put("actionCode", orderItemPassed.getActionCode());
json.put("status", orderItemPassed.getStatus());
return JsonOutput.toJson(json)
Regards | https://community.bonitasoft.com/questions-and-answers/how-pass-value-business-object-attribut-body-rest-api | CC-MAIN-2020-10 | refinedweb | 147 | 56.66 |
Part 1: Building a Kentico CMS Windows Gadget Thomas Robbins — Jun 17, 2010 cmskentico Windows Vista introduced a new UI feature called Windows Gadgets. Fundamentally, a Gadget is a small, lightweight application that runs in a special pane called the Sidebar or directly on a users desktop. In this series of blog posts we will build a widget that connects with Kentico data. In this part of the series we will introduce gadget development and build a very simple gadget. Well start by creating a barebones gadget that we can use as a template for other gadgets we will build over the series of articles. Windows ships with a variety of gadgets out of the box. They range from desktop and mail apps to stock ticker and weather apps. There is even a marketplace for gadgets. These kinds of apps have been around for awhile but the real power lies in the fact that you as a developer can create your own gadgets. The power of these is really only limited by your own imagination or that of your marketing department. In their most basic form gadgets are really nothing more than an HTML script file and an XML file stored in a known directory location. This assortment of files creates a mini-application that can access web services, RSS feeds, images, the file system and respond to user input through mouse clicks or keyboard input. As we get more familiar with gadgets we can start to add in more complex things like custom DLLs to handle complex scripts. Building a Gadget The default installation directory for gadgets is - C:\Users\<your name>\AppData\Local\Microsoft\Windows Sidebar\Gadgets When you view this directory you will see the installed gadgets as shown below If we take a look at the Battery Check gadget we can see the files that are included Whats nice about this structure is that you can see all the files and even look at the source. Lets go ahead and build our sample gadget using the following steps. 1. Create a new folder in C:\Users\<your name>\AppData\Local\Microsoft\Windows Sidebar\Gadgets called simple.gadget as shown below. Note: The directory must contain the .gadget extension for the Gadgets dialogue to recognize it. All files will be saved into this directory 2. Create two more directories images and css your directory structure should look like the following Note: While these arent required directories we will want to include images and css files. 3. Create the XML manifest and save it as Gadget.xml <?xml version="1.0" encoding="utf-8" ?> <gadget> <name>Kentico Gadget</name> <namespace>Kentico.Simple</namespace> <version>1.0</version> <author name="Thom Robbins"> <logo src="images\logo.png" /> <info url="" /> </author> <copyright>2010</copyright> <description>Simple gadget</description> <icons> <icon width="60" height="80" src="images\kentico.ico" /> </icons> <hosts> <host name="sidebar"> <base type="HTML" apiVersion="1.0.0" src="Simple.html" /> <permissions>full</permissions> <platform minPlatformVersion="0.3" /> </host> </hosts> </gadget> Note: The XML file is always called gadget.xml 4. Create an HTML file with the following code and save it as simple.html <html xmlns=""> <head> <meta http- <meta http- <title>Kentico CMS Gadget</title> <link href="/css/kentico.css" rel="stylesheet" type="text/css"> </head> <body onload="loadMain();"> <a href="" title="Kentico CMS .NET" > <img border="0" src="kenticopower.png" alt="Kentico CMS for ASP.NET - Content Management System"/></a> <script language="javascript" type="text/javascript"> function loadMain() { } </script> </body> </html> Note: There is a CSS file and some images that I point to. These are included in the download available at the end Showing the gadget Thats the basics we need. I have included the images and CSS file as part of the download that is available at the end. Lets go ahead and load this into the sidebar using the following steps 1. On your desktop right click and select Gadgets as shown below 2. In the Gadgets window select the Kentico Gadget as shown below 3. Congratulations! You have the gadget available as shown below Keep an eye out as we start to build out this sample to connect into Kentico data. The sample project is available here for download. Share this article on Twitter Facebook LinkedIn Thomas RobbinsGoogle Plus I spend my time working with partners and customers extending their marketing and technology to the fullest. Comments | https://devnet.kentico.com/articles/part-1--building-a-kentico-cms-windows-gadget | CC-MAIN-2021-04 | refinedweb | 736 | 55.44 |
Type: Posts; User: laasunde
Thank you.
That looks very interesting.
Will study it in more detail the coming week.
Hello,
An external library has the following header file;
template <typename T>
class MyCollection
{
public:
MyCollection();
The following code writes to a file on either local disk to a remote disk (commented out code) on Windows 7 platform.
#include <iostream>
#include <fstream>
using namespace std;
int main...
The understand I have is a static library is a collection of compiled object files. Does not that mean that a static library could use a different CRT version than the exe?
How can I check that...
Say I have an executable and a library on the Windows XP platform.
Does building the executable and library as static (/MT) or dynamic (/MD) have any impact on which unit creates and deletes...
Thank you. Will take a look at what you mentioned.
The example enable a client to iterate the internal std::vector using being() and end().
class foo
{
public:
typedef std::vector<std::string>const_iterator iter;
iter begin () const;
...
Agree. Boost is library of choice.
Original post was poorly phrased on my part. What I meant was the controller should create all views (plural) and manage switching between views. Switching...
What is good practice for the relationship between view and controller in the MVC pattern?
It appears to me that this relationship can become quite strongly coupled and is this desirable?
To...
Hello,
Using multiple computers connected with ethernet and running WinXP SP3.
One of the computers is defined as the server, meaning it has created a file share that all the other computers...
The MessageManager class is a wrapper around a c library with all the fun that brings along. The class retrieves all Messages available in the system. Since the class loads a lot of resources it is...
Hello,
I have an issue with setting timezones and using the API GetTimeZoneInformation that I would appreciate some help understanding.
Setting the timezone to GMT+02:00 Jerusalem on computer1...
Thank you for the feedback.
We would like to have a tool that only checks a developers adherence to a set of rules and for instance blocks an attempt to check-in that file. The application you...
What tool would you recommend to verify C++ source code styling? By C++ source code styling I mean, usage of indentation, spacing and newlines, howto format commenting, where to place bracket ,...
#include <iostream>
#include <string>
using namespace std;
int main()
{
// rest of code...
}
The code you provided should not compile, the variable 'value' is not defined.
LDI::LDI(int valueTemp)
: Instructions()
{
value = valueTemp;
}
Please provide code example.
Also explain what happens and what you would like to happen.
Use code tags.
First of all, definiting a type called "new1" is just plain annoying.
In the below code 'sList' is a pointer but the method list_sort does not return a pointer.
new1 *sList;
new1...
In the below code the variable all_names is not defined and the function strcmp requires two parameters of type const char *.
int id;
result = strcmp (all_names[loop].id,id);
...
You already asked the question here
Stick to one thread. Please be a bit more specific in your problem description.
Some info
What specific part of the task are you having a problem with? Does the current code write any, some or all necessary infomation...
Please use code tags and indent your code.
You can use socket programming to communicate between to computers across a network.
Use two for loops.
for(int index1 = 0; index1 < STUDENT; index1++)
{
for(int index2 = 0; index2 < NUM_QUIZ; index2++)
{
// out data from array
} | http://forums.codeguru.com/search.php?s=e45851be5da95c8b68def690bbd54357&searchid=5798629 | CC-MAIN-2014-52 | refinedweb | 603 | 67.45 |
import "golang.org/x/exp/io/i2c"
Package i2c allows users to read from and write to a slave I2C device.
TenBit marks an I2C address as a 10-bit address.
Devfs is an I2C driver that works against the devfs. You need to load the "i2c-dev" kernel module to use this driver.
Device represents an I2C device. Devices must be closed once they are no longer in use.
Open opens a connection to an I2C device. All devices must be closed once they are no longer in use. For devices that use 10-bit I2C addresses, addr can be marked as a 10-bit address with TenBit.
Close closes the device and releases the underlying sources.
Read reads len(buf) bytes from the device.
ReadReg is similar to Read but it reads from a register.
Write writes the buffer to the device. If it is required to write to a specific register, the register should be passed as the first byte in the given buffer.
WriteReg is similar to Write but writes to a register.
Package i2c imports 5 packages (graph) and is imported by 21 packages. Updated 2017-09-30. Refresh now. Tools for package owners. | https://godoc.org/golang.org/x/exp/io/i2c | CC-MAIN-2017-43 | refinedweb | 199 | 77.23 |
LIBS Spectrometer - Build 3
I don't quite get the signal to noise ratio out of the existing build that I was hoping for. One possible reason is the synchronization between the firing of the laser and the acquisition in the spectrometer. Right now, a single button press starts both. I want to measure the delay between sending the firing signal and the firing of the laser. And I also want to have control over a delay between the firing and the acquisition signals.
To implement that, I am using a STM32F746G-DISCO discovery kit from ST:
It has a very fast STM32F746NGH6 microcontroller at 200+ Mhz. That is far more than we need here, but it also has a nice touch screen, which will help me adjust delays and display data. Finally, it has an Arduino compatible header, which makes it easy to add screw terminals etc. with off the shelf shields.
The first step is to install the development environment, System Workbench for STM32.
Then start a new C Project:
And select the options to match the current board. Notable is that the first time the wizard is run, the STMCube library will not yet be installed. Luckily there is a convenient button to download it.
This results in an empty project with a main.c file that just contains an infinite empty loop. Interestingly, there are utility files available for all the hardware on the board under Utilities/STM32746G-Discovery.
That makes it very easy to use the touchscreen and other devices. To use the touchscreen, all that is necessary is to add an include at the beginning of main.c - #include "stm32746g_discovery_lcd.h"
and immediately the LCD can be used with the functions provided in stm32746g_discovery_lcd.c
The LCD expects a certain range for the system clock, so the clock needs to be configured first. Lets define a function, SystemClock_Config:
/*
System Clock Configuration
System Clock source = PLL (HSE)
SYSCLK(Hz) = 216000000
HCLK(Hz) = 216000000
AHB Prescaler = 1
APB1 Prescaler = 4
APB2 Prescaler = 2
HSE Frequency(Hz) = 25000000
PLL_M = 25
PLL_N = 432
PLL_P = 2
PLL_Q = 9
VDD(V) = 3.3
Main regulator output voltage = Scale1 mode
Flash Latency(WS) = 7
*/
static void SystemClock_Config (void) {
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_OscInitTypeDef RCC_OscInitStruct;
/* Enable HSE Oscillator and activate PLL with HSE as source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_OFF;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 25;
RCC_OscInitStruct.PLL.PLLN = 432;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 9;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
/* Activate the OverDrive to reach the 216 MHz Frequency */
HAL_PWREx_EnableOverDrive();
/* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */
RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_H4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7);
}
Then we can drive the LCD with very little code at all:
#include "stm32f7xx.h"
#include "stm32746g_discovery.h"
#include "stm32746g_discovery_lcd.h"
static void SystemClock_Config (void) {
.
.
.
.
}
int main(void)
{
SystemInit();
HAL_Init();
SystemClock_Config();
BSP_LCD_Init();
BSP_LCD_LayerDefaultInit(0, LCD_FB_START_ADDRESS);
BSP_LCD_DisplayOn();
BSP_LCD_SelectLayer(0);
BSP_LCD_Clear(LCD_COLOR_GREEN); // draw color over whole screen
BSP_LCD_SetTextColor(LCD_COLOR_WHITE); // set color of text
BSP_LCD_SetBackColor(LCD_COLOR_BLUE); // set background color of text
BSP_LCD_DisplayStringAt(0, LINE(0),(uint8_t*)"LCD", CENTER_MODE); // draw text
while(1)
{
}
}
That results in a simple display:
The above is all the framework needed to build a GUI. What is missing is a way to detect touches. This is also surprisingly easy:
#include "stm32746g_discovery_ts.h"
.
.
.
//Configure touch screen
TS_StateTypeDef ts;
BSP_TS_Init(BSP_LCD_GetXSize(), BSP_LCD_GetYSize());
//uint8_t theResult = BSP_TS_ITConfig(); /* Touch screen interrupt configuration and enable */
while(1)
{
uint8_t result = BSP_TS_GetState(&ts);
if((ts.touchDetected)&& (TS_OK == result))
{
if (GEST_ID_NO_GESTURE == ts.gestureId)
{
for(int index = 0; index < TS_MAX_NB_TOUCH; index++)
{
if (ts.touchEventId[index]==TOUCH_EVENT_PRESS_DOWN)
{
if ((130 > ts.touchX[index])&&(100 > ts.touchY[index]))
{
// respond to press
}
}
}
}
//Debouncing
while(ts.touchDetected)
{
BSP_TS_GetState(&ts);
HAL_Delay(50);
}
}
}
With that a simple application with functional touch-GUI can be built:
The board uses 400 mA of current. That means I will likely power it separately rather than hoping the spectrometer can source it on the 5V line.
The horizontal and vertical lines in the middle are a placeholder to put a graph. Here, I plan to display the delay between sending the trigger signal and the actual output of the laser - probably with a photo-diode of some sort. To test this approach, I set up a reverse bias photodiode (OP906) in this configuration:
The test used a 9V battery for convenience and a 680 Ohm resistor to keep the current limit in the 10-20 mA range. I put up a piece of tape on the back end (there is an air gap so the tape does not touch the optics). It has a pinhole and I cradled the diode to it.
The pulse is <100 us, so clearly the controller will have to sample faster than that...
Some experimentation showed that the photo-diode does not have to be in the exact center. That means that I can use a regular LED in the center to assist with aiming and focus, while placing the photo-diode off-center and still be able to sense the xenon flash.
I made an adapter in Fusion360 that allows me to mount the photo-diode in a more permanent fashion:
To monitor the Xenon flash driving the laser, we need an A/D channel. There is a good reference on how to use these here:
Here is the list of STM32 to Arduino pin assignments:
Because I am using a breakout board that I have on hand, not all the pins are easily usable with the headers I have. I decided on the following convenient pins
Then, with the use of a number of custom parts made in Fusion360, 3D printer and laser cutter, build #3 is starting to take shape:
The next step is aligning the optics for the light capture. | https://www.sites.google.com/site/janbeck/libs-spectrometer/libs-spectrometer---build-3 | CC-MAIN-2022-40 | refinedweb | 960 | 56.05 |
Opened 5 years ago
Closed 4 years ago
Last modified 4 years ago
#25847 closed New feature (fixed)
Make User.is_authenticated() and User.is_anonymous() "callable properties"
Description
There's an inconsistency between
is_authenticated and
is_superuser. The former is a method and the latter is a property, leading many people to do:
if request.user.is_authenticated: return sensitive_information
which is, of course, always executed.
I propose that is_authenticated be turned into a property, while it can also be a callable, for backwards-compatibility.
Change History (20)
comment:1 Changed 5 years ago by
comment:2 Changed 5 years ago by
comment:3 Changed 5 years ago by
The discussion is leaning towards making this change.
A possible deprecation of the callable form wasn't discussed.
comment:4 Changed 5 years ago by
comment:5 Changed 4 years ago by
comment:6 Changed 4 years ago by
comment:7 Changed 4 years ago by
comment:8 Changed 4 years ago by
I have put up a pull request here:
@apollo13 mentioned that we might want to support the case where a custom user model defines is_anonymous / is_authenticated as methods instead of properties. In this case we could do something like this to monkey-patch that user model to the new style:
def __new__(cls): if not isinstance(cls.is_anonymous, property): real_is_anonymous = cls.is_anonymous cls.is_anonymous = property(lambda x: CallableBool(real_is_anonymous(x))) return super(AbstractBaseUser, cls).__new__(cls)
comment:9 Changed 4 years ago by
Alternatively, we could add a system check that raises a warning for an incompatible implementation.
comment:10 Changed 4 years ago by
comment:11 Changed 4 years ago by
Left comments for improvement.
comment:12 Changed 4 years ago by
comment:13 Changed 4 years ago by
@timgraham: I feel this should get reverted for now. We have to consider custom user models which did define this as a method. A warning is not enough, either his is a hard error or we ensure that it is backwards compatible. Allowing custom user models to have a method is a security risk since all checks will now return true…
comment:14 Changed 4 years ago by
comment:15 Changed 4 years ago by
I was thinking of adding a "compatibility" system check to detect that. I'll do it before 1.10 alpha if no one else takes it.
comment:16 Changed 4 years ago by
Unless that system check is a hard error I am against it. (Ie it does have to be ERROR, so we can ensure that we do not open ourself to security issues) -- can we justify the backwards incompatibility?
I bumped an old django-developers discussion to get opinions about this. | https://code.djangoproject.com/ticket/25847 | CC-MAIN-2020-34 | refinedweb | 447 | 53.41 |
Hi All.
For some odd reason it feels like this should be an extremely easy principle but yet I cannot seem to do this properly.
I know that there might be other ways to accomplish this but for the sake of my current project, i require this.
What i need is to call a method within a class that belongs to the global namespace from within a class that belongs to a defined namespace.
<?php $myNsClass = 'myNamespace\someClass'; echo $myNsClass::printHello("John"); class myClass { function sayHello($name) { return 'Hello ' . $name; } } namespace myNamespace { class someClass { function printHello($name) { // call sayHello in myClass $classsss = new myClass(); return $classsss->sayHello($name); } } } ?> | https://www.daniweb.com/programming/web-development/threads/491931/accessing-non-namespaced-class-from-within-a-namespaced-class | CC-MAIN-2018-43 | refinedweb | 108 | 59.43 |
Hello, »
EasyCriteria 2.0 – JPA Criteria should be easy ...Read More »
EasyCriteria – An easy way to use the JPA Criteria
Today we will see about this tool that make easier to use the JPA Criteria. The application that uses this library will be cleaner, easier to use and portable across the JPA implementations. At the end of this post you will find the source code to download. What is Criteria? Currently is the best solution to create dynamic queries. Imagine ...Read More »
JSF Simple Ajax Samples
Today we will see some Simple Samples of Ajax with JSF. If you want to see other posts about JSF/Web Applications click on the next links: JSF Persisting Objects and Messages after a Redirect ,User Login Validation with JAAS and JSF, JSF: Converter and Bean AutoComplete, JSF – Hello World, Auto Complete, Handling Exceptions on a WebApp, User Authentication (Filter/Servlet), ...Read More »
Ultimate JPA Queries and Tips List – Part 1
There are several JPAs “how to” that we can find on the internet, here in this blog, that teaches how to do several tasks with JPA. Usually I see some people asking questions about Queries with JPA; usually to answer this kind of questions several links are provided trying to find a solution to the question. Until today I could ...Read More »
Ultimate JPA Queries and Tips List – Part 2
This part continues from the first part of the series. J ...Read More »
Ultimate JPA Queries and Tips List – Part 3
Before you read the third part , remember the first and second part of the series JPA: Creating a object from a query The JPA allow us to create objects inside a query, just with the values that we need: package com.model; public class PersonDogAmountReport { private int dogAmount; private Person person; public ...Read More »
Four solutions to the LazyInitializationException – Part 2
This article continues from part 1 of the tutorial. Load ...Read More »
Four solutions to the LazyInitializationException – Part 1
In the post today we will talk about the common LazyInitializationException error. We will see four ways to avoid this error, the advantage and disadvantage of each approach and in the end of this post, we will talk about how the EclipseLink handles this exception. To see the LazyInitializationException error and to handle it, we will use an application JSF ...Read More » | https://www.javacodegeeks.com/author/Hebert-Coelho/ | CC-MAIN-2017-04 | refinedweb | 390 | 59.33 |
In this tutorial, we will learn how to create a preloader for your game.
Despite the small size of a flash game, most of them still amounts to about 1 MB or more. Even though most net surfers are starting to get more decent bandwidth, the Flash game will still take a while to load.
If you were to just deploy the game as it is (without a preloader) online, visitors will see a Blank screen while the game is loading. This is definitely a big NO NO since then they would be wondering if this game is playable or not. There is no feedback about the progress of the loading, and this uncertainty will inevitably cause them to wander off to other games.
The other advantage of having a preloader is that you can start interacting with the players even before the game begins. Some interesting graphics can be used to spice up the boring wait time. I've seen some flash games which include a minigame in the preloader to entertain the player while waiting. These are good ideas if done right. The last thing you want is to overload your preloader such that it needs yet another preloader!
In the tutorial, you'll see a setup like below.
MakeFlashGames_A.swf is the preloader file, whereas testPreloader.swf is the actual game you have coded. When the player visits your game, your website should be loading this MakeFlashGames_A.swf instead. The screenshot below it shows the progress bar that will act as a feedback to the player that the game is loading well.
When the game is fully loaded, the preloader components will be removed, and the game runs as per normal as shown in the screenshot.
The files you need to create this preloader can be downloaded from here.
After you open up MakeFlashGames_A.fla, you should be able to find 3 components already placed on the Contents layer.
mcPreloaderFrame, acts as a boundary around the loading bar to allow the user a sense of how long the downloading of the game is going to take.
mcPreloaderBar is the actual bar that grows from the left to the right according to the % amount of data downloaded thus far.
txtPreloader is the textual representation of the % amount of data downloaded thus far.
Use the rectangle tool to draw a rectangle on the stage. With these settings of the rectangle tool, you should create a frame as well as an inner fill of the rectangle. The inner preloader bar is of length 100 pixels here for easy demonstration of the loading percentage. You are free to choose any length you want. More on this will be mentioned later.
Select the outer frame only, and convert it into a MovieClip (Modify -> Convert to Symbol). Give it an instance name of mcPreloaderFrame. Likewise, select the filled bar and convert it into another MovieClip. Give it an instance name of mcPreloaderBar.
You need to do an additional step with the preloader bar because you want it to grow from left to right. Using the Free Transform Tool, move the center registration point to the leftmost point.
Next, create the text field by using the Text Tool. Then name it txtPreloader.
Now that our UI assets are in place, let's move on to the actual code needed for the preloading to work.
import flash.display.*;
import flash.net.*;
import flash.events.*;
We first import in the necessary components from the default flash libraries. I am using an * here as a wildcard to import all the classes from these 3 libraries. Since it doesn't cause any significant performance overhead to do this, I think this easier than importing each individual file. Of course, if you want, you can just import the necessary classes as you'll see later on.
//****************
//Form the request
//****************
//Specify the exact URL here.
//For testing on local, use this:
//-------------------------------
var myRequest:URLRequest = new URLRequest("testPreloader.swf");
For the preloader to know which game file to load, you need to specify a url request first. If you are testing it on your local server, you can set it to testPreloader.swf. Do make sure that these files are in the same directory. But take note that when you are testing it locally, the preloader effectively loads your file almost instantly.
Flash provided a way to simulate your preloader testing. Go to View and set the appropriate download settings. You may want to test out the download speed for users from a variety of bandwidth. Once it's set, press Ctrl+Enter again to simulate the download. Now, the preloader bar will slowly grow to simulate the downloading of game data.
When the game goes live, your preloader should be downloading from an online URL, so modify it accordingly. It should look something like below.
//****************
//Form the request
//****************
//Specify the exact URL here.
//On actual server, use this:
//-------------------------------
var myRequest:URLRequest = new URLRequest(
"");
After you have created this request, you need to create a loader to load the request.
//****************
//Create a Loader
//****************
var myLoader:Loader = new Loader();
myLoader.load(myRequest);
function showProgress(evt:ProgressEvent):void
{
//Text Version of Preloading
//--------------------------
txtPreloader.text = Math.round((evt.bytesLoaded/evt.bytesTotal)*100)+"%";
//Bar Progress Version of Preloading
//--------------------------
mcPreloaderBar.width = Math.round((evt.bytesLoaded/evt.bytesTotal)*100);
}
function showLoaded(evt:Event):void
{
myLoader.contentLoaderInfo.removeEventListener(
ProgressEvent.PROGRESS,showProgress);
myLoader.contentLoaderInfo.removeEventListener(
Event.COMPLETE,showLoaded);
removeChild(txtPreloader);
removeChild(mcPreloaderBar);
removeChild(mcPreloaderFrame);
mcPreloaderBar = null;
mcPreloaderFrame = null;
txtPreloader = null;
addChild(myLoader);
}
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,showProgress);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,showLoaded);
Lines 3 and 4 creates a Loader object and gets it to load the urlRequest we created earlier on to point to the actual game swf file.
Next, we create 2 functions, showProgress and showLoaded. showProgress does exactly what its name suggests --- it will handle the display each time data is loaded into the preloader. It grows the preloader bar according to the % of data downloaded. The formula Math.round((evt.bytesLoaded/evt.bytesTotal)*100) will work since the preloader bar is 100 pixels. If the length of the bar is changed, modify and multiply it accordingly by the length of the bar.
The function showLoaded is triggered only when the loading is fully complete. The function firstneeds to clean up and remove all the components used during the preloading phase. This is handled in lines 20 to 30. After they are removed, we add the loaded object (contained within myLoader) to the stage in line 32.
Lines 35 to 36 adds the listeners to monitor for the progress and loading completion.
With this, you have created a very simple preloader which you can code independently from your own game swfs. And the best part is this preloader is mostly reusable. You just have to change the url link as well as some of the graphics to suit your game.
If you want, you can now try experimenting to add nicer effects to the preloader, or incorporate some mini activity the players can engage in. | http://makeflashgames.com/tutorials/tutA.php | CC-MAIN-2017-51 | refinedweb | 1,170 | 65.42 |
Hello, reader. I've been learning c++ like a mother recently and, believe it or not, I've encountered a problem! Or, more of a writers block.
note:You don't have to read all this crap, my question is at the end of this post.
I'm making an account management program to better my skill in programming.
It accepts input from the user for personal information then saves it to a .txt file.
I'll show you the code so you can get a better idea of what I'm talking about:
Right now it's a mess and I haven't got half the features done, but what it's suppose to do is open up, give you the option to "create an account", and then save it.Right now it's a mess and I haven't got half the features done, but what it's suppose to do is open up, give you the option to "create an account", and then save it.Code:/* Account Management. This is an information database program. By Jacob Keller March 12, 2008 */ #include <iostream> #include <cstring> #include <fstream> using namespace std; int main() { char yes[10]; char name[50]; char lastname[50]; char fullname[100]; char phonenumber[11]; char address[100]; ofstream account_a ("accounts.txt", ios::app); cout<<"To create an account, type 'new'. "; if(strcmp(yes,"new")==0) { cout<<"Enter first name: \n"; cin.getline(name,50); cout<<"Enter last name: \n"; cin.getline(lastname,50); cout<<"Enter home phone number: \n"; cin.getline(phonenumber,11); cout<<"Enter address: \n"; cin.getline(address,100); //Group info. strcat(fullname,name); strcat(fullname," "); strcat(fullname,lastname); account_a<<"Name: " <<fullname<<". Address: "<<address<<". Phone Number: "<<phonenumber<<"."; cout<<"New account saved to accounts.txt \n"; } cin.get(); }
But, (because of cin.get(); I believe) it closes once you press enter, not giving the user a chance to create an account. The only way I see of resolving this problem is by hitting a key without hitting the enter key.
So is there a way to make the program wait for the user to press a specific key instead of using enter? If so, please tell me. | http://cboard.cprogramming.com/cplusplus-programming/100296-wait-specific-key-press-cplusplus.html | CC-MAIN-2015-06 | refinedweb | 363 | 75.81 |
PySpark
Pyspark DataFrame
In this article, we’ll discuss 10 functions of PySpark that are most useful and essential to perform efficient data analysis of structured data.
#installing pyspark !pip install pyspark
#importing pyspark import pyspark #importing sparksessio from pyspark.sql import SparkSession #creating a sparksession object and providing appName spark=SparkSession.builder.appName("pysparkdf").getOrCreate()
This SparkSession object will interact with the functions and methods of Spark SQL. Now, let’s create a Spark DataFrame by reading a CSV file. We will be using simple dataset i.e. Nutrition Data on 80 Cereal products available on Kaggle.
#creating a dataframe using spark object by reading csv file df = spark.read.option("header", "true").csv("/content/cereal.csv")
#show df created top 10 rows df.show(10)
This is the Dataframe we are using for Data analysis. Now, let’s print the schema of the DataFrame to know more about the dataset.
df.printSchema()
The DataFrame consists of 16 features or columns. Each column contains string-type values.
Let’s get started with the functions:
- select(): The select function helps us to display a subset of selected columns from the entire dataframe we just need to pass the desired column names. Let’s print any three columns of the dataframe using select().
df.select('name', 'mfr', 'rating').show(10)
In the output, we got the subset of the dataframe with three columns name, mfr, rating.
- withColumn(): The withColumn function is used to manipulate a column or to create a new column with the existing column. It is a transformation function, we can also change the datatype of any existing column.
In the DataFrame schema, we saw that all the columns are of string type. Let’s change the data type of calorie column to an integer.
df.withColumn("Calories",df['calories'].cast("Integer")).printSchema()
In the schema, we can see that the Datatype of calories column is changed to the integer type.
- groupBy(): The groupBy function is used to collect the data into groups on DataFrame and allows us to perform aggregate functions on the grouped data. This is a very common data analysis operation similar to groupBy clause in SQL.
Let’s find out the count of each cereal present in the dataset.
df.groupBy("name", "calories").count().show()
- orderBy(): The orderBy function is used to sort the entire dataframe based on the particular column of the dataframe. It sorts the rows of the dataframe according to column values. By default, it sorts in ascending order.
Let’s sot the dataframe based on the protein column of the dataset.
df.orderBy("protein").show()
We can see that the entire dataframe is sorted based on the protein column.
- split(): The split() is used to split a string column of the dataframe into multiple columns. This function is applied to the dataframe with the help of withColumn() and select().
The name column of the dataframe contains values in two string words. Let’s split the name column into two columns from space between two strings.
fropm pyspark.sql.functions import split
df1 = df.withColumn('Name1', split(df['name'], " ").getItem(0)) .withColumn('Name2', split(df['name'], " ").getItem(1))
df1.select("name", "Name1", "Name2").show()
In this output, we can see that the name column is split into columns.
- lit(): The lit function is used to add a new column to the dataframe that contains literals or some constant value.
Let’s add a column “intake quantity” which contains a constant value for each of the cereals along with the respective cereal name.
from pyspark.sql.functions import lit
df2 = df.select(col("name"),lit("75 gm").alias("intake quantity")) df2.show()
In the output, we can see that a new column is created “intak quantity” that contains the in-take a quantity of each cereal.
- when(): The when the function is used to display the output based on the particular condition. It evaluates the condition provided and then returns the values accordingly. It is a SQL function that supports PySpark to check multiple conditions in a sequence and return the value. This function similarly works as if-then-else and switch statements.
Let’s see the cereals that are rich in vitamins.
from pyspark.sql.functions import when
df.select("name", when(df.vitamins >= "25", "rich in vitamins")).show()
- filter(): The filter function is used to filter data in rows based on the particular column values. For example, we can filter the cereals which have calories equal to 100.
from pyspark.sql.functions import filter
df.filter(df.calories == "100").show()
In this output, we can see that the data is filtered according to the cereals which have 100 calories.
- isNull()/isNotNull(): These two functions are used to find out if there is any null value present in the DataFrame. It is the most essential function for data processing. It is the major tool used for data cleaning.
Let’s find out is there any null value present in the dataset.
#isNotNull()
from pyspark.sql.functions import * #filter data by null values df.filter(df.name.isNotNull()).show()
There are no null values present in this dataset. Hence, the entire dataframe is displayed.
isNull():
df.filter(df.name.isNull()).show()
Again, there are no null values. Therefore, an empty dataframe is displayed.
In this blog, we have discussed the 9 most useful functions for efficient data processing. These PySpark functions are the combination of both the languages Python and SQL.
Thanks for reading. Do let me know if there is any comment or feedback.
The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.You can also read this article on our Mobile APP
| https://www.analyticsvidhya.com/blog/2021/05/9-most-useful-functions-for-pyspark-dataframe/ | CC-MAIN-2021-25 | refinedweb | 952 | 58.99 |
Name | Synopsis | Description | Return Values | Errors | See Also
#include <sys/types.h> int mincore(caddr_t addr, size_t len, char *vec);
The mincore() function determines the residency of the memory pages in the address space covered by mappings in the range [addr, addr + len]. The status is returned as a character-per-page in the character array referenced by *vec (which the system assumes to be large enough to encompass all the pages in the address range). The least significant bit of each character is set to 1 to indicate that the referenced page is in primary memory, and to 0 to indicate that it is not. The settings of other bits in each character are undefined and may contain other information in future implementations.
Because the status of a page can change between the time mincore() checks and returns the information, returned information might be outdated. Only locked pages are guaranteed to remain in memory; see mlock(3C).
Upon successful completion, mincore() returns 0. Otherwise, -1 is returned and errno is set to indicate the error.
The mincore() function will fail if:
The vec argument points to an illegal address.
The addr argument is not a multiple of the page size as returned by sysconf(3C), or the len argument has a value less than or equal to 0.
Addresses in the range [addr, addr + len] are invalid for the address space of a process or specify one or more pages which are not mapped.
mmap(2), mlock(3C), sysconf(3C)
Name | Synopsis | Description | Return Values | Errors | See Also | http://docs.oracle.com/cd/E19253-01/816-5167/6mbb2jahm/index.html | CC-MAIN-2015-32 | refinedweb | 259 | 51.99 |
Basic code that should help you get started with Interactive Brokers API.
5 Downloads
Updated 30 Nov 2010
A collection of classes that shows how to wrap IB API inside a class and use event handlers.
For more details see
Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.
Zheng (view profile)');
Zheng (view profile)
Hi Jev, Is it possible to give me an example how to execute the positions via your api? So many thanks.
DN (view profile)
Jev, At a quick glance this seems excellent since I last saw max dama's stuff he started with some years ago. Now with windows 7's 64 bit system is there allot of changes needed? Can i just use your code as is?
thxs again
faruto (view profile)
Tobias (view profile)
Thanks! Really nice! Some modification should be done to make it more flexible. I for example introduced a loop to acquire more data.
Anyhow, great program!
Mate 2u (view profile)
Hi, I see you are printing the prices and time. If you want to carry on listening but storing in an array at real time how would this be possible?
Best,
Prashant bajpayee (view profile)
I am trying to connect IB API on Matlab. I am able to connect to tws but when I try to get historical data I am getting following error in this command:
obj about the solution?
regards
prashant
Jev Kuznetsov (view profile)
I am aware of the namespace problem... will fix it shortly and upload the new code. For now, just remove the 'IB.' prefix .
Chris (view profile)
Ahh... got it... RTM!
Just delete all the references to the namespace the "IB." from the CTws.m.
Bingo!
=D
Chris
Chris (view profile)
Hi Jev,
Just wanted to say thanks for posting the code!
Very helpful!
I'm using the Max Dama version right now but this is a very interesting version. Good job on the genericIBEvent.
Excellent job commenting the code.
The demoScript.m is very great!
There is however one error popping up.
I'm still pretty new to the OOP style of MATLAB so it could just be my setup/environment. (matlab 2010a)
So here's what I'm getting:
Running:
tws.subscribe('GOOG');
Exception:
>> tws.subscribe('GOOG');
??? Undefined variable "IB" or class "IB.CSymbolData".
Error in ==> CTws>CTws.subscribe at 68
obj.symbolData{iNewSubs} = IB.CSymbolData(symbol);
I'll keep reading though the code. =D
Thanks again!
Chris (view profile) | http://www.mathworks.com/matlabcentral/fileexchange/29434-connecting-to-interactive-brokers-via-activex-api?requestedDomain=www.mathworks.com&nocookie=true | CC-MAIN-2017-47 | refinedweb | 414 | 77.64 |
Perl 5.8.0 is the first version of Perl with a stable threading implementation. Threading has the potential to change the way we program in Perl, and even the way we think about programming. This article explores Perl's new threading support through a simple toy application - an elevator simulator.
Until now, Perl programmers have had a single mechanism for
parallel processing - the venerable
fork(). When a program forks,
an entirely new process is created. It runs the same code as the
parent process, but exists in its own memory space with no access to
the parent process' memory. Communication between forked processes
is possible but it's not at all convenient, requiring pipes, sockets,
shared memory or other clumsy mechanisms.
In contrast, multiple threads exist inside a single process, in the same memory space as the creating thread. This allows threads to communicate much more easily than separate processes. The potential exists for threads to work together in ways that are virtually impossible for normal processes.
Additionally, threads are faster to create and use less memory than full processes (to what degree depends on your operating system). Perl's current threading implementation doesn't do a good job of realizing these gains, but improvements are expected. If you learn to thread now, then you'll be ready to take advantage of the extra speed when it arrives. But even if it never gets here, thread programming is still a lot of fun!
Building a Threading Perl
To get started with threads you'll need to compile Perl 5.8.0 () with threads enabled. You can do that with this command in the unpacked source directory:
sh Configure -Dusethreads
Also, it's a good idea to install your thread-capable Perl someplace
different than your default install as enabling threading will slow
down even nonthreaded programs. To do that, use the
-Dprefix
argument to configure. You'll also need to tell Configure not to link
this new Perl as
/usr/bin/perl with
-Uinstallusrbinperl. Thus, a
good Configure line for configuring a threaded Perl might be:
sh Configure -Dusethreads -Dprefix=~/myperl -Uinstallusrbinperl
Now you can
make and
make install. The resulting Perl binary
will be ready to run the simulator in Listing 1, so go ahead and give
it a try. When you get back, I'll explain how it works.
An Elevator Simulator
The elevator simulator's design was inspired by an assignment from Professor Robert Dewar's class in programming languages at New York University. The objective of that assignment was to learn how to use the threading features of Ada. The requirements are simple:
- Each elevator and each person must be implemented as a separate thread.
- People choose a random floor and ride up to it from the ground floor. They wait there for a set period of time and then ride back down to the ground floor.
- At the end of the simulation, the user receives a report showing the efficiency of the elevator algorithm based on the waiting and riding time of the passengers.
- Basic laws of physics must be respected. No teleporting people allowed!
The class assignment also required students to code a choice of elevator algorithms, but I've left that part as an exercise for the reader. (See how lazy I can get without a grade hanging over my head?)
When you run the simulator you'll see output like:
$ ./elevator.pl Elevator 0 stopped at floor 0. Elevator 1 stopped at floor 0. Elevator 2 stopped at floor 0. Person 0 waiting on floor 0 for elevator to floor 11. Person 0 riding elevator 0 to floor 11. Elevator 0 going up to floor 11. Person 1 waiting on floor 0 for elevator to floor 1. Person 2 waiting on floor 0 for elevator to floor 14. Person 2 riding elevator 1 to floor 14. Person 1 riding elevator 1 to floor 1. Elevator 1 going up to floor 1.
And when the simulation finishes, you'll get some statistics:
Average Wait Time: 1.62s Average Ride Time: 4.43s
Longest Wait Time: 3.95s Longest Ride Time: 10.09s
Perl's Threading Flavor
Before jumping headlong into the simulator code I would like to introduce you to Perl's particular threading flavor. There are a wide variety of threading models living in the world today - POSIX threads, Java threads, Linux threads, Windows threads, and many more. Perl's threads are none of these; they are of an entirely new variety. This means that you may have to set aside some of your assumptions about how threads work before you can truly grok Perl threads.
Note that Perl's threads are not 5.005 threads. In Perl 5.005 an experimental threading model was created. Now known as 5.005 threads, this system is deprecated and should not be used by new code.
In Perl's threading model, variables are not shared by default unless explicitly marked to be shared. This is important, and also different from most other threading models, so allow me to repeat myself. Unless you mark a variable as shared it will be treated as a private thread-local variable. The downside of this approach is that Perl has to clone all of the nonshared variables each time a new thread is created. This takes memory and time. The upside is that most nonthreaded Perl code will ``just work'' with threads. Since nonthreaded code doesn't declare any shared variables there's no need for locking and little possibility for problems.
Perl's threading model can be described as low-level, particularly compared to the threading models of Java and Ada. Perl offers you the ability to create threads, join them and yield processor time to other threads. For communication between threads you can mark variables as shared, lock shared variables, wait for signals on shared variables, and send signals on shared variables. That's it!
Most higher-level features, like Ada's entries or Java's synchronized methods, can be built on top of these basic features. I expect to see plenty of development happening on CPAN in this direction as more Perl programmers get into threads.
Preamble
Enough abstraction, let's see this stuff work! The elevator simulator
in Listing 1 starts with a section of POD documentation describing how
to use the program. After that comes a block of
use declarations:
use 5.008; # 5.8 required for stable threading use strict; # Amen use warnings; # Hallelujah use threads; # pull in threading routines use threads::shared; # and variable sharing routines
The first line makes sure that Perl version 5.8.0 or later is used to
run the script. It isn't written
use 5.8.0 because that's a syntax
error with older Perls and the whole point is to produce a friendly
message telling the user to upgrade. The next lines are the
obligatory
strict and
warnings lines that will catch many of the
errors to which my fingers are prone.
Next comes the
use threads call that tells Perl I'll be using
multiple threads. This must come as early as possible in your
programs and always before the next line,
use threads::shared. The
threads::shared module allows variables to be shared between
threads, making communication between threads possible.
Finally, GetOpt::Long is used to load parameters from the command
line. Once extracted, the parameter values are stored in global
variables with names in all caps (
$NUM_ELEVATORS,
$PEOPLE_FREQ,
and so on).
Building State
The building is represented in the simulation with three shared
variables,
%DOOR,
@BUTTON and
%PANEL. These variables are
declared as shared using the
shared attribute:
# Building State our %DOOR : shared; # a door for each elevator on each floor our @BUTTON : shared; # a button for each floor to call the elevators our %PANEL : shared; # a panel of buttons in each elevator for each floor
When a variable is marked as shared its state will be synchronized between threads. If one thread makes a change to a shared variable then all the other threads will see that change. This means that threads will need to lock the variable in order to access it safely, as I'll demonstrate below.
The building state is initialized in the
init_building() function.
# initialize building state sub init_building { # set all indicators to 0 to start the simulation for my $floor (0 .. $NUM_FLOORS - 1) { $BUTTON[$floor] = 0; for my $elevator (0 .. $NUM_ELEVATORS - 1) { $PANEL{"$elevator.$floor"} = 0; $DOOR{"$elevator.$floor"} = 0; } } }
The buttons on each floor are set to 0 to indicate that they are
``off.'' When a person wants to summon the elevator to a floor they
will set the button for that floor to 1 (
$BUTTON[$floor] = 1).For
each elevator there are a set of panel buttons and a set of doors, one
for each floor. These are all cleared to 0 at the start of the
simulation. When an elevator reaches a floor it will open the door by
setting the appropriate item in
%DOOR to 1
(
$DOOR{"$elevator.$floor"} = 1). Similarly, people tell the
elevators where to go by setting entries in
%PANEL to 1
(
$PANEL{"$elevator.$floor"} = 1).
Figure 2 shows a single-elevator building with four floors and three people. Don't worry if this doesn't make much sense yet, you'll see it in action later.
Thread Creation
After calling
init_building() to initialize the shared building
state variables, the program creates the elevator threads inside
init_elevator():
# create elevator threads sub init_elevator { our @elevators; for (0 .. $NUM_ELEVATORS - 1) { # pass each elevator thread a unique elevator id push @elevators, threads->new(\&Elevator::run, id => $_); } }
Threads are created by calling
threads->new(). The first
argument to
threads->new() is a subroutine reference where the
new thread will begin execution. In this case, it is the
Elevator::run() subroutine declared later in the program. Anything
after the first argument is passed as an argument to this subroutine.
In this case each elevator is given a unique ID starting at 0.
The return value from
threads->new() is an object representing
the created thread. This is saved in a global variable,
@elevators, for use later in shutting down the simulation.
After the elevators are created the simulation is ready to send in
people with the
init_people() routine:
# create people threads sub init_people { our @people; for (0 .. $NUM_PEOPLE - 1) { # pass each person thread a unique person id and a random # destination push @people, threads->new(\&Person::run, id => $_, dest => int(rand($NUM_FLOORS - 2)) + 1);
# pause if we've launched enough people this second sleep 1 unless $_ % $PEOPLE_FREQ; } }
This routine creates
$PEOPLE_FREQ people and then sleeps for one
second before continuing. If this wasn't done, then all the people would
arrive at the building at the same time and the simulation would be
rather boring. Notice that while the main thread sleeps the
simulation is proceeding in the elevator and people threads.
The people threads start at
Person::run(), which will be described
later.
Person::run() receives two parameters - a unique ID and a
randomly chosen destination floor. Each person will board an elevator
at the ground floor, ride to this floor, wait there for a set period
of time and then ride an elevator back down.
The Elevator Class
Each elevator thread contains an object of the Elevator class. The
Elevator::run() routine creates this object as its first activity:
# run an Elevator thread, takes a numeric id as an argument and # creates a new Elevator object sub run { my $self = Elevator->new(@_);
Notice that since
$self is not marked shared it is a
thread-local variable. Thus, each elevator has its own private
$self object. The
new() method just sets up a hash with some
useful state variables and returns a blessed object:
# create a new Elevator object sub new { my $pkg = shift; my $self = { state => STARTING, floor => 0, dest => 0, @_, }; return bless($self, $pkg); }
All elevators start at the ground floor (floor 0) with no destination.
The
state attribute is set to
STARTING which comes from this set
of constants used to represent the state of the elevator:
# state enumeration use constant STARTING => 0; use constant STOPPED => 1; use constant GOING_UP => 2; use constant GOING_DOWN => 3;
After setting up the object, the elevator thread enters an infinite
loop looking for button presses that will cause it to travel to a
floor. At the top of the loop
$self->next_dest() is called to
determine where to go:
# run until simulation is finished while (1) { # get next destination $self->{dest} = $self->next_dest;
The
next_dest() method examines the shared array
@BUTTON to
determine if any people are waiting for an elevator. It also looks at
%PANEL to see if there are people inside the elevator heading to a
particular floor. Since
next_dest() accesses shared variables it
starts with a call to
lock() for each shared variable:
# choose the next destination floor by looking at BUTTONs and PANELs sub next_dest { my $self = shift; my ($id, $state, $floor) = @{$self}{('id', 'state', 'floor')}; lock @BUTTON; lock %PANEL;
Perl's
lock() is an advisory locking mechanism, much like
flock(). When a thread locks a variable it will wait for any other
threads to release their locks before proceeding. The lock obtained
by
lock() is lexical - that is, it lasts until the enclosing scope
is exited. There is no
unlock() call, so it's important to
carefully scope your calls to
lock(). In this case the locks on
@BUTTON and
%PANEL last until
next_dest() returns.
next_dest()'s logic is simple, and largely uninteresting for the
purpose of learning about thread programming. It does a simple scan
across
@BUTTON and
%PANEL looking for
1s and takes the first
one it finds.
Once
next_dest() returns the elevator has its marching orders. By
comparing the current floor (
$self->{floor}) to the destination
the elevator now knows whether it should stop, or travel up or down. First, let's look at what happens when the elevator decides to
stop:
# stopped? if ($self->{dest} == $self->{floor}) { # state transition to STOPPED? if ($self->{state} != STOPPED) { print "Elevator $id stopped at floor $self->{dest}.\n"; $self->{state} = STOPPED; }
# wait for passengers $self->open_door; sleep $ELEVATOR_WAIT;
The code starts by printing a message and changing the state attribute
if the elevator was previously moving. Then it calls the
open_door() method and sleeps for
$ELEVATOR_WAIT seconds.
The
open_door() method opens the elevator door. This allows
waiting people to board to elevator.
# open the elevator doors sub open_door { my $self = shift; lock %DOOR; $DOOR{"$self->{id}.$self->{floor}"} = 1; cond_broadcast(%DOOR); }
Like
next_dest(),
open_door() manipulates a shared variable so
it starts with a call to
lock(). It then sets the elevator door
for the elevator on this floor to open by assigning
1 to the
appropriate entry in
%DOOR. Then it wakes up all waiting person
threads by calling
cond_broadcast() on
%DOOR. I'll go into more
detail about
cond_broadcast() when I show you the Person class
later on. For now suffice it to say that the people threads wait on
the
%DOOR variable and will be woken up by this call.
The other states, for going up and going down, are handled similarly:
} elsif ($self->{dest} > $self->{floor}) { # state transition to GOING UP? if ($self->{state} != GOING_UP) { print "Elevator $id going up to floor $self->{dest}.\n"; $self->{state} = GOING_UP; $self->close_door; }
# travel to next floor up sleep $ELEVATOR_SPEED; $self->{floor}++;
} else { # state transition to GOING DOWN? if ($self->{state} != GOING_DOWN) { print "Elevator $id going down to floor $self->{dest}.\n"; $self->{state} = GOING_DOWN; $self->close_door; }
# travel to next floor down sleep $ELEVATOR_SPEED; $self->{floor}--; }
The elevator looks at the last value for
$self->{state} to
determine whether it was already heading up or down. If not, then it prints a
message and calls
$self->close_door(). Then it sleeps for
$ELEVATOR_SPEED seconds as it travels between floors and adjusts
its current floor accordingly.
The
close_door() method simply does the inverse of
open_door(),
but without the call to
cond_broadcast() since there's no point
waking people up if they can't get on the elevator:
# close the elevator doors sub close_door { my $self = shift; lock %DOOR; $DOOR{"$self->{id}.$self->{floor}"} = 0; }
Finally, at the bottom of the elevator loop there is a check on the
shared variable
$FINISHED:
# simulation over? { lock $FINISHED; return if $FINISHED; }
Since the elevator threads are in an infinite loop the main thread
needs a way to tell them when the simulation is over. It uses the
shared variable
$FINISHED for this purpose. I'll go into more
detail about why this is necessary later.
That's all there is to the Elevator class code. Elevators simply travel from floor to floor opening and closing doors in response to buttons being pushed by people.
The Person Class
Now that we've looked at the machinery, let's turn our attention to the inhabitants of this building, the people. Each person thread is created with a goal - ride an elevator up to the assigned floor, wait a bit and then ride an elevator back down. Person threads are also responsible for keeping track of how long they wait for the elevator and how long they ride. When they finish they report this information back to the main thread where it is output for your edification.
Person::run() starts the same way as
Elevator::run(), by
creating a new object:
# run a Person thread, takes an id and a destination floor as # arguments. Creates a Person object. sub run { my $self = Person->new(@_);
Inside
Person::new() two attributes are setup to keep track of the
person's progress, floor and elevator:
# create a new Person object sub new { my $pkg = shift; my $self = { @_, floor => 0, elevator => 0 }; return bless($self, $pkg); }
Back in
Person::run() the person thread begins waiting for the
elevator by calling
$self->wait(). The calls to
time() will
be used later to report on how long the person waited.
# wait for elevator going up my $wait_start1 = time; $self->wait; my $wait1 = time - $wait_start1;
The
wait() method is responsible for waiting until an elevator
arrives and opens its doors on this floor:
# wait for an elevator sub wait { my $self = shift;
print "Person $self->{id} waiting on floor 1 for elevator ", "to floor $self->{dest}.\n";
while(1) { $self->press_button(); lock(%DOOR); cond_wait(%DOOR); for (0 .. $NUM_ELEVATORS - 1) { if ($DOOR{"$_.$self->{floor}"}) { $self->{elevator} = $_; return; } } } }
# signal an elevator to come to this floor sub press_button { my $self = shift; lock @BUTTON; $BUTTON[$self->{floor}] = 1; }
After printing out a message, the code enters an infinite loop waiting
for the elevator. At the top of the loop, the
press_button()
method is called.
press_button() locks
@BUTTON and sets
$BUTTON[$self->{floor}] to
1. This will tell the elevators that a
person is waiting on the ground floor.
The code then locks
%DOOR and calls
cond_wait(%DOOR). This has
the effect of releasing the lock on
%DOOR and putting the thread to
sleep until another thread does a
cond_broadcast(%DOOR) (or
cond_signal(%DOOR), a variant of
cond_broadcast() that just
wakes a single thread). When the thread wakes up again it re-acquires
the lock on
%DOOR and then checks to see if the door that just
opened is on this floor. If it is the person notes the elevator and
returns from
wait().
If there's no elevator on the floor where the person is waiting, the
loop is run again. The person presses the button again and then goes
back to sleep waiting for the elevator. You might be wondering why
the call to
press_button() is inside the loop instead of outside.
The reason is that it is possible for the person to wake up from
cond_wait() but have to wait so long to re-acquire the lock on
%DOOR that the elevator is already gone.
Once the elevator arrives, control returns to
run() and the person
boards the elevator:
# board the elevator, wait for arrival at destination floor and get off my $ride_start1 = time; $self->board; $self->ride; $self->disembark; my $ride1 = time - $ride_start1;
The
board() method is simple enough. It just turns off the
@BUTTON entry used to summon the elevator and presses the
appropriate button inside the elevator's
%PANEL:
# get on an elevator sub board { my $self = shift; lock @BUTTON; lock %PANEL; $BUTTON[$self->{floor}] = 0; $PANEL{"$self->{elevator}.$self->{dest}"} = 1; }
Next, the
run() code calls
ride() which does another
cond_wait() on
%DOOR, this time waiting for the door in the
elevator to open on the destination floor:
# ride to the destination sub ride { my $self = shift;
print "Person $self->{id} riding elevator $self->{elevator} ", "to floor $self->{dest}.\n";
lock %DOOR; cond_wait(%DOOR) until $DOOR{"$self->{elevator}.$self->{dest}"}; }
When the elevator arrives,
ride() will return and the person thread
calls
disembark(), which clears the entry in
%PANEL for this
floor and sets the current floor in
$self->{floor}.
# get off the elevator sub disembark { my $self = shift;
print "Person $self->{id} getting off elevator $self->{elevator} ", "at floor $self->{dest}.\n";
lock %PANEL; $PANEL{"$self->{elevator}.$self->{dest}"} = 0; $self->{floor} = $self->{dest}; }
After reaching the destination floor, the person thread waits for
$PEOPLE_WAIT seconds and then heads back down by repeating the
steps again with
$self->{dest} set to 0:
# spend some time on the destination floor and then head back sleep $PEOPLE_WAIT; $self->{dest} = 0;
When this is complete the person has arrived at the ground floor. The
thread ends by returning the recorded timing data with
return:
# return wait and ride times return ($wait1, $wait2, $ride1, $ride2);
The Grand Finale
While the simulation is running the main thread is sitting in
init_people() creating person threads periodically. Once this task
is complete the
finish() routine is called.
The first task of
finish() is to collect statistics from the people
threads as they complete:
# finish the simulation - join all threads and collect statistics sub finish { our (@people, @elevators);
# join the people threads and collect statistics my ($total_wait, $total_ride, $max_wait, $max_ride) = (0,0,0,0); foreach my $person (@people) { my ($wait1, $wait2, $ride1, $ride2) = $person->join; $total_wait += $wait1 + $wait2; $total_ride += $ride1 + $ride2; $max_wait = $wait1 if $wait1 > $max_wait; $max_wait = $wait2 if $wait2 > $max_wait; $max_ride = $ride1 if $ride1 > $max_ride; $max_ride = $ride2 if $ride2 > $max_ride; }
To extract return values from a finished thread the
join() method
must be called on the thread object. This method will wait for the
thread to end, which means that this loop won't finish until the last
person reaches the ground floor.
Once all the people are processed, the simulation is over. To tell
the elevators to shutdown the shared variable
$FINISHED is set to
1 and the elevators are joined:
# tell the elevators to shut down { lock $FINISHED; $FINISHED = 1; } $_->join for @elevators;
If this code were omitted the simulation would still end but Perl would print a warning because the main thread exited with other threads still running.
Finally,
finish() prints out the statistics collected from the
person threads:
# print out statistics print "\n", "-" x 72, "\n\nSimulation Complete\n\n", "-" x 72, "\n\n"; printf "Average Wait Time: %6.2fs\n", ($total_wait / ($NUM_PEOPLE * 2)); printf "Average Ride Time: %6.2fs\n\n", ($total_ride / ($NUM_PEOPLE * 2)); printf "Longest Wait Time: %6.2fs\n", $max_wait; printf "Longest Ride Time: %6.2fs\n\n", $max_ride;
The end!
A Few Wrinkles
Overall, the simulator was a fun project with few major stumbling blocks. However, there were a few problems or near problems that you would do well to avoid.
Deadlock
All parallel programs are susceptible to deadlock, but, by virtue of higher levels of inter-activity, threads suffer it more frequently. Deadlock occurs when independent threads (or processes) each need a resource the other has.
In the elevator simulator I avoided deadlock by always performing
multiple locks in the same order. For example,
Elevator::next_dest() begins with:
lock @BUTTON; lock %PANEL;
And in
Person::board() the same sequence is repeated:
lock @BUTTON; lock %PANEL;
If the lock calls in
Person::board() were reversed then the
following could occur:
- Elevator 2 locks
@BUTTON.
- Person 3 locks
%PANEL.
- Elevator 2 tries to lock
%PANELand blocks waiting for Person 3's lock.
- Person 3 tries to lock
@BUTTONand blocks waiting for Elevator 2's lock.
- Deadlock! Neither thread can proceed and the simulation will never end.
Modules
In general, unless a module has been specifically vetted as thread safe it cannot be used in a threaded program. Most pure Perl modules should be thread safe but most XS modules are not. This goes for core modules too!
An earlier version of the elevator simulator used Time::HiRes to allow
for fractional
sleep() times. This really helped speed up the
simulation since it meant that elevators could traverse more than one
floor per second. However, on further investigation (and advice from
Nick Ing-Simmons) I realized that Time::HiRes is not necessarily
thread safe. Although it seemed to work fine on my machine there's no
reason to believe that would be the case elsewhere, or even that it
wouldn't blow up at some random point in the future. The problem with
thread safety is that it's virtually impossible to test for; either
you can prove you have it or you must assume you don't!
Synchronized
rand()
The first version of the simulator I wrote had the people threads
calling
rand() inside
Person::run() to choose the destination
floor. I also had a call to
srand() in the main thread, not
realizing that Perl now calls
srand() with a good seed
automatically. The combination resulted in every person choosing the
same destination floor. Yikes!
The reason for this is that by calling
srand() in the main thread I
set the random seed. Then when the threads were created that seed was
copied into each thread. The call to
rand() then generated the
same first value in each thread.
Resources
Perl comes with copious threading documentation. You can read these
docs by following the links below or by using the
perldoc program
that comes with Perl.
- elevator.pl - Sample code from this article.
- perlthrtut () - a threading tutorial
- threads () - the reference for the threads module
- threads::shared () -the reference for the threads::shared module | http://www.perl.com/pub/2002/09/04/threads.html | CC-MAIN-2014-15 | refinedweb | 4,377 | 61.46 |
17499/there-way-prevent-kubectl-from-registering-kubernetes-nodes
$ kubectl delete nodes --all
and it deletes de-registers all the nodes including the masters. Now I can't connect to the cluster (Well, Obviously as the master is deleted).
Is there a way to prevent this as anyone could accidentally do this?
Extra Info: I am using KOps for deployment.
P.S. It does not delete the EC2 instances and the nodes come up on doing a EC2 instance reboot on all the instances.
By default, you using something like a superuser who can do anything he want with a cluster.
For limit access to a cluster for other users you can use RBAC authorization for. By RBAC rules you can manage access and limits per resource and action.
In few words, for do that you need to:
Create new cluster by Kops with --authorization RBAC or modify existing one by adding 'rbac' option to cluster's configuration to 'authorization' section:
authorization:
rbac: {}
Now, we can follow that instruction from Bitnami for create a user. For example, let's creating a user which has access only to office namespace and only for a few actions. So, we need to create a namespace firs:
kubectl create namespace office
Create a key and certificates for new user:
openssl genrsa -out employee.key 2048
openssl req -new -key employee.key -out employee.csr -subj "/CN=employee/O=bitnami"
Now, using your CA authority key (It available in the S3 bucket under PKI) we need to approve new certificate:
openssl x509 -req -in employee.csr -CA CA_LOCATION/ca.crt -CAkey CA_LOCATION/ca.key -CAcreateserial -out employee.crt -days 500
Creating credentials:
kubectl config set-credentials employee --client-certificate=/home/employee/.certs/employee.crt --client-key=/home/employee/.certs/employee.key
Setting a right context:
kubectl config set-context employee-context --cluster=YOUR_CLUSTER_NAME --namespace=office --user=employee
You can use the AWS node.js SDK ...READ MORE
Yes. Your credentials are used to sign ...READ MORE
AWS Marketplace Entitlement Service API Reference
The AWS ...READ MORE
this link helped : see hack solution by ...READ MORE
Hey @nmentityvibes, you seem to be using ...READ MORE
It can work if you try to put ...READ MORE
To solve this problem, I followed advice ...READ MORE
Try using ingress itself in this manner
except ...READ MORE
There isn't a built-in solution for this, ...READ MORE
Create a role with Elasticsearch permission.
Provide the iam:PassRole for ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/17499/there-way-prevent-kubectl-from-registering-kubernetes-nodes | CC-MAIN-2020-05 | refinedweb | 419 | 59.3 |
Messy desks can help you think, but at some point, they start to look like this:
And that's when you realize you need that bit of code that did some piece of magic for another control, but you can't remove it without three feet of paper falling on the floor. I know. I've lived it. This week.
So the second time I needed my store-some-form-variables-in-session-while-I-make-somebody-log-in code, I got smart. I didn't write it. I pretended it existed. I gave my imaginary friend an impressive name, LoginHandoffUtil, and started slapping methods on the sucker. Sure, Visual Studio got mad, and put the class in fire-engine red, but I didn't pull the trigger on creating it just yet. I was in a groove, and didn't want to hand the controls over. That's when ReSharper freaked me out. Because its tricked-out Intellisense started giving methods that I just made up, that didn't yet exist. Sure, they were screaming red, but they were there, at the click of a dot. Nice.
So I've got my consuming code written, and now I'm autogenerating class and method stubs. But I'm keeping the class in front of me, in the same code file. Consuming code up here needs something, so add it to the Util class down there. All in front of me, on my big messy desk, until I've got the thing working. Messy, but the new class is doing just one thing, just as Uncle Bob would like.
When it's time to go home, you should think about cleaning up your desk, maybe putting some papers in the trash, and the ones you need to keep in your files. So have ReSharper put the class in its own file. Presto, you have a nice small class that does just one thing. But where should you put it? Next to the consuming ASCX files, or in some Util folder somewhere, maybe even in a separate project? No worries, if you decide to move it later on, ReSharper can update namespaces to be consistent with the new location, while updating consuming references, so that your code still works.
The best part of the story was coming in the next day, tackling the next step in the project, and my new little class just worked. Bliss.
If you're interested in trying this out, there's a nice ReSharper video on using the tool for code generation while doing TDD. Soon, you'll be using Alt+Enter to make classes and methods appear, without touching your mouse. | http://www.dansolovay.com/2012/08/rocking-srp-with-resharper.html | CC-MAIN-2018-34 | refinedweb | 445 | 80.01 |
Remote arbitrary file corruption / creation flaw via injected files
Bug Description
Matthias Weckbecker from SUSE Security Team reported the following:
------------------
During our internal security audit efforts at SUSE for openstack, I have found
an issue in openstack-nova (compute).
Quoting from [1] (comment #1):
Vulnerable code (quoted), /usr/lib64/
[... snipped copy of utils.execute code ...]
It's already doing lots of things correctly, like e.g. calling Popen with
the first parameter being a list, still it is affected by traversal flaws.
Testcase (also from [1], comment #0):
mweckbecker@
<?xml version="1.0" encoding="UTF-8"?>
<server xmlns="http://
imageRef="http://
<metadata>
<meta key="My Server Name">foobar</meta>
</metadata>
<personality>
<file path=".
</file>
</personality>
</server>
mweckbecker@
"http://
-H"X-Auth-
-H"Content-
Additional note: This beast is calling tee with sudo, potentially allowing
attackers to even alter files such as /etc/passwd.
[1] https:/
Thanks, Matthias
Related branches
- Chuck Short: Pending requested 2012-03-22
- Diff: 56 lines (+14/-4)3 files modifieddebian/changelog (+8/-0)
debian/control (+6/-3)
debian/nova-console.install (+0/-1)
Added PTL to share the fun.
> I would not blame the utils.execute() code though, it's a low-level primitive that just does what it's told to do.
Well, there are probably multiple ways to address this and all of them come with their own pros and cons. Fixing it
directly at low-level means that all subsequent calls that will in turn boil down to utils.execute() code will be safe.
Otherwise we might find us ending up fixing "hundreds" of high-level occurrences.
The trick is that you can't decide at utils.execute() level what generic argument is or is not safe. In some cases passing "../.." is perfectly accepted use !
I see your point though... and as a strengthening low-level measure the rootwrap filter that allows to run mkdir/tee as root should also do a deeper inspection on arguments to check that it only affects nova stuff.
> The trick is that you can't decide at utils.execute() level what
> generic argument is or is not safe. In some cases passing "../.."
> is perfectly accepted use !
Just off the top of my head:
Doesn't Python offer something like Perl's caller() as well? Then you could
possibly perform whitelisting for functions that are allowed to pass "../../".
I'm assigning this to myself. I should have a patch up shortly for review/testing.
Here is a patch that address the issue directly in the file injection code. There is some unit test coverage, but I haven't tested this fully yet to ensure that the failure is clean when trying to start an instance.
I'm also going to add Pádraig Brady to this bug. In addition to working on OpenStack, he's also a GNU coreutils maintainer. He helped me refine this patch and can provide valuable input here if we need to explore any additional changes.
Here is the same patch for stable/essex.
I checked stable/diablo and the code is very different there. It looks like there is some xen specific support for file injection. I don't think it's vulnerable, but it would be nice for someone familiar with the xen code to check that.
Added markmc so he can help review the patches.
minor issue in the patch: can you replace the two hardcoded '/' with os.sep or os.path.sep ?
Otherwise looks good.
Hmm, I think the _path_within_fs() check needs to be called for all injected files, as one could upload an image with symlinks in various places to get back to the host.
For example if /root/.ssh in the image was a symlink to ../../.
Nice find Matthias
Russell: the way we're using commonprefix here, we may as well just use startswith() i.e.
os.path.
is equivalent to:
absolute_
FWIW, the xenapi driver handles injected_files via the guest agent and isn't vulnerable.
Pádraig is right:
def _inject_
sshdir = os.path.join(fs, 'root', '.ssh')
...
keyfile = os.path.
need to apply realpath() here too. Easiest is to add an 'append' arg to _inject_
def _inject_
meta.js could be a symlink ... again, we should just use _inject_
Ok, here's what I've come up with
Last patch looks good to me, especially with all tee calls now going through a single code path.
The remark from Vish about using os.sep instead of '/' still holds.
Looked into stable/diablo and although it doesn't support file injection (so it's not vulnerable to this precise issue), it's still vulnerable to Padraig's variation (upload an image with symlinks in meta.js, /etc/network or /root/.ssh). The impact is slightly lower in the second case, since it's harder to inject arbitrary data, but it affects more setups.
I think we should treat those as two separate issues, two separate CVEs, though probably in the same patch:
* Matthias's is about arbitrary file injection through <personality>, affects Essex/Folsom in libvirt-based setups
* Padraig's is about file corruption through net/ssh/metadata injection, affects Diablo/
Thoughts ?
Meant to comment on the os.sep thing - since the existing code already uses '/':
absolute_path = os.path.join(fs, path.lstrip('/'))
and we don't support compute nodes on any platforms where '/' isn't the path separator, I don't think it's an issue.
No problem with a later general "switch to os.sep" cleanup in Nova, though.
Splitting it into two separate CVEs makes sense to me since Diablo didn't have libvirt-
FYI, the blueprint for that was: https:/
Good point Thierry on the separate CVEs.
Mark nice refactoring in the patch. It's needs this fixup though:
diff --git a/nova/
index 8744dcc..730008b 100644
--- a/nova/
+++ b/nova/
@@ -380,7 +380,7 @@ def _inject_
utils.
utils.
- netfile = os.path.join('etc', 'interfaces')
+ netfile = os.path.join('etc', 'network', 'interfaces')
_inject_
Nice work on the patch, Mark. I have attached an updated version that includes the fix from pbrady. I also added Signed-off-by lines to show who all was involved in writing the patch.
Proposed Impact description:
Title: Arbitrary file injection/
Impact: Critical
Reporter: Matthias Weckbecker (SUSE Security team), Pádraig Brady (RedHat)
Products: Nova
Affects: All versions
Description:
Matthias Weckbecker from SUSE Security team reported a vulnerability in Nova compute nodes handling of file injection in disk images. By requesting files to be injected in malicious paths, a remote authenticated user could inject files in arbitrary locations on the host file system, potentially resulting in full compromise of the compute node. Only Essex and later setups running the OpenStack API over libvirt-based hypervisors are affected.
Upon further inspection of the code, Pádraig Brady from RedHat found an additional vulnerability. By crafting a malicious image and requesting an instance based on it, a remote authenticated user may corrupt arbitrary files on the host filesystem, potentially resulting in a denial of service. This affects all setups.
Next steps here:
* Master patch: needs formal pre-approval from nova core (Vish/Markmc ?)
* Essex patch: needs to be proposed
* Diablo patch: needs to be proposed
* Impact description: VMT members please ack
Once we've all this we can push the pre-announce to downstream stakeholders, to get CVEs and propose CRD.
Essex patch.
Same as Russell's latest version, except Essex uses json instead of jsonutils.
Folsom and Essex patches look good to me
+1for folsom/essex from me.
Thierry, do you want me to do the Diablo patch?
Diablo patch.
New version of the Diablo patch, with tests backported and correct paths used (thanks Padraig).
Please run through run_tests.sh if you've a run_tests.sh setup that works with stable/diablo :)
Diablo patch looks good too. cheers
all looks good to me. I'm happy with the .sep change going in later since its broken in a lot of other places :)
OK, will send notice to downstream stakeholders later today, based on the attached patches and impact description (comment 22). Please check that everything looks good before I do :)
Proposed CRD: July 3rd, 1500 UTC
I've only a small remark re comment 22.
It's not just corrupting arbitrary files on the host.
You could inject arbitrary keys into /root/.
Now that's probably not an issue as the attacker probably wouldn't have remote access to the host.
If that assumption is always valid, then comment 22 is fine as is.
#22 looks fine for me too. Thanks.
@Padraig: I think it's fair to assume you wouldn't run ssh on remotely-accessible compute nodes IPs. Anyway, the report is rated "critical" already, and I can't come up with a good wording that adequately covers that corner case :) Feel free to suggest if you care.
The vulnerability description and latest patches look good. One nit pick on the description is that "RedHat" should be "Red Hat" (with a space).
Downstream stakeholders email sent, CRD: July 3rd, 1500 UTC
CVE assignment:
Mathias's is CVE-2012-3360
Padraig's is CVE-2012-3361
Adding Dave Walker to coordinate stable/* releases, should have done that earlier.
Folsom/essex in, OSSA 2012-008
Diablo patch at https:/
Reviewed: https:/
Committed: http://
Submitter: Jenkins
Branch: stable/diablo
commit 1e218105b08b1af
Author: Thierry Carrez <email address hidden>
Date: Tue Jul 3 16:34:58 2012 +0200
Prevent key/net/md injection writing to host fs
Fix bug 1015531, CVE-2012-3361
Checks that the final normalized path that is about to be written
to is always within the mounted guest filesystem.
This is a Diablo backport of the part of Russell Bryant, Pádraig Brady
and Mark McLoughlin's Folsom patch that applies to stable/diablo.
Change-Id: I134c40258ff2c9
So, Ubuntu 12.04 LTS should be fixed between:
http://
http://.
Ouch :)
I would not blame the utils.execute() code though, it's a low-level primitive that just does what it's told to do.
The flaw is actually in nova/virt/
disk/api. py which does not check that "path" is still within the image mount_dir in inject_files() or _inject_ file_into_ fs(). | https://bugs.launchpad.net/nova/+bug/1015531 | CC-MAIN-2018-26 | refinedweb | 1,687 | 65.73 |
Write more semantic code with functional programming
Do you ever look at your code and see a waterfall of for loops? Do you find yourself having to squint your eyes and lean towards your monitor to get a closer look?
I know I do.
For loops are a Swiss army knife for problem-solving, but, when it comes to scanning code to get a quick read of what you’ve done, they can be overwhelming.
Three techniques — map, filter, and reduce — help remedy the for loop mania by offering functional alternatives that describe why you’re iterating. I previously wrote about getting started with these techniques in JavaScript, but the implementation is slightly different in Python.
We’ll briefly introduce each of the three techniques, highlight the syntactic differences between them in JavaScript and Python, and then give examples of how to convert common for loops.
What are Map, Filter, and Reduce?
Reviewing my previously written code, I realized that 95% of the time when looping through strings or arrays I do one of the following: map a sequence of statements to each value, filter values that meet specific criteria, or reduce the data set to a single aggregate value.
With that insight, these three methods are recognition — and implementation — that the reason you loop through an iterable often falls into one of these three functional categories:
- Map: Apply the same set of steps to each item, storing the result.
- Filter: Apply validation criteria, storing items that evaluate True.
- Reduce: Return a value that is passed from element to element.
What Makes Python Map/Filter/Reduce Different?
In Python, the three techniques exist as functions, rather than methods of the Array or String class. This means that instead of writing
my_array.map(function) you would write
map(function, my_list).
Additionally, each technique will require a function to be passed, which will be executed for each item. Often, the function is written as an anonymous function (called a fat arrow function in JavaScript). However, in Python you often see lambda expressions being used.
The syntax between a lambda expression and arrow function is actually quite similar. Swap the
=> for a
: and make sure to use the keyword
lambda and the rest is almost identical.
// JavaScript Arrow Function const square = number => number * number;// Python Lambda Expression square = lambda number: number * number
One key difference between arrow functions and lambda expressions is that arrow functions are able to expand into full-blown functions with multiple statements while lambda expressions are limited to a single expression that is returned. Thus, when using
map(),
filter(), or
reduce() if you need to perform multiple operations on each item, define your function first then include it.
def inefficientSquare(number): result = number * number return resultmap(inefficientSquare, my_list)
Replacing For Loops
All right, on to the good stuff. Here are three examples of common for loops that will be replaced by map, filter, and reduce. Our programming prompt: Calculate the sum of the squared odd numbers in a list.
First, the example with basic for loops. Note: This is purely for demonstration and could be improved even without map/filter/reduce.
numbers = [1,2,3,4,5,6] odd_numbers = [] squared_odd_numbers = [] total = 0# filter for odd numbers for number in numbers: if number % 2 == 1: odd_numbers.append(number)# square all odd numbers for number in odd_numbers: squared_odd_numbers.append(number * number)# calculate total for number in squared_odd_numbers: total += number# calculate average
Let’s convert each step to one of the functions:
from functools import reducenumbers = [1,2,3,4,5,6]odd_numbers = filter(lambda n: n % 2 == 1, numbers)squared_odd_numbers = map(lambda n: n * n, odd_numbers)total = reduce(lambda acc, n: acc + n, squared_odd_numbers)
There are a few important points of syntax to highlight.
map()and
filter()are natively available. However,
reduce()must be imported from the
functoolslibrary in Python 3+.
- The lambda expression is the first argument in all three functions while the iterable is the second argument
- The lambda expression for
reduce()requires two arguments: the accumulator (the value that is passed to each element) and the individual element itself. | https://learningactors.com/how-to-replace-your-python-for-loops-with-map-filter-and-reduce/ | CC-MAIN-2021-43 | refinedweb | 681 | 52.29 |
05 November 2009 21:14 [Source: ICIS news]
?xml:namespace>
NACD members showed a 16.7% increase in sales in 2008 over the year before, according to the NACD’s Company Productivity Report (CPR), released Thursday. Adjusted for inflation, the increase was 14.5%.
NACD disclosed only the percentage change and not sales figures.
Companies also showed an increase on return on investment (ROI), said NACD.
Firms with 75.0% or more of sales from bulk or repackaged liquids showed a 15.2% increase in ROI, and companies with 75.0% or more of sales from factory-packaged products (FPP), either liquid or dry, increased ROI by 34.2%. Distributors providing a product mix balanced between the two had an ROI increase of 32.4%.
On the other hand, the NACD pointed out that growth by actual tonnage was flat or negative: -1.6% for liquids and -4.0% for FPP, with balanced products growing by less than 0.1%.
NACD president Chris Jahn said the ROI increase while fewer tonnes of chemicals were being sold “indicates a strong management culture, backed up by a commitment to the Responsible Distribution Process," the association's continuous improvement program for environment, health, safety, and | http://www.icis.com/Articles/2009/11/05/9261348/chemical-distributors-sales-up-in-2008-despite-slow-growth.html | CC-MAIN-2014-42 | refinedweb | 202 | 67.25 |
Simplify Your If Statements That Return Booleans2020-01-17
Here’s a hint I have found myself repeating in code review. I learnt this from my university lecturer Tony Field, who probably repeated it in every lecture! He was teaching us Haskell, but it applies to Python, and most other programming languages.
Take a look at this code:
def is_frazzable(widget): if widget.frobnications >= 12: return True else: return False
While clear and correct, it’s longer than it needs to be. The function body can be simplified - down to one line!
if takes a boolean expression - a Python
bool.
Here the expression is
widget.frobnications >= 12.
Our code then returns a
bool:
True if the expression is
True, and
False if the expression is
False.
We can remove this redundant redundancy by returning the expression instead:
def is_frazzable(widget): return (widget.frobnications >= 12)
(The brackets are not necessary in Python, but I like keeping them for clarity.)
In general, any expression of the form:
if x: return True else: return False
…can be simplified to:
return bool(x)
The wrapping call to
bool is unnecessary if the expression already returns a
bool.
This at least all comparison and boolean operators (
==,
in,
and, etc.).
Assignments
If you’re not returning but instead assigning a new variable:
if widget.frobnications >= 12: is_frazzable = True else: is_frazzable = False
…this can also be simplified to:
is_frazzable = (widget.frobnications >= 12)
In general, that means code looking like:
if x: y = True else: y = False
…can be simplified to:
y = x
One Line Format
Python also has the single line
if format, for example:
is_frazzable = True if widget.frobnications >= 12 else False
…this can be simplified as above:
is_frazzable = (widget.frobnications >= 12)
Negated
If you’re returning the negation of an expression (reversed
True /
False):
if widget.frobnications >= 12: return False else: return True
…this can be simplified using
not:
return not (widget.frobnications >= 12)
You might be able to simplify further by swapping to the opposite operator(s) and removing the
not.
For example here
>= can be swapped to
<:
return (widget.frobnications < 12)
Single Exit
If you’re also doing something on one path only, you can simplify with this pattern too. For example, if we wanted log a message when encountering unfrazzable widgets:
def is_frazzable(widget): if widget.frobnications >= 12: return True else: logger.warning("Unfrazzable widget found, ID %s", widget.id) return False
We can separate it by storing the boolean result in a variable and returning it after logging:
def is_frazzable(widget): frazzable = (widget.frobnications >= 12) if not frazzable: logger.warning("Unfrazzable widget found, ID %s", widget.id) return frazzable
This is one line shorter, and also has the advantage of a single
return at the end of the function.
def is_frazzable(widget): if not (frazzable := widget.frobnications >= 12): logger.warning("Unfrobnicated widget found, ID %s", widget.id) return frazzable
Fin
Hope this helps you write clearer code! If I sent you this article in code review, thanks for taking the time to read.
—Adam
Working on a Django project? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.
Related posts:
- Limit Your Try Clauses in Python
- How I Import Python's datetime Module
- Tuples versus Lists in Python
Tags: python | https://adamj.eu/tech/2020/01/17/simplify-your-ifs-that-return-booleans/ | CC-MAIN-2021-04 | refinedweb | 563 | 57.47 |
omnijson 0.1.2
Wraps the best JSON installed, falling back on an internal simplejson.
The
>>> import omnijson as json # \o/
Features
- Loads whichever is the fastest JSON module installed
- Falls back on built in pure-python simplejson, just in case.
- Proper API (loads(), dumps())
- Verndorizable
- Supports Python 2.5-3.2 out of the box
Usage
Load the best JSON available:
import omnijson as json
Dump some objects:
>>> json.loads('{"yo": "dawg"}') {'yo': 'dawg'}
Load some objects:
>>> json.dumps({'yo': 'dawg'}) '{"yo": "dawg"}'
Check JSON Engine:
>>> json.engine 'ujson'
Install
Installing OmniJSON is easy:
$ pip install omnijson
Of, if you must:
$ easy_install omnijson
But, you really shouldn't do that.
License
The MIT License:
Copyright (c) 2011 Kenneth Reitz: Kenneth Reitz
- License: MIT
- Package Index Owner: kennethreitz
- DOAP record: omnijson-0.1.2.xml | http://pypi.python.org/pypi/omnijson/0.1.2 | crawl-003 | refinedweb | 135 | 56.35 |
understanding accelerometer wake example
Hi to everyone,
I have one Lopy4 and one pytrack ex. board (version 1.1)
I'm trying to run the example of the site:
but I really dont understand how it works.
My purpose is to get the type of the interrupt (time or accelerometer) and to send some data via LoraWan.
For now I just want to test this example (No Lorawan).
I'm using visual studio code IDE and the operation I do is simply :
- click "upload" button
- click the "run" button
The problem is : what should I expect from this script in the terminal you see attached?
It seems the code is running ! am right?
but if I shake the board nothing happens.
Please advice on what I'm doing wrong!
Thanks
Nico
@NicolaC The
PORTCconfiguration will be changed during the
go_to_sleepcall. You should just add an argument
falseto that call to disable the GPS (the argument is optional and defaults to
true).
Hi guys,
I have modified the code by defining a new method in the pycropoc.py file:
def gps_state(self, gps=True): # enable or disable back-up power to the GPS receiver if gps: self.set_bits_in_memory(PORTC_ADDR, 1 << 7) else: self.mask_bits_in_memory(PORTC_ADDR, ~(1 << 7)
and I shutdown the GPS before to go into sleep while I switch on it when i wake up.
At the moment I have these issues:
even with this new function the power consumption does not change
When I wake up from cyclic sleep the LED is RED ("shock" event ) and not yellow (only sometimes is yellow) as I expected. However The shock waking event seems to work (always red as expected)
Could you please advice on what I'm doing worng for both issues ?
Awaitng your reply
Thanks
Nicola
Hi Andreas,
I'm doing some test to understand if it works but I would like to shutdown GPS before going to sleep and turn on it when it wakes up.
I'm using :
py.set_bits_in_memory(PORTC_ADDR, 1 << 7)
to shut down and
py.set_bits_in_memory(PORTC_ADDR, 1 << 7)
for turning on. But how can I define PORTC_ADDR?
I have an error because its not defined
Could you help me ?
Thanks
Nicola
str(number) == 1
will always yield
Falseas any string will never equal a number. You should probably omit the conversion to String by
str().
With kind regards,
Andreas.
Hi @jcaron,
I have make steps forward in order to send LoraWan packet on GPS event but I cant discriminate the accelerometer wake event from boot one. this is what i did:
1)configured one Fipy as nanogateway (properly connected to TTN)
2)flashed the following fw on the end device :
the
if (str(py.get_wake_reason())==1)
doesnt seem to work since the led is always yellow.
Any Ideas?
These is my code:
import machine import math import network import os import time import utime import gc import pycom from machine import RTC from machine import SD from L76GNSS import L76GNSS from pytrack import Pytrack from LIS2HH12 import LIS2HH12 from pytrack import Pytrack from network import LoRa import socket import ubinascii import binascii import struct time.sleep(2) gc.enable() py = Pytrack() l76 = L76GNSS(py, timeout=30) #lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868,device_class=LoRa.CLASS_A) #lora.nvram_restore() def loraSend (msg): # Initialize LoRa in LORAWAN mode. # Please pick the region that matches where you are using the device: # Asia = LoRa.AS923 # Australia = LoRa.AU915 # Europe = LoRa.EU868 # United States = LoRa.US915 print("dentro:sto mandando....."+msg) lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) # create an ABP authentication params dev_addr = struct.unpack(">l", binascii.unhexlify('xxxxxxx'))[0] nwk_swkey = binascii.unhexlify('xxxxxxxxxxxxxx') app_swkey = binascii.unhexlify('xxxxxxxxxxxxxxxxxxxxxx') # join a network using ABP (Activation By Personalization) lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey)) print("join finito") # print("scoppio?") #s.send(bytes(msg)) s.send(msg.encode('utf-8')) print("non scoppio") # make the socket non-blocking # (because if there's no data received it will block forever...) s.setblocking(False) print("fine") def returnGps (): lat=None lng=None gpsResult=None timer=30 while(timer!=0 and ((lat==None)or(lng==None))): print("getting coordinate") time.sleep(0.9) timer=timer-1 gpsResult = l76.coordinates() lat=gpsResult[0] lng=gpsResult[1] print ("LAT is: "+str(lat)+"\r\n") print ("LONG is: "+str(lng)+"\r\n") if (lat!=None and lng!=None): print ("found coordinate") break return gpsResult if (str(py.get_wake_reason())==1): pycom.heartbeat(False) pycom.rgbled(0xFF0000) # red time.sleep(5) pycom.heartbeat(False) c=returnGps() print ("prparing data") strToSend="shake\LAT:"+str(c[0])+"\LONG:"+str(c[1]) loraSend(strToSend) print("sending lora data") print ("LAT is: "+str(c[0])+"\r\n") else: pycom.heartbeat(False) pycom.rgbled(0x7f7f00) # yellow time.sleep(5) pycom.heartbeat(False) c=returnGps() print ("prparing data") strToSend="Alive\LAT:"+str(c[0])+"\LONG:"+str(c[1]) print("sending lora data") loraSend(strToSend) print ("LAT is: "+str(c[0])+"\r(60) py.go_to_sleep() ################################################ # while True: # time.sleep_ms(300) # print("xxxxxxxxxxxxxxxxxxxxxrikkion") # c=returnGps() # print ("LAT is: "+str(c[0])+"\r\n")
Any suggestion non what I 'm doing wrong?
Thanks
Nicola
@andreas thanks,
I have the file to "main.py" and it seems to work but:
- at the boot when no accelermoter event occurs it gives me the yellow led (its right)
- then when I shake it , it seems to give me the green led but it doesnt take 2 sec. as designed in the code and it soon
switches to the yellow again .
Do you know why?
Thanks
@jcaron said in understanding accelerometer wake example:
Hi jcaron,
thanks for reply,
I have put a comment to the print statements at the begining and I have put the following code:
#print("Wakeup reason: " + str(py.get_wake_reason())) #print("Approximate sleep remaining: " + str(py.get_sleep_remaining()) + " sec") pycom.heartbeat(False) if (str(py.get_wake_reason())==1): pycom.rgbled(0x007f00) # green time.sleep(2) pycom.heartbeat(False) else: pycom.rgbled(0x7f7f00) # yellow time.sleep(2) pycom.heartbeat(False)
but it doesnt seem to work .
Do I have to close the IDE ?
Do I have to power from external power supply?
I really dont understand the flow of the code.
Please help
Thanks
Dear Nicola,
the code you are showing is probably not even starting. Please try to rename your file from
Main.pyto
main.pyand try again.
With kind regards,
Andreas.
@NicolaC One problem with that code is that when it goes to sleep it will disconnect USB, and when it wakes up it takes a little while for USB to come back up, but it will go back to sleep before it's up.
You should probably change the LED color on boot, based on the wake reason, if you want to see what happens. | https://forum.pycom.io/topic/5758/understanding-accelerometer-wake-example/1?lang=en-US | CC-MAIN-2021-17 | refinedweb | 1,121 | 59.3 |
Firmware update with atom plugin of PyMakr?
Hi,
I was advised to not use PyMakr and instead using atom PyMakr plugin. I am able to basically se that.
Now I found that I need to update my LoPy but I don't know if that is possible with the atom version of PyMakr.
Can I update via telnet or do I need a board with an USB (I have one)?
Thank you,
Lothar
@robert-hh Thanks for that specific detail. It is especially interesting to have a mode for both. I was not aware of that to be possible. Currently I got my LoPy connected (to my other wlan). It was a failure to get an IP address in the first wlan. I may have some issues with that wlan.
Now I have setup a dns name in my lan and can reach the gateway by it's name. The next step is to get it registering with TTN :-)
@lollisoft You can always in your code set the mode(AP or STA, or both) you want. Look into the network.WLAN module. the method wlan.isconnected() tells you, whether your device is connected to an Access point.
Look also at the WLAN section in the tutorial
And, like @RobTuDelft said, until WLAN works as wanted, you can always use the USB connection. But better use the most recent version of the firmware. You can tell the version with
import uos uos.uname()
The actual version is 1.6.12b1
I found a way to reset with a save boot. Then it starts again the ap mode and not my code.
Is there any way to try the wlan connect and if it fails, fall back to ap mode, so that I do not always have to save boot?
I think the connect to wlan function in tne nano gateway code is using an endless loop to connect to the configured wlan.
If the fallback idea is not possible (what I do not believe), then I assume the best would be to resort to USB serial mode with atom and pymakr, to see the error messages, because otherwise, I keep disconnecting the telnet session when I try to connect to wlan - what is naturally the case.
- RobTuDelft last edited by
@lollisoft If you don't have access over Wi-Fi it's easiest to just plug in it with usb.
You can format the flash memory (sd or internal), check out the documentation.
Hi,
I have found that tool and updated my board. Actually I have put it back to my breadboard, but it no longer shows up with an active wlan access point. But it blinks as of before.
I had some software on it to run a nano gateway. May it be the case, that this is actually running and the access point is off?
The wifi password is an old WEP based password that I have configured in binary form, as of that way I have to put it in when I connect to my mac for example. Is that an issue?
How to reset the flash contents? Is it now only possible to reset that content over USB or can I hard reset it without going back with the firmware version?
@lollisoft For firmware upadtes you need the Pycom updating tool, which is available for the usual OSes. See, firmware updates. The update is performed using the Serial/USB interface. That works best with the expansion board. Please follow the instructions carefully. | https://forum.pycom.io/topic/1068/firmware-update-with-atom-plugin-of-pymakr | CC-MAIN-2019-30 | refinedweb | 585 | 82.65 |
On 22.02.2021 11:20, Michał Górny wrote:
On Sun, 2021-02-21 at 13:04 -0800, Gregory P. Smith wrote:
The main thing from a project maintenance perspective is for platforms to not become a burden to other code maintainers. PRs need to be reviewed. Every #if/#endif in code is a cognitive burden. So being a minor platform can come with unexpected breakages that need fixing due to other changes made in the codebase that did not pay attention to the platform. As we cannot expect everyone working on code to care about anything beyond the tier-1 fully supported platforms, buildbot or not..
They themselves have limited time to work on it. So it's entirely fine for things to break occasionally, and they provide fixes as their time permits. They don't ask others to maintain their code. There's no real maintenance burden involved.
But there is. As was pointed to above, the extra legacy code makes making _any_ changes in the corresponding part of the file more difficult -- because one has to think how to combine the changes with that code. E.g.: at which side of that code to place the changes; if it's a part of a block statement, where in the block statement to place the changes; if I want to change the program structure, how to incorporate that code into the new structure -- all made much more difficult because I cannot be sure what changes would and wouldn't break the "legacy" code. So, by your logic, it would be "blocking" any change to that file and will have to be removed anyway the first time we change that file. Now, if that's the case -- why should we spent time and effort tracking which files were "cleansed" and which weren't (which we'll have to do because such cleansing is an unrelated change in a PR so a PR's author should know whether they need to look out to do any "cleansing" as well as making the change that does what they want) if we can cleanse them all at once and be done with it?
In fact, this whole thread feels like removing 80%-complete translations from a program because they 'burden developers' and confuse users. Even if the translations are not actively updated and degenerates with strings changing, some users find them helpful. | https://mail.python.org/archives/list/python-dev@python.org/message/AXMROBO7DYGOR4R3HNARFUC3PVKAWFQA/ | CC-MAIN-2021-17 | refinedweb | 400 | 74.12 |
Learn how to use the Microsoft Visual Studio Tools for Applications (VSTA) development environment to write managed-code business logic against the Office InfoPath 2007 object model. (7 printed pages)
February 2007
Applies to: Microsoft Office InfoPath 2007
Contents
Lab Objectives
Lab Setup and Requirements
Scenario
Exercises
Conclusion
Additional Resources
After completing this lab, you will know how to do the following:
Use the Microsoft Visual Studio Tools for Applications (VSTA) development environment that is integrated into Microsoft Office InfoPath 2007.
Access the Microsoft .NET Framework classes from form template business logic.
Use the InfoPath object model from form template business logic.
To complete this lab, you must have Office InfoPath 2007 installed with VSTA.
Before you can install VSTA, you must have the Microsoft .NET Framework 2.0 and Microsoft Core XML Services (MSXML) 6.0 installed on your computer. The .NET Framework 2.0 is available as an optional software update on Windows Update. MSXML6.0 is available for download from the MSDN Web site (see Microsoft Core XML Services 6.0).
The VSTA development environment is not installed by default when you choose Typical to install InfoPath. To install VSTA, you must select either Customize when you are IT department at Contoso is designing an order form. They plan to use the functionality provided by the Microsoft .NET Framework classes in a form, while continuing to use the built-in form-specific features (data validation, conditional formatting) of InfoPath 2007.
Office InfoPath 2007 provides a new object model for writing managed business logic. In this exercise, you will learn how to use code to display a simple alert dialog box.
Start InfoPath.
On the File menu, click Design a Form Template.
In the Design a Form Template dialog box, under Based on, click Blank, and then click OK.
This creates a new blank form template that is compatible with InfoPath.
On the File menu, click Save, and then save the form as OM Lab.
Click OK on the message about using the Publishing Wizard to publish the form when you are finished designing it.
On the Tools menu, click Form Options.
In the Category list, click Programming.
Under Programming Language, change the value in the Form template code language drop-down list from Visual Basic to C#.
Click OK.
On the Design Tasks pane, click Controls.
Click the Button control to insert a button into your form template.
Double-click the button to open the Button Properties dialog box.
Change the Label field to Alert.
Change the ID field to AlertID.
Click Edit Form Code.
This opens the VSTA development environment window and adds an event handler for the Clicked event of the button to the FormCode.cs file.
In the event handler, add the following line of code.
System.Windows.Forms.MessageBox.Show("Hello, World");
You should now see the following screen.
You have completed your first InfoPath form template with managed-code business logic. Next, you can build and preview this form template.
In VSTA, on the Build menu, click Build OM Lab. In the status bar, you will see an indication that the build has successfully finished.
Change focus back to the InfoPath form template designer, and then click Preview.
The Alert Button that you created appears in the Preview, as shown in Figure 3.
Click Alert in the previewed form to display the MessageBox that you added as shown in Figure 4.
Now you will write managed-code business logic by using the Office InfoPath 2007 object model implemented in the Microsoft.Office.InfoPath namespace. You will design an order form with a billing address and a shipping address. You will write code to insert the shipping address whenever the user indicates that it differs from the billing address.
This creates a new, blank form template that is compatible with InfoPath.
On the File menu, click Save, and save the form as OM Lab- ExecuteAction.
On the task pane, select Controls.
Click the Section control.
Drag a Text Box control inside the Section control.
Drag a Check Box control and place it below the Section control.
Drag an Optional Section control and place it below the Check Box control.
Drag a Text Box control inside the Optional Section control, as shown in Figure 5.
Right-click the Check Box control, point to Programming, and then click Changed Event.
Insert the following code in the field2_Changed event handler.
field2_Changed");
}
When the check box is selected, this code inserts the optional section by calling ExecuteAction. When the check box is cleared, the code uses ExecuteAction to remove the optional section.
To determine the values to use for the xmlToEdit parameter of the ExecuteAction method and for the viewContext parameter of the SelectNodes method, display the Advanced tab of the Section Properties dialog box of the Optional Section control in InfoPath design mode. If you followed steps 2 through 6 in exact order, the values will be those used in the previous code example. Otherwise, they might differ slightly.
The advanced tab will look like Figure 6.
In the previous code example, replace group2_2 with the value displayed for XmlToEdit for xOptional. Also replace CTRL4 with the value displayed for ViewContext.
group2_2
CTRL4
To determine the value to use for the xpath parameter of the SelectSingleNode method, complete the XPath to the Optional Section control with the name of that control, for example, /my:myFields/my:group2.
/my:myFields/my:group2.
You can see the name of the Optional Section control by selecting it in InfoPath design mode, as shown in Figure 5.
Your form code should now look like the following example (or vary slightly based on viewContext and xmllToEdit values).)
{");
}
}
}
}
In VSTA, on the Build menu, click Build OM Lab - ExecuteAction.
In the status bar, you will see an indication that the build has successfully completed.
Change focus back to the InfoPath designer.
Click Preview, and you will see the screen shown in Figure 7.
Select the check box, and the new section will be inserted. Clear the check box and the section will be removed.
After completing this lab, you should have a basic understanding of how to work with the InfoPath 2007 object model and VSTA. In Lab 9: Designing InfoPath 2007 Forms for Mobile Web Browsers, you can find out how to create a form template that can be filled out using a Web browser on a mobile device.
For more information about developing with InfoPath, see the following resources:
Microsoft Office Developer Center: InfoPath Developer Portal
InfoPath Home page on Office Online
What's New for Developers in InfoPath 2007 | http://msdn.microsoft.com/en-us/library/bb251747.aspx | crawl-002 | refinedweb | 1,100 | 65.62 |
Question 6 :
Which files will get closed through the fclose() in the following program?
#include < stdio.h > int main() { FILE *fs, *ft, *fp; fp = fopen("A.C", "r"); fs = fopen("B.C", "r"); ft = fopen("C.C", "r"); fclose(fp, fs, ft); return 0; }
Extra parameter in call to fclose().
Question 7 :
On executing the below program what will be the contents of 'target.txt' file if the source file contains a line "To err is human"?
#include < stdio.h >; }
The file source.txt is opened in read mode and target.txt is opened in write mode. The file source.txt contains "To err is human".
Inside the while loop,
ch=getc(fs); The first character('T') of the source.txt is stored in variable ch and it's checked for EOF.
if(ch==EOF) If EOF(End of file) is true, the loop breaks and program execution stops.
If not EOF encountered, fseek(fs, 4L, SEEK_CUR); the file pointer advances 4 character from the current position. Hence the file pointer is in 5th character of file source.txt.
fputc(ch, ft); It writes the character 'T' stored in variable ch to target.txt.
The while loop runs three times and it write the character 1st and 5th and 11th characters ("Trh") in the target.txt file.
Question 8 :
To scan a and b given below, which of the following scanf() statement will you use?
#include < stdio.h > float a; double b;
To scan a float value, %f is used as format specifier.
To scan a double value, %lf is used as format specifier.
Therefore, the answer is scanf("%f %lf", &a, &b);
Question 9 :
Out of fgets() and gets() which function is safe to use?
Because, In fgets() we can specify the size of the buffer into which the string supplied will be stored.
Question 10 :
Consider the following program and what will be content of t?
#include < stdio.h > int main() { FILE *fp; int t; fp = fopen("DUMMY.C", "w"); t = fileno(fp); printf("%d\n", t); return 0; }. | http://www.indiaparinam.com/c-programming-language-question-answer-input-output/page1 | CC-MAIN-2019-22 | refinedweb | 341 | 85.28 |
This document provides a detailed reference on the data feed for version 2.4 of the Core Reporting API.
Overview
Reports in the Analytics user interface are generally organized into these categories:
- Users
- Traffic Sources
- Content
- Internal Site Search
- Goals
- Ecommerce
Each report, regardless of the section to which it belongs, consists of two primary fields—metrics, and dimensions..
Keep in mind that not all categories of data can be combined in a single request. When you request a combination of dimensions and metrics that are not allowed, you will receive an error response instead of an actual feed. This causes no harm, so feel free to experiment with combinations of metrics and dimensions that seem most useful. For a detailed list of the metrics and dimensions you can query, see the Dimensions & Metrics Reference
To understand how Analytics data is applied to the view (profile) you are requesting data for, see the background document on Accounts and Views (Profiles).
Data Feed Request
This section describes all the elements and parameters that make up a data feed request. In general, you provide the table ID corresponding to the view (profile) you want to retrieve data from, choose the combination of dimensions and metrics, and provide a date range along with other parameters in a query string.
&dimensions=ga:source,ga:medium
&metrics=ga:sessions,ga:bounces
&filters=ga:medium%3D%3Dreferral
&segment=gaid::-10 OR segment=sessions::condition::ga:medium%3D%3Dreferral
&start-date=2008-10-01
&start-index=10
&max-results=100
&prettyprint=true
Base URL
ids
ids=ga:12345
<ga:tableId>element for each entry in the account feed. This value is composed of the
ga:namespace and the view (profile) ID of the web property.
dimensions
dimensions=ga:source,ga:medium
dimensionsparameter defines the primary data keys for your Analytics report, such as
ga:browseror
ga:city. Use dimensions to segment your metrics. For example, while you can ask for the total number of pageviews to your site, it might be more interesting to ask for the number of pageviews segmented by browser. In this case, you'll see the number of pageviews from Firefox, Internet Explorer, Chrome, and so forth.
When the value of the dimension cannot be determined, Analytics uses
the special string
(not set). There are a number of situations
where the dimension value will not be set. For example, suppose you want
to query your reports for country, city,
and pageviews,
and suppose the following is true for your view (profile) data:
- Pageviews on your site came from only two identified countries
- Each of those countries had only two identifiied cities
- Some number of pageviews also came from areas that could not be mapped to either a country or a city
- Some pageviews could be mapped to a country, but not to a city within that country
The results for this request would return data as illustrated by the following example table.
When using dimensions in a feed request, be aware of the following constraints:
- You can supply a maximum of 7 dimensions for any query.
- You can not send a query comprised only of dimensions: you must combine any requested dimension with at least one metric.
- Any given dimension can be used with other dimensions or metrics, but only where Valid Combinations apply for that dimension.
For more information and the list of all dimensions, see the Dimensions section in the Dimensions and Metrics Reference.
metrics
metrics=ga:sessions,ga:bounces
ga:pageviewsrequested with
ga:countryreturns the total pageviews per country. When requesting metrics, keep in mind:
- All requests require at least one metric.
- You can supply a maximum of 10 metrics for any query.
- Not all dimensions and metrics can be used together. Consult the Valid Combinations tool to see which combinations work together.
sort
sort=-ga:sessions
Indicates the sorting order and direction for the returned data. For example,
the following parameter would first sort by
ga:browser and then
by
ga:pageviews in ascending order.
sort=ga:browser,ga:pageviews
If you do not indicate a sorting order in your query, the data is sorted by dimension from left to right in the order listed. For example, if the query looks like this:
dimensions=ga:browser,ga:country
Sorting occurs first by
ga:browser, then by
ga:country.
However, if the query uses a different order:
dimensions=ga:country,ga:browserSorting occurs first by
ga:country, then by
ga:browser.
When using the
sort parameter, keep in mind the following:
- Sort only by dimensions or metrics value that you have used in the
dimensionsor
metricsparameter. If your request sorts on a field that is not indicated in either the dimensions or metrics parameter, you will receive a request error.
- Strings are sorted in ascending alphabetical order in an en-US locale.
- Numbers are sorted in ascending numeric order.
- Dates are sorted in ascending order by date.
The sort direction can be changed from ascending to descending by using a
minus sign (
-) prefix on the requested field. For example:
filters
filters=ga:medium%3D%3Dreferral
The
filters query string parameter restricts the data returned from your request to the Analytics servers. When you use the
filters parameter, you supply a dimension or metric you want to filter, followed by the filter expression. For example, the following feed query requests
ga:pageviews and
ga:browser Java client library automatically encodes the filter operators. However, when you use the JavaScript client library, or make requests directly to the protocol, you must explicitly encode filter operators as indicated in the table below.
- Valid Combinations for more information.
Filter Syntax
A single filter uses the form:
ga:name operator expression
In this syntax:
- name — the name of the dimension or metric to filter on. For example:
ga:pageviewswill filter on the pageviews metric.
- operator — defines the type of filter match to use. Operators are specific to either dimensions or metrics.
- expression — states the values included or excluded from the results. Expressions use regular expression syntax.
Filter Operators
There are six filter operators for dimensions and six operators for metrics. The operators must be URL encoded in order to be included in URL query strings.
Tip: Use the Data Feed Query Explorer to design filters that need URL encoding, since the explorer will automatically URL encode necessary strings and spaces for you. will result in a
400 Bad Requeststatus code returned from the server.
- Case sensitivity — Regular expression matching is case-insensitive.
For more information on common regular expression matches supported by Google Analytics, see What are regular expressions in the Help Center..
start-date
start-date=2009-04-20
YYYY-MM-DD.
2005-01-01. There is no upper limit restriction for a start-date. However, setting a start-date that is too far in the future will most likely return empty results.
end-date
end-date=2009-05-20
YYYY-MM-DD.
2005-01-01. There is no upper limit restriction for an end-date. However, setting an end-date that is too far in the future might return empty results.
start-index
start-index=10
1. (Feed indexes are 1-based. That is, the first entry is entry
1, not entry
0.) Use this parameter as a pagination mechanism along with the max-results parameter for situations when
totalResultsexceeds 10,000 and you want to retrieve entries indexed at 10,001 and beyond.
max-results
max-results=100
start-indexto retrieve a subset of elements, or use it alone to restrict the number of returned elements, starting with the first. If you do not use the
max-resultsparameter in your query, your feed returns the default maximum of 1000 entries.
ga:country, so when segmenting only by country, you can't get more than 300 entries, even if you set
max-resultsto a higher value.
prettyprint
prettyprint=true
trueor
false, where the default is
false. Use this parameter for debugging if you're looking at the feed responses directly.
Data Feed Response
The data feed returns data that is entirely dependent on the fields you specify in your request using the
dimensions and
metrics parameters.
For a list of the available dimensions and metrics that you can query in the
data feed, see the Dimensions & Metrics Reference. This section describes the general structure of the data feed as returned in XML, with a description for the key elements of interest for the data feed.
- Data Feed
title—the string Google Analytics Data for View (Profile), followed by the ID of the selected view (profile)
id—the feed URL
totalResults—the total number of results for the query, regardless of the number of results in the response
startIndex—the starting index of the entries, which is 1 by default or otherwise specified by the
start-indexquery parameter
itemsPerPage—the number of items in the current request, which is a maximum of 10,000
dxp:startDate—the first date for the query as indicated in the
start-datequery parameter
dxp:endDate—the ending date for the query as indicated in the
end-datequery parameter, inclusive of the date provided
dxp:containsSampledData—boolean value indicating whether any of the entries in this response contain sampled data. See Sampling below for details.
dxp:aggregates—contains the total values of each metric matched by the query. Some queries match more values in Google Analytics than can be returned by the API in a single page. When this happens, you will have to paginate through the results. The aggregate metric values contain the sum of each metric for the un-paginated data. This is different than the sum of the metric values returned in a single page, which the API does not return.
dxp:metric—metrics representing the total values of all metrics the query matched
name—the name of the metric
value—the un-paginated value of this metric
type—the type of the value returned. Can be: currency, float, percent, time, us_currency, an unknown type, or not set
dxp:dataSource—summary information about the Analytics source of the data
dxp:tableId—The unique, namespaced view (profile) ID of the source, such as
ga:1174
dxp:tableName—The name of the view (profile) as it appears in the Analytics administrative UI
dxp:property name=ga:profileId—The view (profile) ID of the source, such as
1174
dxp:property name=ga:webPropertyId—The web property ID of the source, such as
UA-30481-1
dxp:property name=ga:accountName—The name of the account as it appears in the Analytics interface.
dxp:segment—For both default and custom advanced segments, the feed returns the name and ID associated with the segment. For dynamic segments, the feed returns the expression contained in the request.
entry—Each entry in the response contains the following elements
title—the list of dimensions in the query and the matching result for that entry
dxp:dimension—one element for each dimension in the query
name—the name of the dimension
value—the value of the dimension
dxp:metric—one element for each metric in the query
name—the name of the metric
value—the aggregate value for the query for that metric (e.g. 24 for 24 pageviews)
type—the type of the value returned. Can be: currency, float, percent, time, us_currency, an unknown type, or not set
Data Feed Error Codes
The Core Reporting API returns a
200 HTTP status code
if your request is successful. If an error or problem occurs with
your request, the Data Feed returns HTTP status codes based on
the type of error, along with a reason describing the nature of the
error.
Note: The descriptive reason returned by the API may change at any time. For that reason, your application should not use string matching on the reason, but rather rely only on the error code.
The following list shows the possible error codes and corresponding reasons.
400 Bad Request
Types of bad requests include:
- Invalid dimensions and/or metrics
- Quantity: either no metric, or too many dimensions/metrics
- Using OR on a filter where one side is a metric and the other a dimension
- Invalid filter/segment syntax
- Illegal dimension/metric combination or advanged segment
401 Unauthorized
Types of authentication issues include:
- Invalid username or password
- Invalid authorization token
403 Forbidden
Types of authorization issues include:
- Permissions: user is not authorized to access the requested view (profile)
- Using account ID (instead of view (profile) ID)
500 Internal Server Error
Do not retry.
503 Service Unavailable
Types of service issues are listed below. Be sure to check the
X-Google-Commandheader to determine whether a retry is allowed.
- Timeout
- Server error
- Service unavailable
- Insufficient quota
Sampling
Google Analytics calculates certain combinations of dimensions and metrics on the fly. To return the data in a reasonable time, Google Analytics only processes a sample of the data.
If the data you see from the Core Reporting API doesn't
match the web interface, use the
containsSampledData top-level response element
to determine if the data has been sampled.
Use the
containsSampledData top-level response element to
determine if any metric values in the response entries contain sampled
data.
See Sampling for a general description of sampling and how it is used with Google Analytics.
Handling Large Data Results
If you expect your query to return large result sets, the guidelines below will help you optimize your API query, avoid errors, and minimize quota overruns. Keep in mind that we establish a baseline level of optimization for any given API request by allowing a maximum number of dimensions (7) and metrics (10). While some queries that specify large numbers of metrics and dimensions can take longer to process than others, limiting the number of requested metrics does not generally improve query performance. Instead, you can use the following techniques for the best performance results.
Paging
Paging through results can be a useful way to break large results sets into manageable chunks. The data feed tells you how many matching rows exist, along with giving you the requested subset of rows. If there is a high ratio of total matching rows to number of rows actually returned, then the individual queries might be taking longer than necessary. If you need only a limited number of rows, such as for display purposes, setting an explicit limit is fine. However, if the purpose of your application is to process a large set of results in its entirety, then it is most efficient to request the maximum allowed rows.
Splitting the Query by Date Range
Instead of paging through the date-keyed results of one long date range, consider forming separate queries for one week—or even one day—at a time. For a very large data set, it may still be necessary to page through results, such as when a request for one day still contains more than the maximum number of result rows per query. In any case, if the number of matching rows for your query is higher than the max results rows, breaking apart the date range may improve the total time to retrieve the answer. This is true whether the queries are being sent in a single thread or in parallel.
Use Filters Intelligently
Consider whether additional filters might reduce the data while still providing the information you need. Can a dimension filter, such as a regular expression match on a page path, return the subset of the data you care about? Can value thresholds (such as ignoring matches with less than 5 sessions) filter out less interesting results? This approach can be used as a complement to any of the other suggestions mentioned earlier. With this technique, the actual time to get each result set is likely to be about the same, but fewer result pages would be retrieved, thus reducing the overall interaction time and minimizing impact on your quota allowance. | https://developers.google.com/analytics/devguides/reporting/core/v2/gdataReferenceDataFeed | CC-MAIN-2018-43 | refinedweb | 2,644 | 50.16 |
So the news is out [Mailinglist, Newsgroups]. UFacekit is proposed as a Component under Platform/Incubator project (proposal). I think this is the right move for UFacekit to gather momentum towards our first release. If you want to support this move:
- Comment on the following newsgroup post from Boris
- Add yourself/company as an interested party on the proposal page
I’m currently working on the JavaDoc and for SWT/JFace a build should be available right after we moved the sources to foundations repositories, swiched namespaces, … .
Advertisements
Cool, I hope UFace goes a long way to further improve the databinding work and stretch Eclipse technology into new and interesting places.
Great news !!
I hope you will managed to be part of the Eclipse Platorm Community !
I need to find a data binding framework on a GWT project (GWT EXT)… please help me to use yours. Uface seems to be based on the JFace databinding ! How can we use your project ? I can’t find any releases. I just can checkout the svn repo.
Their are many different framewoks dealing with GWT databinding… The best is hard to find ! Maybe the one, with the famous Angelo and Tom… 😉
The Databinding-Stuff for GWT is not in good shape yet and I didn’t had time because it really made me sad to see how MyGWT/GWT-Ext simply switched their Licenses.
The code once worked with a pre release for GWT and it is not really hard to implement Observables. So if someone has the time I could help you to get started. I’ve for now concentrated on SWT and Swing but the first release Scheduled for Q1-2009 will at least have Eclipse-Databinding and Bindings for GWT-Widgets. | https://tomsondev.bestsolution.at/2008/09/09/ufacekit-proposed-as-a-component-under-platformincubator/ | CC-MAIN-2018-39 | refinedweb | 291 | 70.73 |
View release notes for newer releases
Error messages in the Command Window no longer appear with question marks or arrows. In addition, error messages for each function now provide a link to that function's documentation.
The following images show examples of the differences in presentation:
Built-in functions:
MATLAB®® Media Foundation,
on Windows®®®® Version
10.0 is
yvals.h..
The new MathWorks®® continue to behave as they did in previous releases.
MATLAB Version 7.12 (R2011a) supports these new compilers for building MEX-files:
GNU®++®.
New desktop features and changes introduced in Version 7.11 (R2010b) are:
You can now customize the date format that the Current Folder browser and the Command History window use to display dates, such as the dates indicated here:
Previously, the date format in both of these tools was M/d/yy (for instance, 6/4/90 for June 4, 1990) and you could not change it. Now, both tools use the operating system short date format. For details, see Customizing the Column Display.
MATLAB now integrates keyboard shortcuts preferences with File Exchange. You can access File Exchange directly from the Keyboard Shortcuts Preferences panel and find:
MATLAB keyboard shortcuts available in Version 7.9 (R2009a) and earlier releases
Keyboard shortcuts sets created by other MATLAB users
For details, see Download Keyboard Shortcut Settings Files from File Exchange .
MATLAB provides a template for classes that define enumerations. Enumeration classes enable you to define a fixed set of names representing a particular type of value. Choose File > New > Enumeration. For more information, see Enumerations.
If your system displays documentation in Japanese, you can use the Language panel in the Help Preferences dialogHelp Preferences dialog to instruct the Help browser to display documentation in English instead of Japanese. You can toggle between languages with the preference panel, enabling you to revert to Japanese at any time. The option changes the language used in the Help Browser and for GUI context-sensitive help, but it does not affect the language appearing in menus or elsewhere in products.
For example, the
help command still provides
help in Japanese after you switch the Help browser to English. The Language preference
is available only when the system locale is Japanese and the Japanese
documentation is installed. If the documentation for a product is
not translated, the Help Browser displays the English documentation
for it no matter how you set the preference.
MathWorks usually provides Japanese translations of product documentation about 2 months after new versions of products first ship. When you install the new version of a product, the previous version of translated documentation is installed in most cases.
To read the most current documentation for your release, switch the Help browser to English. After the translations of the latest documentation are available, you can download and install them in your products. At that time, you can find a link to download the latest translated documentation on the Japanese documentation start page.
New features and changes introduced in Version 7.11 (R2010b) are:
Using the Current Folder browser, you can now view the files in a zip file without having to extract them. This feature enables you to:
Confirm the contents of a newly created zip file
Selectively open items from a zip file
Add or remove files from the zip file
For details, see Creating and Managing Zip File Archives or watch the Zip File Browsing video demo Zip File Browsing video demo.
Now, when you select a
JPEG,
JPG,
BMP,
WBMP,
PNG,
or
GIF image in the Current Folder browser, the
Details panel displays a thumbnail of the image and lists its width
and height in pixels. For more information, see Viewing
File Details Without Opening Files or watch the File
Preview Enhancements video demoFile
Preview Enhancements video demo.
Now, if you modify a file in the Editor, but have not yet saved the changes, the Current Folder browser indicates the file state. An asterisk (*) appears next to the name of such a file in the Current Folder browser. In addition, when you select such a file in the Current Folder browser, the detail panel reflects the modified file, not the file saved on disk. This feature is useful when you are creating zip files and want to be sure that all files included in the archive are saved and up-to-date. For details see, Viewing File Details Without Opening Files or watch the File Preview Enhancements video demo File Preview Enhancements video demo.
You can now compare any combinations of zip files, folders, and Simulink® Manifests with the Comparison Tool. Right-click files or folders in the Current Folder browser and choose Compare Selected Files/Folders, or Compare Against > Choose.
For details, see Comparing Folders and Zip Files.
The Comparison Tool now provides the following capabilities:
Select what type of comparison to run from a list of possible comparison options, e.g., text, binary or XML comparison.
Enhanced MAT-file comparisons now include size, data type and change summary.
New option to ignore whitespace changes in text comparisons.
For details, see Comparing Files and Folders.
New Desktop features and changes introduced in Version 7.11 (R2010b) are:
You now can save a file that is open in the Editor to a backup file. Select File > Save Backup, and then specify a backup file name. The file that is active in the Editor when you perform the save operation remains active. If changes to the active file prove problematic, you can use the backup file to return to a known state or to compare with the active file. This comparison can help you determine where errors exist.
For information on other save options, see Save Files.
The enhanced ability to wrap MATLAB comments includes:
Wrapping an entire block of comments by selecting File > Wrap Comments.
There is no need to select the block of comments first. For details see Wrap Comments Manually.
Specifying where you want column counting to begin.
For example, if you indent comments, you can specify that you want the maximum width of comments to be 75 columns from the start of a comment, rather than from the start of a line. To set Comment formatting preferences, select File > Preferences > Editor/Debugger > Language.
The Editor now presents variables that are not local variables in a teal blue color, by default. Also by default, when you click a function or local variable, the Editor highlights it and all other references to it in a sky blue color. As demonstrated in the Variable and Subfunction Highlighting video demo Variable and Subfunction Highlighting video demo, this feature makes it easier to:
Find unintentional reuses of a variable within a nested function
For details, see Avoid Variable and Function Scoping Problems.
Navigate through a file from function to function reference or variable to variable reference
For details, see Navigate to a Specific Location.
Search a file for a particular function or variable name
For details, see Find and Replace Functions or Variables in the Current File.
To disable or change the colors that the Editor uses for variable and function highlighting, see Use Automatic Function and Variable Highlighting.
When multiple documents are open and docked in the Editor, you can right-click the document tab, and then from the context menu choose:
Change Current Folder to folder-name
Add folder-name to Search Path or Remove folder-name from Search Path, respectively
Locate on Disk
This option locates the document in your operating system file browser. It is not available on Linux platforms.
Copy Full Path to Clipboard
You can use the File > Open as Text option to open
a file in the Editor as a text file, even if the file type is associated
with another application or tool. This feature is useful, for example,
if you import a tab-delimited data file (
.dat)
into the workspace, and then you find you want to add a data point.
For details, see Open
Existing Files.
The two-output form of
DelaunayTri/nearestNeighbor returns
the corresponding Euclidean distances between the query points and
their nearest neighbors.
The three-output form of
svd displays
significantly enhanced performance.
Sparse Column Assignment
The assignment of elements into multiple columns of a MATLAB sparse matrix displays significantly enhanced performance.
Trigonometric Functions
All degree-based trigonometric functions (
sind,
cosd,
tand,
cotd,
secd,
cscd)
and their inverses (
asind,
acosd,
atand,
acotd,
asecd,
acscd)
display significantly enhanced performance.
If you do not have an Optimization Toolbox™ license, and
you set an
optimset option
for a solver that is only available in Optimization Toolbox,
optimset errors.
Previously,
optimset would
warn, not error, and ignore the option.
Change your code to set only those options that apply to your
solver:
fminbnd,
fminsearch,
fzero,
or
lsqnonneg.
When you use
atan(1i) and
atan(-1i) you
no longer get a warning.
Remove instances of the warning ID
MATLAB:atan:singularity from
your code.
MATLAB now enables you to create arrays of
timeseries objects.
In Version 7.10 (R2010a) and before,
timeseries objects
behaved as arrays, but some array behavior was overridden.
In Version 7.11 (R2010b), all of the overridden behaviors for
the functions listed in the table that follows are removed. The behavior
of these functions on
timeseries objects is the
built-in behavior for arrays of objects. Think of a
timeseries object
as a single object that you can concatenate into an array of objects.
Do not think of each
timeseries itself as an
array.
Suppose you concatenate the following two
timeseries objects:
t1 = timeseries(ones(5,1),0:4); t2 = timeseries(zeros(5,1),5:9);
timeseriesobject,
t3, with 10 samples spanning the time range 0-9. The first 5 samples derived from
t1and the last 5 samples derived from
t2. The size of the
timeseries,
t3, was
[10 1]and its length was 10, because
t3has 10 samples.
t3 = [t1;t2] t3 = vertcat(t1,t2)
Now, the same syntax creates a 2x1 array comprising the two
timeseries objects
t1 and
t2.
Its size is
[2 1], and its length is 2 because
the array has two rows, each a single
timeseries..
Program code that compares object arrays that may contain NaNs should be examined to ensure correct behavior.
In earlier releases of MATLAB, the following statements
returned different results for objects with a base class of
logical:
isa(obj, 'logical') islogical(obj)
In MATLAB version 7.11, both of these statements return
true if
the class of
obj is derived from
logical,
and
false otherwise.
MATLAB provides support for classes that define enumerations. Enumeration classes enable you to define a fixed set of names representing a particular type of value. See Enumerations for more information.
The new
VideoWriter function allows you to
create AVI files on all platforms. As an improvement over the
avifile function,
VideoWriter can
create files larger than 2 GB. For more information, watch this video
demovideo
demo or see the
VideoWriter reference
page.
For consistency with the new
VideoWriter class,
the
mmreader class is now called
VideoReader.
A new function,
VideoReader, replaces the
mmreader function.
VideoReader and
mmreader return
identical
VideoReader objects for the same input
file.
Replace all instances of
mmreader with
VideoReader.
The two functions use identical syntax. When requesting help or
documentation for methods from the command line, or calling a static
method such as
getFileFormats, use the new
VideoReader class
name (such as
doc VideoReader/read). You do not
need to change any calls to the
read,
get,
or
set methods.
Previously, the R2010a Release Notes recommended replacing instances
of
aviinfo with
mmreader and
get,
and instances of
aviread with
mmreader and
read.
Instead, replace
aviinfo with
VideoReader and
get,
and replace
aviread with
VideoReader and
read.
The MATLAB interface to the grid functions in the HDF-EOS
C library,
hdfgd, now includes three new syntaxes.
These syntaxes convert grid coordinates to longitude and latitude
values.
ij2ll
ll2ij
rs2ll
To view the help for these functions, use the
help command
at the MATLAB prompt, as in the following example:
help hdfgd
The MATLAB interfaces to the HDF5 C library now include the following new functions.
H5A.open_by_idx
H5A.open_by_name
H5D.get_access_plist
H5I.is_valid
H5L.copy
H5L.get_name_by_idx
H5P.set_chunk_cache
H5P.get_chunk_cache
H5P.set_copy_object
H5P.get_copy_object
To view the help for these functions, use the
help command
at the MATLAB prompt, as in the following example:
help H5P.get_copy_object
The MATLAB interface to the netCDF C library now includes the following new functions.
netcdf.inqFormat
netcdf.inqUnlimDims
netcdf.defGrp
netcdf.inqNcid
netcdf.inqGrps
netcdf.inqVarIDs
netcdf.inqDimIDs
netcdf.inqGrpName
netcdf.inqGrpNameFull
netcdf.inqGrpParent
netcdf.defVarChunking
netcdf.defVarDeflate
netcdf.defVarFill
netcdf.defVarFletcher32
netcdf.inqVarChunking
netcdf.inqVarDeflate
netcdf.inqVarFill
netcdf.inqVarFletcher32
To view the help for these functions, use the
help command
at the MATLAB prompt, as in the following example:
help netcdf.inqVarFletcher32
The following table lists upgrades to scientific file format libraries used by MATLAB.
The MATLAB command line help for the HDF5, netCDF, and CDF low-level functions now includes hundreds of new examples.
You can now use the
imread and
imwrite functions
with n-channel J2C JPEG 2000 files.
J2C files are raw JPEG2000 codestreams that usually have the
file extension
.j2c or
.j2k.
J2C files don't contain color space, color palette, capture resolution,
display resolution and vender specific information.
In previous releases, if you use
imread to
read a 4-channel J2C file, you receive a warning that some channels
may be ignored and
imread returns a 3-channel image.
Now,
imread returns a 4-channel image and does
not issue a warning.
If you try to write a 4-channel J2C file in previous releases,
imwrite issues
an error. In this release,
imwrite creates the
4-channel J2C file.
The R2010a Release Notes originally stated that
csvread and
csvwrite would
be removed in a future release. As of R2010b, there are no plans
to remove these functions.
In previous releases, calls to
sprintf or
fprintf that
printed strings using the
%s qualifier prematurely
terminated strings that contained null characters. For example, this
code
sprintf('%s', ['foo' 0 'bar'])
returned
ans = foo
The same code now returns
ans = foo bar
If you do not want to print the entire contents of strings that
contain null characters, test the string for these characters (for
example, using the
isstrprop function).
If you save an object having a property value equal to the property's
default value, and then that property is removed from the class definition, MATLAB did
not detect the fact that the property was missing. In this case, MATLAB did
not build a
struct to pass to
loadobj. MATLAB now
returns a
struct in this case.
If you rely on the following situation not returning
a
struct to
loadobj, you need
to update your code:
You saved an object using the
save command
This object had a property that was set to the default value defined by the class at the time of saving
he property set to its default value at save time is subsequently removed from the class definition
You load the property and expect the load operation
to return an object (it should return a
struct because
the class definition has changed in a way the load cannot create the
object).
Your
loadobj method is not prepared
to use the returned
struct to create an object
You must implement a
loadobj method to
recreate the object using the current class definition.
See Saving and Loading Objects for more information.
The
–dmfile
printdmfile function now issue a
deprecation warning. Both option and function will be removed in a
subsequent release. The
–dmfile option and
the
printdmfile function were used by GUIDE.
Remove any use of
print –dmfile or
printdmfile from
your code.
The
saveas function now issues a deprecation
warning if you use the
'mmat' format option. This
option will be removed in a subsequent release. This option was used
with GUIDE.
Remove any use of the
mmat option with
saveas from
your code.
The
uitabgroup and
uitab GUI
components are undocumented features that provide tabbed panels to
GUIs that you create programmatically. The current method of calling
these functions and some of their properties will change in a future
release. MathWorks has never supported their use.
However, if your MATLAB code includes these functions, read the
following information:
You should update any code that you maintain which uses the
undocumented
uitabgroup and
uitab functions
to conform to the new standards, as described in the uitab
and uitabgroup Migration Document. Existing code for these
functions is unlikely to work in R2010b going forward.
MATLAB Version 7.11 (R2010b) supports these new compilers for building MEX-files:
Microsoft Visual Studio 2010 (10.0) Professional
Microsoft Visual Studio 2010 (10.0) Express
GNU gcc Version 4.3.x
Support for the following compilers will be discontinued in a future release, at which time new versions will be supported. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
Intel Visual Fortran Version 10.1
Microsoft Visual Studio 2005 SP1
MATLAB no longer supports the following compilers:
Intel C++ Version 9.1
GNU gcc Version 4.2.3
Apple Xcode 3.1 (gcc / g++ Version 4.0.1)
GNU gfortran Version 4.2.2
To ensure continued support for building your MEX-files, consider upgrading to another supported compiler. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
In the next release of MATLAB, the
mex command
will change to use the large-array-handling API by default. This means
the
-largeArrayDims option will become the default.
You do not need to make changes to build and run MEX-files with MATLAB Version 7.11 (R2010, see Upgrading
MEX-Files to Use 64-Bit API.
The
-argcheck option was a strategy for identifying
memory corruption caused by a MEX-file. When you understand the likely
causes of memory corruption, you can take preventative measures in
your code or use your debugger to identify the source of errors.
If a binary MEX-file causes a segmentation violation or assertion, it means the MEX-file attempted to access protected, read-only, or unallocated memory.
These types of programming errors are sometimes difficult to track down. Segmentation violations do not always occur at the same point as the logical errors that cause them. If a program writes data to an unintended section of memory, an error might not occur until the program reads and interprets the corrupted data. Consequently, a segmentation violation can occur after the MEX-file finishes executing.
One cause of memory corruption is to pass a null pointer to a function. To check for this condition, add code in your MEX-file to check for invalid arguments to MEX Library and MX Matrix Library API functions.
To troubleshoot problems of this nature, run MATLAB within a debugging environment. For more information, see Debugging C/C++ Language MEX-Files or Debugging Fortran Source MEX-Files.
MATLAB supports:
Using .NET Delegates in MATLAB.
Accessing Microsoft Office Applications with .NET.
Using
System.Nullable, described
in How
MATLAB Handles System.Nullable.
Calling constructors or
NET.invokeGenericMethod with
ref or
out type
arguments.
Calling methods with default arguments (
System.Reflection.Missing.Value is
supported.)
Support for the following COM data type has been added. See Handling COM Data in MATLAB Software for a description of supported data types.
VT_I8 —
signed
int64
VT_UI8 —
unsigned
int64
Unsigned integer
For an overview of the major new features in the MATLAB Desktop Tools and Development Environment area, watch this video demo video demo.
On UNIX® systems, MATLAB no longer uses the
AUTOMOUNT_MAP environment
variable, the path prefix map for automounting. Previously, MATLAB set
the value of the variable in
.matlab7.rc, but you
could override this setting using the
AUTOMOUNT_MAP environment
variable.
New Desktop features and changes introduced in Version 7.10 (R2010a) are:
Keyboard shortcuts now provide the following:
You can now list all of the keyboard shortcuts for a given set in a text editor. For details, see List All Keyboard Shortcuts in a Set.
You can now remove keyboard shortcut sets that you created or imported. For details, see Delete a Set of Keyboard Shortcuts.
You can now compare one set of keyboard shortcuts to another. This enables you, for example, to see what is different between the current Windows default keyboard shortcuts and those that were the defaults in MATLAB Version 7.8 (R2009a) and earlier. For details, see Compare Sets of Keyboard Shortcuts.
The M-Lint Preferences is now renamed
the Code Analyzer Preference. Therefore, to set
preferences for analyzing MATLAB code, select File > Preferences > Code Analyzer. Similarly,
the M-Lint Report is now renamed the Code Analyzer Report. To access
this report, click the Actions button
in the Current Folder
browser, and then select Reports > Code Analyzer Report. The
names of the
mlint and
mlintrpt functions
are unchanged.
A new preference setting allows you to adjust the amount of
memory that MATLAB allocates for storing Java objects.
Insufficient memory for these objects results in
OutOfMemory errors.
For more information, see Java
Heap Memory Preferences.
Technical
Solution 1-18I2C specifies a procedure for creating a text
file named
java.opts to set the Java heap
size. Do not use both the new MATLAB preference and a
java.opts file
to adjust the heap size.
For a demonstration of previous enhancements to the Help browser, watch the Help Browser EnhancementsHelp Browser Enhancements video.
The MATLAB documentation now includes more details about how to display your own HTML help and demos. In particular, the documentation clarifies procedures for setting up files and folders and provides three new XML file templates that you can inspect, copy, and modify.
The documentation also adds a new complete working example,
called the Upslope Area Toolbox. Documentation for the toolbox includes
a getting started guide, user guide, function reference pages, and
release notes. The documentation set is generated entirely from MATLAB script
files (also provided), using the
publish command.
The example folder includes all program files for the toolbox. However,
certain routines require Image Processing Toolbox for full functionality.
You can also find the Upslope Area Toolbox on the MATLAB Central File Exchange. For more information about techniques and algorithms the toolbox uses, see the set of articles about it on this MATLAB Central blog:.
Find the updated documentation in Create Help and Demos. For details, XML templates, and examples, see these subsections:
Add Documentation to the Help Browser
Add Demos to the Help Browser
You can view the Upslope Toolbox documentation example in the Help browser now by clicking hereclicking here, which places its folder on the search path.
The Help Browser now provides suggestions for search terms as you type in the search field. These hints save you time and can suggest words and phrases you might not have thought of but that can be useful in making a search. The hints display as a drop-down menu that changes its contents as you type. The following illustration shows the appearance of the menu.
The Help browser can now recall searches you have made across MATLAB sessions. Your search history and search hints display as separate lists in a drop-down pane as you type in the search field. Select Show Search History from the pop-up menu to the right of the search field, or press the down arrow key in the search field when it is empty. The following illustration shows search history and search hints as they appear when you enter search terms.
You can now choose not to see the one-line descriptions of search results called previews. To toggle all previews off, right-click in the Search Results pane of the Help Navigator and choose Hide Previews. The search results listing is smaller so you can scan it quickly when you hide previews. To see previews again, right-click in the Search Results pane, and choose Show Previews.
This release obsoletes the
docopt function,
which specified which system Web browser to use on UNIX platforms.
This function has been removed. You can instead specify a default
system browser in your preferences. For more information, see New System Browser Preference Instead of docopt.m for MATLAB on UNIX Platforms.
If you call
doctopt in your startup file
or some other program file, remove the call to avoid receiving an
error.
Effective this release, the capability to create and expand,
and archive
.zip files has been added to the Current
Folder browser. Select files and folders in the Current Folder browser,
then right click, and choose Create Zip File to
create an archive. The archive appears in the current folder. You
can expand an archive in the same way. For details, see Creating
and Managing Zip File Archives.
This release changes the default behavior of the Current Folder browser. The Current Folder browser now dims files that are inaccessible to MATLAB to indicate their unavailability. A tooltip provides an explanation.
You can also customize or disable this feature. For more information, see Preferences for the Current Folder Browser and Viewing Files and Folders on the Search Path.
You can now remove folders from the MATLAB path as follows:
In the Current Folder browser, right-click the folder you want to remove from the path.
From the context menu, select Remove from Path, and then select Selected Folders or Selected Folder and Subfolders.
If the default preferences for the Current Folder Path indication option are set, the folders you removed now appear dimmed in the Current Folder browser. For more information, see Preferences for the Current Folder Browser and Removing Folders from the Search Path.
This release enhances the File and Folder Comparisons tool to improve the usability of comparisons between text files and folders.
File comparisons now highlight changes within lines and provide new toolbar buttons for stepping through differences, as the following figure shows.
Folder comparisons now provides results that are sortable by name, type, size, timestamp, or change summary. Click column headers to sort the table. Click compare links to explore differences between files and folders. The following example shows results sorted by Type.
When you compare subfolders with many files, now the tool continues analysis in the background, reporting progress. You can now skip items or cancel as you review this analysis.
For more information, see Comparing Files and Folders.
New features and changes introduced in Version 7.10 (R2010a) are:
The MATLAB Editor now supports tab completion for local variable and subfunction names within MATLAB program files. For more information, see Complete Names in the Editor Using the Tab Key.
This release provides two New Cell Mode toolbar buttons, Next
Cell
and
Previous Cell
.
You can use these buttons to step through cells in the Editor without
evaluating the code within the cells. By default, these buttons do
not appear on the Cell Mode toolbar.
For more information, see Navigate Among Code Cells in a File.
The factorization routine in
qr produces
an upper triangular matrix,
R. Now this matrix
always contains real and nonnegative diagonal elements. In previous
releases, the diagonal of
R could contain complex
and negative elements.
R now contains only real, nonnegative diagonal
elements. The
QR factorization is not unique, so
the answer is still correct.
Now subscripted reference into a sparse matrix always returns a sparse matrix. In previous versions of MATLAB, using a double scalar to index into a sparse matrix resulted in full scalar output.
Scalars extricated from sparse matrices are no longer full. If you previously used the output with a function that does not support sparse input, you now need to update your code. For a list of the functions that do not support sparse matrices, see Functions That Do Not Support Sparse Matrices in the MATLAB Mathematics documentation.
Functions that erroneously accepted N-D arrays and returned reshaped sparse 2-D outputs no longer accept full N-D inputs and now return an error. The functions affected are:
spones,
spfun,
sprand,
sprandn,
and
sprandsym
cat,
horzcat,
and
vertcat
Also, binary functions that formerly accepted both full N-D
inputs along with sparse 2-D inputs and warned about the reshape,
now return an error. For example,
ones(2,2,2).*sparse(3) formerly
returned a sparse 2-by-4 matrix along with a warning about the reshape.
This code now returns an error.
The functions
griddata3,
delaunay3,
dsearch,
tsearch will
be removed in a future release. Use of these functions now throws
a warning.
Update your code to use the
DelaunayTri and
TriScatteredInterp computational
geometry classes .
Support for the
erfcore function has been
removed. Use of
erfcore now results in the following
error message:
ERFCORE will be removed in a future release. Use ERF, ERFC, ERFCX, ERFINV, or ERFCINV instead.
These warning messages for integer math and conversion have been removed:
MATLAB:intConvertNaN
MATLAB:intConvertNonIntVal
MATLAB:intConvertOverflow
MATLAB:intMathOverflow
The warning messages for integer math and conversion are no longer available. Remove these warning IDs from your code.
The
intwarning function will be removed
in a future release. Use of
intwarning now throws
a warning:
Warning: All four integer warnings are removed. INTWARNING will be removed in a future release.
The warnings previously thrown when you used
intwarning on
are now removed. Remove all instances of
intwarning from
your code.
The warning thrown when you use
atan(i) and
atan(-i) will
be removed. Currently, the warning message is:
Warning: Singularity in ATAN. This warning will be removed in a future release.Consider using DBSTOP IF NANINF when debugging.
Remove instances of the warning ID
MATLAB:atan:singularity from
your code.
In previous releases,
nextpow2 with a vector
input
v returned
nextpow2(length(v)).
Now
nextpow2(v) returns a vector the same size
as the input.
If you require the old behavior, replace instances of
nextpow2 with
nextpow2(length(v)).
MATLAB no longer provides the
libdflapack.dll and
libdfblas.dll math
libraries for building Fortran MEX-files with a Compaq®.
In a future release, the
timeseries Boolean
property
isTimeFirst will behave differently. If
the value is
true, this property indicates that
the time vector is the first dimension of a time
series. If the value is
false, the time vector
is the last dimension of a time series. In this
release, you receive a warning that certain settings of
isTimeFirst will
not be valid in a future release. The warning indicates that for 3-D
or N-D data, time must be the last dimension,
while 2-D time series data can have time as the first dimension.
You can receive a warning when:
Constructing a time series object with three or more
dimensions without specifying a time vector. In a future release, MATLAB will
calculate a value of the
isTimeFirst property
that can differ from the value it currently calculates.
Changing the
data of a time series
to data of a different dimensionality. In a future release MATLAB will
calculate a value of the
isTimeFirst property
that differs from the value it currently calculates.
Directly setting the
isTimeFirst property
for a time series to a value that will be invalid in a future release.
The warning does not affect how you can use time series
data in this release. It is intended to inform you that the behavior
of
isTimeFirst will change in a future release.
If you receive a warning about
isTimeFirst, you
can use the
timeseries method
migrateistimefirst to
correct the problem. For information type
help timeseries/migrateistimefirst
Starting with this release, a vector containing sample times
can have duplicate times in contiguous positions. Previously, time
vectors needed to increase monotonically and duplicated time values
generated errors. This condition is now relaxed, such that time vectors
must be nondecreasing. Interpolation of time
series can produce duplicated times if the input to the interpolation
method contained duplicate time samples. For more information, see
the
timeseries reference
documentation.
This type of field access has never been allowed within function code, and this change causes scripts and command line statements to be in agreement with function rules.
If you have scripts that employ this type of dot indexing, they will now throw an error. Replace this unsupported style of dot indexing with the style shown above.
The following command constructs an empty
containers.Map object
that uses a key type of
kType, and a value type
of
vType:
M = containers.Map('KeyType', kType, 'ValueType', vType)
See the
containers.Map function
reference page for more information.
When creating a function handle inside a method of a class, the function is resolved using the permissions of that method. When MATLAB invokes the function handle, it does so using the permissions of the class. This gives MATLAB the same access as the locations where the function handle was created, including access to private and protected methods accessible to that class.
See Obtaining Permissions from Class Methods for more information.
The new
mmreader.getFileFormats method returns
a list of the formats that
mmreader supports.
The list of formats is static for Windows and UNIX systems,
but dynamic on Macintosh systems. For more information, see
the
getFileFormats reference
page.
In previous releases, for files archived using WinZip® software,
the
unzip function set the file write attribute
of extracted files to read only. Starting with R2010a,
unzip preserves
the original attribute.
MATLAB has included high-level routines for accessing Common
Data Format (CDF) files:
cdfread,
cdfwrite,
and
cdfinfo. However, the CDF API is so large,
these functions cannot satisfy every need. To solve this, MATLAB now
includes a new package, called
CDFlib, that provides
access to dozens of the functions in the CDF API. Using these low-level
functions, you can create CDF files and populate them with variables
and attributes using the CDF library, version 3.3.0.
The following table lists upgrades to several scientific file format libraries used by MATLAB.
The Tiff class includes the following enhancements.
You can no longer read YCbCr OJPEG ("old-style" JPEG compression) TIFF images. The Tiff object was not intended to work with OJPEG data but some TIFF files contain data in this format. Reading this data could cause LibTIFF to terminate.
To read OJPEG image data, use the
imread function.
Note that the
imread function transforms the image
data into the RGB colorspace.
The Tiff class includes the following additional capabilities:
Writing image data that use 16-bit colormaps (palettes)
Reading and writing
LogL and
LogLUV High
Dynamic Range (HDR) images. To write a
LogL or
LogLUV image,
you must use the new
SGILogDataFmt property.
You can now use the
imwrite function to create
a JPEG 2000 file and write data to the file. The
imwrite function
supports format-specific parameters that let you specify the mode,
compression ratio, and other characteristics.
While class properties do not have a
Sealed attribute,
the
meta.property class listed
Sealed as
a property.
Sealed is no longer listed as a
meta.property class
property.
The Plot Selector, which was upgraded in Version 7.9 (R2009b), now also generates plots for display functions in the following toolboxes:
Curve Fitting Toolbox
DSP System Toolbox
Image Processing Toolbox
Signal Processing Toolbox
The Plot Selector continues to support display functions for Control System Toolbox, Financial Toolbox, and Statistics and Machine Learning Toolbox™. You must have installed a toolbox to display data using its plotting functions. For more information about the Plot Selector, see Enhanced Plot Selector Simplifies Data Display.
MATLAB Version 7.10 (R2010a) supports these new compilers for building MEX-files:.
Open Watcom Version 1.8.
Support for the following compilers will be discontinued in a future release, at which time new versions will be supported. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
Intel Visual Fortran Version 10.1
Intel C++ Version 9.1
Intel Visual Fortran Version 10.1
Intel C++ Version 9.1
MATLAB no longer supports the following compilers:
Open Watcom Version 1.7
Microsoft Visual Studio .NET 2003 Version 7.1
Sun™ Studio 11 cc / CC Version 5.8
Sun Studio 11 f90 Version 8.2
To ensure continued support for building your MEX-files, consider upgrading to another supported compiler. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
If you run MATLAB Version 7.10 (R2010a) on a Linux with Debian® system, you must use Debian 5, as indicated on the Platforms & Requirements Web page.
MEX-files created with MATLAB Version 7.2 (R2006a) or earlier
depend on the
libstdc++.so.5 library. Debian 5
does not include this library. MATLAB running on Linux platforms
with Debian 5 cannot load these pre-R2006a MEX-files.
You cannot run MEX-files created with MATLAB R2006a or earlier on Linux with Debian 5. Recompile these files on a system with Debian 5.
MATLAB no longer provides the
libdflapack.dll and
libdfblas.dll math
libraries for building Fortran MEX-files with a Compaq.
On Windows 32-bit platforms, support for MEX-files with
a
.dll file extension is being phased out. Use
the
.mexw32 extension instead.
MATLAB Version 7.10 will continue to execute
.dll MEX-files,
but future versions of MATLAB will not support the
.dll extension.
You can no longer use the
mex function
-output switch
to create MEX-files with a
.dll extension. If you
enter a command such as:
mex myfile.c -output newfile.dll
MATLAB creates the MEX-file
newfile.mexw32 and
displays a warning message.
For more information about MEX-files with
.dll extensions,
see Running
MEX-Files with .DLL File Extensions on Windows 32-bit Platforms.
Recompile MEX-files with
.dll file extensions.
Update MATLAB scripts or
makefiles that explicitly
specify
.dll extensions for compiled MEX-files.
If you use MEX-files with a
.dll extension
from a third-party source, contact that vendor to get a recompiled
version, referring to these release notes.
In the next release of MATLAB, the default
mex command
will change to use the large-array-handling API. This means the
-largeArrayDims option
will become the default.
You do not need to make changes to build and run MEX-files with MATLAB Version 7.10 (R2010, Upgrading
MEX-Files to Use 64-Bit API.
When you start MATLAB using
-nodisplay (UNIX)
or
-noFigureWindows (Microsoft Windows)
startup options, running a built-in GUI (predefined dialog boxes)
generates this warning:
This functionality is no longer supported under the -nodisplay and -noFigureWindows startup options.
This change affects predefined dialog boxes, such as
dialog,
msgbox,
printpreview,
uigetfile,
uisetcolor,
waitfor,
waitbar,
and more. For a list of predefined dialog boxes, see Predefined
Dialog Boxes. For more information on startup options, see
the
matlab
(UNIX) and
matlab
(Windows) reference pages, respectively.
In a future release, instead of a warning, MATLAB will
generate an error when you use such a dialog box under the
-nodisplay or
-noFigureWindows options.
To avoid generating the warning, start MATLAB without the
-nodisplay or
-noFigureWindows startup
options. To avoid warnings while continuing to use these startup options,
remove the code that is now producing the warnings.
Version 7.9 removes support for the
-memmgr and
-check_malloc command
line arguments and the
MATLAB_MEM_MGR environment
variable.
MATLAB ignores any memory manager options.
New features and changes introduced in Version 7.9 (R2009b) are:
MATLAB supports customizing keyboard shortcuts for desktop tools. Press combinations of keyboard keys to perform a desktop action, instead of using the mouse to select items from menus. For example, press Ctrl+N to open a blank file in the Editor.
The ability to customize keyboard shortcuts enables you to:
Modify keyboard shortcuts across desktop tools on an action-by-action basis.
Modify keyboard shortcuts to match other applications you use or to match your personal preferences.
Share your keyboard shortcuts with others, or use shortcuts created by someone else.
Create keyboard shortcuts for some actions that currently have no shortcut.
Use your preferred keyboard shortcuts when you use MATLAB on a different system than you typically use.
To customize keyboard shortcuts, choose File > Preferences > Keyboard > Shortcuts.
MATLAB does not support customizing keyboard shortcuts for Figure Windows, dialog boxes, or toolboxes. For details, see Customize Keyboard Shortcuts. For a video demo, see Customizable Keyboard ShortcutsCustomizable Keyboard Shortcuts.
The method for specifying keyboard shortcuts differs from previous versions.
In previous versions, you chose File > Preferences > Keyboard, and then chose a set of key bindings. MATLAB no longer limits your choices to either platform-specific settings or Emacs settings.
Some default keyboard shortcuts differ from the previous defaults.
Defaults changed in Version 7.9 (R2009b) to be more consistent across the MATLAB desktop. Previously, you could specify keyboard shortcut preferences for the Command Window and Editor/Debugger only. For instance, on Windows, default keyboard shortcut preferences appeared as follows:
To restore keyboard shortcuts that were the default before Version 7.9 (R2009b):
Choose File > Preferences > Keyboard > Shortcuts.
From the Active settings drop-down menu, choose R2009a Windows Default Set, R2009a Macintosh Default Set, or R2009a UNIX Default Set, depending on the platform on which MATLAB is installed.
MATLAB now supports setting the font size and type for extended M-Lint messages and the function browser. In previous releases, changes to HTML Proportional Text affected only the display in the MATLAB Web browser, the Profiler, and Help topics. To set font preferences:
Choose File > Preferences > Fonts > Custom.
Under Desktop tools, select HTML Proportional Text, and then specify the font size and type you want to use.
For more information, see Fonts.
To save a file being displayed in the MATLAB Web Browser, select File > Save As.
For a demonstration of enhancements to the Help browser, watch the Help Browser EnhancementsHelp Browser Enhancements video.
When you expand a product in the Contents pane, you now can view the following:
Function and block names with brief descriptions — Expand Functions or Blocks, and then expand a category to see the list and descriptions. Select a function or block to view its reference page.
If you provide your own HTML help files for use in the Help browser, you now can include Functions and Blocks entries for your toolbox.
Demos — Expand Demos, and then select a demo from the list to view or run it.
Each search result includes:
A preview of where the search words were found within the page.
An icon representing the type of document, such as a reference page or demo.
Use new sorting and grouping features to arrange results:
Sort results by Relevance, in addition to sorting by Type and Product, which were available in previous versions.
After sorting by Type or Product, you now can collapse and expand results for each type or product. To expand or collapse all groups, right-click in the results pane and select the option you want from the context menu.
The following example of Search Results in the Help browser illustrates grouping, previews, and the block reference page icon.
To see where the current page is located within the documentation, use the navigation bar at the top of the display pane. To go to another topic in the documentation, select an entry from the navigation bar.
Use the new Actions button
on the display pane toolbar
to access features such as Refresh, which clears the search results
highlighting for the current page.
Get links to reference pages for overloaded functions.
When you run
doc foo, if
foo is
an overloaded function, a message appears at the top of the display
pane that provides links to the other
foo reference
pages.
To use the Help browser alongside other tools, dock it in the desktop. When docked in a narrow area of the desktop, the pane for Contents and Search Results moves above the display pane.
The Index and Demos tabs are no longer in the Help browser:
To find terms that were in the Index, use the search feature instead.
To access demos for a product, go to the Contents pane and expand the Demos entry for the product.
The Actions button on the toolbar provides access to features for the displayed page. Previously, some of these features were available on individual toolbar buttons. To add individual toolbar buttons, right-click the toolbar and select Customize.
If you provide your own files for use in the Help browser:
Remove the
helpindex.xml entry
from the
info.xml file for your toolbox. MATLAB no
longer supports the Index.
Demos you add now appear in the Contents pane
under
Other Demos, which is after the entries for
all MathWorks products.
For more information about the new Help browser features, see Help and Product Information.
The Plot Selector button on
the
Workspace Browser and Variable Editor toolbars has a new look and
added capabilities, options, and help. The tool now displays larger
icons, includes many more graphing functions, summarizes each function,
and displays pop-up windows with syntax descriptions (function
hints). You can customize the tool by rearranging and categorizing
functions, and by creating a list of "favorites".
For further details, see this video demovideo demo and the release note Enhanced Plot Selector Simplifies Data Display.
The Current Directory browser is now the Current Folder browser.
For an overview of the enhancements, watch this video, Current Folder Browser EnhancementsCurrent Folder Browser Enhancements, or review the following summary:
Use the expandable tree structure to view the contents of the current folder. Double-click a subfolder to make it the current folder.
Display the file type in a column.
Distinguish types of MATLAB program files using new icons:
class
function
script
View file descriptions below file names. To show or hide descriptions, select View > Show > Description.
Display hidden files a new way:
On Windows platforms, MATLAB follows your Windows preference for hidden files.
On other platforms, MATLAB uses the new setting in Current Folder preferences.
Find files and folders within the current folder and its subfolders:
To access the search feature, click the Search button
on
the address bar, and then enter the string you want to find.
To clear the results and display all files and folders
in the current folder, click the Clear button
.
The following illustration shows the new Current Folder browser, including the tree view, new icons for program files, and the search button.
With the new tree structure, you now see all files, including those in subfolders. You might not be able to run the files you see in the subfolders. To run a file from a subfolder, the subfolder must be on the search path or the subfolder must become the current folder. In previous versions, you could only see files in the current folder, so you could run every file you could see.
You now search for files by clicking the search button in the address bar. In previous versions, the search feature, referred to as the filter field, appeared if your preference was set to display it.
File descriptions now appear below the file name. In previous versions, they displayed in a column.
For more information about the new features, see Managing Files in MATLAB.
Watch this video, MATLAB File Exchange AccessMATLAB File Exchange Access, or review the following summary of what you can do with the new File Exchange desktop tool:
Access user-created files from the File Exchange repository. The files are at MATLAB Central, the community area of the MathWorks Web site.
Use the files in your own work to save time and get new ideas.
Work with the file repository from within the MATLAB desktop.
Use features like those found in the Web site interface to the File Exchange repository.
The File Exchange desktop tool offers these main features:
Find files by searching and by selecting tags (keywords associated with files).
Sort results. For example, show the most highly rated or the most recent files first.
View details about a file.
Download files to use in MATLAB.
Provide feedback about files.
To open the File Exchange tool, select Desktop > File Exchange.
If you have questions while you work, access the File Exchange
FAQ by clicking the Help button
. For full
documentation, see File Exchange
— Finding and Getting Files Created by Other Users.
New features and changes introduced in Version 7.9 (R2009b) are:
The MATLAB Editor now supports syntax highlighting for VHDL and Verilog code. For details see, Highlight Syntax to Help Ensure Correct Entries in the Editor.
When you use the File and Folders Comparisons tool to compare folders, it now includes the following information about each file in each folder:
The file size, in bytes
The date the file was last modified
In addition, the File and Folders Comparisons tool enables you
to reload the information by clicking the refresh button
or
selecting File > Refresh. For details see, Comparing
Files and Folders.
MATLAB now supports PDF as the output format for publishing MATLAB code
files. For instructions on how to publish to
If you use the Customize option to modify the locale setting, MATLAB ignores the customized portion. For example, if you select the euro currency symbol for a locale set to the United Kingdom, the locale name is:
en_GB@currency=EUR
MATLAB uses the locale name:
en_GB
2- and 3-D computational geometry functions (
delaunay,
convhull,
griddata,
voronoi,
delaunay3,
griddata3)
no longer use QHULL or the QHULL options arguments. The N-D functions
gridatan,
delaunayn,
convhulln,
and
voronoin still use QHULL.
The QHULL options arguments to
delaunay,
convhull,
griddata,
and
voronoi are no longer required and are currently
ignored. Support for these options will be removed in a future release.
A future release will remove the
griddata3,
dsearch,
tsearch,
and
delaunay3 functions. See the table below
for alternatives.
Update your old code to use the new computational geometry classes
DelaunayTri and
TriScatteredInterp.
MATLAB functions
fft,
fft2,
and
fftn (and their inverses
ifft,
ifft2,
and
ifftn) can now handle input arrays with a
size in 1 dimension greater than on
64-bit platforms.
MATLAB includes improved sparse matrix performance for indexing, basic math, binary and relational operators, and exponential functions.
There are significant performance improvements to
conv2.
Use of
erfcore will produce a warning:
ERFCORE will be removed in a future release. Use ERF, ERFC, ERFCX, ERFINV, or ERFCINV instead.
Replace all instances of
erfcore with
erf,
erfc,
erfcx,
erfinv,
or
erfcinv.
The Plot Selector button on the Workspace Browser and Variable
Editor toolbars has a new look and added capabilities, options, and
help. Now the Plot Selector button
changes
its appearance to reflect the variable or variables you select. Now
it suggests a plot type and indicates its calling argument sequence.
You can also make the Plot Selector list the types of graphs you use
most often at the top of its drop-down menu. The tool provides descriptions
and hints to help you discover data graphing functions and learn to
use them more effectively.
For further details, see this video demovideo demo and the release note Enhanced Plot Selector Simplifies Data Display.
This version of MATLAB introduces a new usage for the tilde
(
~) operator. As in earlier releases, tilde signifies
a logical NOT. In the 9b release, you can also use the tilde operator
to specify unused outputs in a function call, or unused inputs in
a function definition. See Ignore Function
Inputs in the Programming Fundamentals documentation for more
information on this feature.
This feature enables you to replace this type of function call:
[val1, ignoreThisOutput, val3] = myTestFun;
with the following:
[val1, ~, val3] = myTestFun;
MATLAB ignores any values returned by a function that have a corresponding tilde in the output list. This new syntax can help you avoid confusion in your program code and unnecessary clutter in your workspace. It also avoids wasting memory to store unused outputs returned from the called function.
You can also use the tilde operator to specify unused inputs when you are creating a function. You can replace this type of function definition:
function myTestFun(arg1, ignoreThisInput, arg3)
with the following
function myTestFun(arg1, ~, arg)
Whenever this function is called, MATLAB ignores any inputs passed to the function that have a tilde in the corresponding position in the input argument list. You are likely to find the tilde operator most useful when writing callback functions and subclass methods that must match a predefined function interface.
The MathWorks® reserves the use of packages named
internal for
utility functions used by internal MATLAB code. Functions that
belong to an
internal package are intended for The MathWorks use
only. Using functions that belong to an
internal package
is strongly discouraged. These functions are not guaranteed to work
in a consistent manner from one release to the next. In fact, any
of these functions and classes may be removed from the MATLAB software
in any subsequent release without notice and without documentation
in the product release notes.
See Internal Utility Functions in the Programming Fundamentals documentation for more information.
In version 7.5, The MathWorks introduced a new class called
MException for
use in error handling. Prior to this change, the
lasterr and,
more recently,
lasterror functions
kept track of only the one most recently thrown error. The state of
any errors thrown before that was overwritten by newer errors. Also,
this error state was globally accessible, which means that it could
be unintentionally modified or destroyed either during an interactive
session or by another function.
When using the newer, object-based error mechanism, every error
generated by a MATLAB function stores information about what
caused the error in a separate
MException object.
This enables MATLAB to store information about multiple errors,
adds the capacity to store new fields of information including links
to related errors, and also resolves the problem of being globally
accessible.
The MathWorks now discourages the use of the
lasterr and
lasterror functions
because the information they return is global and thus has the potential
to be corrupted. You should replace the use of these two functions
with the new style of
try-
catch statement
that captures an
MException object to represent
the error. When entering commands at the MATLAB command line,
you can also use the static method
Mexception.last to retrieve
information on the most recent error. For more information on this
method of error handling, see The
MException Class.
This change also affects which form of the
rethrow function
to use when reissuing an exception. The original
rethrow function,
in use since before version 7.5, accepts only a structure as input.
Because this structure is typically obtained using the
lasterror function,
this form of
rethrow should be avoided. The later
form of
rethrow(MException),
introduced in version 7.5, accepts an
MException object
as input, and is the recommended form.
It is strongly recommended that you discontinue the use of
lasterror and
lasterr,
and that you replace the use of these functions in your program code
with the
MException-based style of error handling
described above.
Invoking the function
maxNumCompThreads now
returns the following warning:
Warning: maxNumCompThreads will be removed in a future release. Please remove any instances of this function from your code.
maxNumCompThreads continues to operate
the same in this release of MATLAB. However, the function will
be discontinued in a future release of the product.
It is recommended that you discontinue the use of
maxNumCompThreads.
However, if you do have any program code that invokes this function,
you should make sure that such programs are not affected by this new
warning.
In previous releases, the Import Wizard imported only the first populated worksheet in an Excel file. The Import Wizard now allows you to specify the worksheet to import. To start the Import Wizard, use one of the following methods:
Select File > Import Data.
Call
uiimport.
Double-click a file name in the Current Folder browser.
mmreader now imports Motion JPEG 2000 (
.mj2)
files on Windows, Macintosh, and Linux platforms.
Because
mmreader imports Motion JPEG 2000
files, the function
mmreader.isPlatformSupported always
returns
true on Windows, Macintosh, and Linux platforms.
For a list of file formats that
mmreader supports,
and the requirements to read these formats on each platform, see the
mmreader reference
page.
If you specify a sample rate less than 80 samples per second,
audioplayer generates
an error with the following ID:
MATLAB:audioplayer:positivesamplerate
In previous releases, the error ID on Windows platforms for low sample rates was:
MATLAB:audioplayer:negativesamplerate
Change any references to this identifier to:
MATLAB:audioplayer:positivesamplerate
The function category "File I/O" is renamed "Data Import and Export." It appears immediately below the category "Desktop Tools and Development Environment."
In the MATLAB User Guide, Data Import and Export content previously appeared in the Programming Fundamentals documentation. The User Guide now includes a stand-alone topic for Data Import and Export.
Object array indexing operations on properties now return an error for improper array references. Before MATLAB 7.9, an expression such as:
obj.Prop(n) % for non-scalar obj is invalid if Prop is a property
did not return an error. MATLAB 7.9, you can reference or assign properties from scalar objects only by entering:
obj(int).Prop(n)
where
int is a positive integer.
Before MATLAB 7.9, an expression such as:
isequal(a,b)
returned false in cases where
a and
b are
objects of the same class that have properties set to numeric values
which are mathematically equivalent, but of different classes (for
example,
double and
single),
MATLAB 7.9 returns an error when it loads a class that
defines a property as both
Abstract and
Private.
Before MATLAB 7.9, the
numel function
did not return the same results for built-in classes and subclasses
of built-in classes. In MATLAB 7.9, the behavior of
numel is
consistent with built-in classes and subclasses of built-in classes.
See Understanding
size and numel for a discussion of the current behavior.
Before MATLAB 7.9, initializing a handle object array by specifying the last element in the array to create it:
obj(10) = MyClass;
resulted in the same handle being assigned from the second to the penultimate elements of the array. With MATLAB 7.9, all elements in the handle object array have unique handles. See Creating Object Arrays for more information on the current behavior.
Using the new
Tiff object, you can now write
portions of a TIFF file and update the values of individual metadata
tags in an image. MATLAB has long offered the capability of reading
and writing TIFF files, using the
imread and
imwrite functions.
However, if you wanted to update any part of the image, you had to
write the entire image to the file. Similarly, if you just wanted
to update a tag, you had to write the entire image. By providing access
to functions in the LibTIFF library, the Tiff object offers more flexibility
in creating and editing TIFF images. You can write data to specific
tiles in an image and update individual tags in a file, without having
to write the entire image.
Due to a bug, versions of MATLAB prior to Version 7.9 did
not report an error in functions such as the following, even though
it cannot be determined in the last line whether
U is
a variable or a function:
function r = testMfile1(A) A = 1; eval('U = 1;'); r = A(logical(end), U(end));
However, if you replace the last line with
r = A(U(end));
MATLAB reports an ambiguity error and has done so since Version 7.0. Starting in Version 7.9, MATLAB reports an ambiguity error for either statement.
In certain circumstances, it is possible that you will see ambiguity errors generated in code that did not report this error in previous releases. If you do get such an error, examine your code and resolve the ambiguous statements.
The Plot Selector workspace tool creates graphs of workspace variables. As this video demovideo demo shows, the tool lets you access more types of data display functions and provides help about each one. It also categorizes display functions and lets you organize them within its drop-down menu. The following illustration shows the old and new versions of the Plot Selector and calls out new features.
Use the Plot Selector tool to instantly generate graphs of workspace variables. You can choose from more than 40 two-dimensional, three-dimensional, and volumetric MATLAB data display types. It also constructs graphs using Control System Toolbox, Financial Toolbox, and Statistics and Machine Learning Toolbox functions if your installation includes those products.
The Plot Selector button
displays
a graph icon and the names of selected variables in the Workspace
browser or the Variable Editor. Until you select one or more variables,
the button reads Select to plot
. The graphing function
for one or two data vectors still defaults to
plot,
but the tool now gives you additional options and information, including
the following:
The grouping of menu items into categories of graph types, such as Stem and Stair Plots, 3-D Surface Plots, and Analytic Plots. You can rearrange categories and items within a category by dragging them.
A Favorites category at the top of the menu, where you can collect the types of graphs you use most often. Your collection of favorites persists across MATLAB sessions.
A star-shaped button
on menu items
that adds a graph type to or removes one from your Favorites collection.
Two tabs
for toggling
the scope of the menu:
Plots for <variable names> — The set of graphs you can generate with the currently selected variables
All plots — A master list of graphing functions available on your system
On the All plots tab, graphing functions that are not compatible with the selected variables display in gray and do not plot. Incompatible plot types do not appear on the first-tab menu.
A button
to interchange the axes positions
of two selected variables
Pop-up descriptions of function syntax when your mouse pointer lingers over a menu item
Direct access to your Favorites from context menus in the Workspace Browser and the Variable Editor
For more information, see Creating Plots from the Workspace Browser.
In previous versions, the Plot Selector automatically
assigned variables named
t and
time to
the x-axis. Now, the variable you select first
always plots on the x- axis. Use the switch variable
input order button
to interchange the x and y variables
before plotting them.
In previous versions, clicking Plot Selector > More Plots opened the Plot Catalog tool. Now, you click Catalog at the bottom of the Plot Selector GUI to open the Plot Catalog tool. The Plot Catalog has not changed.
The following print command option and device now throw warnings when used and will be removed in a future release:
If you wish to prevent these warnings from displaying, use the warning command.
To disable the warning generated by using the
–adobecset print
option:
warning('off', 'MATLAB:print:adobecset:DeprecatedOption');
To disable the warning generated by using the
–dill print
device:
warning('off', 'MATLAB:print:Illustrator:DeprecatedDevice');
If you have developed code that uses the previous option or device, in the future you must remove such calls or replace them with other code.
The section Lay Out a Programmatic GUI of the Creating Graphic User Interfaces documentation has been expanded. The updated section, formerly called "Aligning Components," now has the title Compose and Code GUIs with Interactive Tools.
The renamed section describes techniques, functions, and predefined dialog boxes you can use to accelerate programmatic construction of GUIs (that is, those you create without using GUIDE).
The section includes examples of setting component positions,
colors, and font properties interactively. Also included is an example
function that generates a
set statement for a
specified property of any GUI component. By running this function
and pasting its output into your GUI code file, you can save time
and avoid making typographical errors.
The MATLAB
SelectionType figure property
had an undocumented change in V. 7.6 (R2008a). That change modified
how the property is set in response to single-clicking and double-clicking
objects, particularly uicontrols, with and without key modifiers.
For information about this change, including potential incompatibilities,
see Changes to How uicontrols Set Figure SelectionType. The table
in that release note specifies the
SelectionType setting
resulting from clicking a UI component in both enabled and disabled
states.
MATLAB Version 7.9 (R2009b) supports these new compilers for building MEX-files:
Apple Xcode 3.1 (gcc / g++ Version 4.0.1)
GNU gfortran Version 4.3
MATLAB Version 7.9 (R2009b) supports the following compilers but will not support them in a future version.
Intel Visual Fortran Version 10.1
Intel C/C++ Version 9.1
Microsoft Visual Studio .NET Version 7.1
Intel Visual Fortran Version 10.1
Intel C/C++ Version 9.1
Sun Studio 11 cc / CC Version 5.8
Sun Studio 11 f90 Version 8.2
MATLAB no longer supports the Intel Visual Fortran Version 9.1 compiler on the following platforms:
Windows 32-bit
Windows 64-bit
To ensure continued support for building your Fortran programs, consider upgrading to another supported compiler. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
You must provide the Visual C++ run-time libraries if you distribute any of the following:
MEX-file
Engine application
MAT-file application built with the Visual Studio 2008 compiler
You need these files.
The use of the
-inline switch has been deprecated
and will not be available in future versions of the
mex function.
This release includes several changes that affect your use of the Microsoft .NET framework:
The
NET.addAssembly function
returns information about the assembly in the
NET.Assembly class.
You can also add an assembly using an instance of the
System.Reflection.AssemblyName class.
You can access elements of a .NET array using MATLAB one-based indexing, as described in Accessing .NET Array Elements in MATLAB.
To call a generic method, use the
NET.invokeGenericMethod function.
You can change a static property or field name using
the
NET.setStaticProperty function.
You can use overloaded operators, such as
+ and
*.
For a complete list of supported operators, see How
MATLAB Represents .NET Operators.
For an overview of the major new features in the MATLAB Desktop Tools and Development Environment area, watch this video demovideo demo. Another way to access the demo is by selecting the Demos tab in the Help browser, and then selecting MATLAB > New Features in Version 7.8.
The
matlab command to start MATLAB now
supports the
-singleCompThread option on all platforms.
When you specify this option, you limit MATLAB to a single computational
thread. By default, if you do not specify this option, MATLAB makes
use of the multithreading capabilities of the computer on which it
is running.
New features and changes introduced in Version 7.8 (R2009a) are:
On UNIX platforms (except Apple Macintosh), MATLAB now
uses the Mozilla® Firefox® browser by default to display
documents or Web sites in a system browser. If you want MATLAB to
use a different system browser, use the new System Web browser setting
in Web preferences to specify it. In addition, the
web function
with the
–browser option now determines
the system browser to use from the preference. For more information,
click the Help button in the Web preference
pane, or see Web
Preferences.
In previous versions, the default system browser on UNIX platforms was Netscape Navigator®; it is now Firefox. If you do not have Firefox on your system, when MATLAB tries to use a system browser, it produces a warning. To correct the problem, use Web preferences to specify a system browser that is installed.
In previous versions, if you wanted to use a different browser,
you specified it in the
docopt.m file. Starting
in R2009a, MATLAB ignores the browser specified in
docopt.m.
If you have code that relies on
docopt.m, your
code still runs, but it produces a warning. Remove the calls from
your code. In future versions, the code will not run and will produce
an error.
If you have your own
docopt.m file, delete
it and either use the new default, Firefox,
or specify a different system browser using Web preferences.
If you want to access the Internet from MATLAB, and your network uses a firewall or another means of protection that restricts Internet access, you now can ensure your proxy server settings are working correctly. Click the new Test Connection button in Web preferences, and MATLAB will use the proxy settings you specified in Web preferences to attempt to access the Internet. For more information about the proxy server features, click the Help button in the Web preferences pane, or see Web Preferences.
The Command Window and Editor now support tab completion for class directories. In addition, the Command Window supports tab completion for class file names. For details, see Complete Names in the Command Window Using the Tab Key.
New features and changes introduced in Version 7.8 (R2009a) are:
When you start MATLAB, the Help browser no longer automatically opens if you had it open when you last quit MATLAB.
In previous versions, the Help browser opened at MATLAB startup
if it had been open when you last quit MATLAB. If you want the
Help browser to automatically open at startup, use a startup option.
For example, you can include a
helpbrowser statement
in your
startup.m file. For more information, see Startup Options.
If you include a statement in a
finish.m file
that closes the Help browser automatically whenever you quit MATLAB,
you now can remove that statement because MATLAB now performs
the action by default.
The
docsearch function,
which you can use to search the documentation, now accepts multiple
words as input, without requiring the function form of the syntax.
For example, in previous versions, you used
docsearch('word1
word2'), but now you can use
docsearch word1 word2.
With the new form of the syntax, you can use all options for
docsearch,
such as wildcards (for example,
docsearch wor*)
and exact phrases (for example,
docsearch "word1 word2").
To find out if you are currently running a 32-bit or 64-bit version of MATLAB, select Help > About MATLAB, and view the value in the resulting About MATLAB dialog box. You might need to know the version if you want to take advantage of the benefits of 64-bit MATLAB, or if you want to use files that depend on the version, such as MEX-files.
The About MATLAB dialog box also shows the architecture value,
for example,
(win32) or
(win64).
You use this value for the
arch option of the
mex function.
For more information, see Information About your Installation.
These are the enhancements to the Current Directory browser:
You can use the new View menu to choose the columns to display, to specify the sort order for a column, and to apply grouping for any attribute. In the previous version, you performed these actions using the column header and its context menus, which you can still do (but only on Microsoft Windows platforms). For more information, see Sorting and Grouping Files and Folders.
A new Description column displays the brief description for files and directories in the current directory. To show the column, use View > Choose Columns. Descriptions include the first help line in a MATLAB program file, and a model file's description, which is useful because you do not need to start the Simulink software to view it. The description is the same one that appears with the details for a selected file. For more information, see Viewing Help for a MATLAB Program File.
If you try to rename a MATLAB program file in
the Current Directory browser to an invalid name, such as
*myfile.m,
a warning appears, notifying you about the name problem. If you want
to run the ile, change the file name to a valid one. For more information
about what a MATLAB file name requires to be valid so you can
run it, see Naming
Functions.
When you right-click a FIG-file in the Current Directory browser, there is a new option to open the figure in GUIDE.
New features and changes introduced in Version 7.8 (R2009a) are:
When you create a file with integrated M-Lint warning and error messages enabled, you can get additional information about many of the messages. When you hover the pointer over an M-Lint indicator that has an extended message, the message appears as a link:
When you click the link, the message window expands to display an explanation and suggested action.
When you click a link within the extended message, the Help browser opens to provide more information.
You can now filter the list of M-Lint messages in the preferences panel (File > Preferences > M-Lint), to find a message of interest.
For example, you can search for a message:
Containing a string
Corresponding to a particular message ID
Within a given category
With a setting different from the default
Filtering the list of messages can help you see, for example, why certain messages are suppressed, and which messages are disabled. It can be helpful when you want to see the explanation and suggested action for a message, as described in Many M-Lint Messages Now Extend to Provide an Explanation and Suggested Action.
The Block Indent option is no longer available. Previously, this option was available for MATLAB, Java, and C/C++ programming languages, when you selected File > Preferences > Editor/Debugger > Language.
To attain the effect of block indenting, you can use the No indent option and indent lines manually using the Tab and space keys.
The MATLAB Editor no longer supports EmacsLink. In previous releases, you could choose File > Preferences > Editor/Debugger, and then (if you correctly registered EmacsLink with MATLAB) you could select Integrated text editor. This option is no longer available.
The File and Directory Comparisons Tool now provides links to help you quickly navigate to the areas of differences. This is useful for large files that have too many lines to fit on the screen. At the top of the page is a link to the first difference. In addition, each set of differences has an up arrow that you click to go to the previous set of differences, and a down arrow you click to go to the next set of differences. For details, see Stepping Through Differences.
When the Find Next operation for searching files in the Editor reaches the end of a file, it automatically wraps around to search from the beginning of the file for the text you specified. In previous releases, the Wrap around option was off by default. This meant that if you were in the middle of a file and the text you were searching for appeared before your current position, Find Next would not find that text.
Because it is more convenient to have this option on, it is now selected by default. To access this option, select Edit > Find and Replace.
For more information, see Find and Replace Text in Files.
The bottom of the Profile Summary Report now indicates the amount of time spent in profiling overhead, when possible. For details, see Profile Summary Report.
New features and changes introduced in Version 7.8 (R2009a) are:
Two new options are available to specify how you want figures
captured for published documents:
entireGUIWindow and
entireFigureWindow.
The
entireGUIWindow option is appropriate for most
publishing purposes and is now the default. The
entireFigureWindow option
is appropriate when you want to capture all the details, including
the title bar and other window decorations in your published document.
Use this option, for example, if you are creating a tutorial on using MATLAB software.
In the GUI, you can select these options from the Figure
capture method setting in the Edit M-file Configuration
dialog box. In the
publish function, you can specify
these options with
figureSnapMethod.
For more information, see Figure
capture method and the
publish reference
page.
When you publish a document to HTML, you can include dynamic links. Dynamic links are links to files on the MATLAB path. They are called dynamic links because MATLAB evaluates them when the reader of your document clicks on one. To use a dynamic link, the reader must open the HTML file in the MATLAB Web browser.
For more information, see Dynamic Hyperlinks..
MATLAB has new functions for incomplete inverse gamma and
incomplete inverse beta functions. These functions,
gammaincinv and
betaincinv,
provide the Statistics and Machine Learning Toolbox functionality of the inverse incomplete
gamma and beta functions to MATLAB.
Use of the
conv2 and
convn functions
with one empty input now returns the matrix of the correct size as
described by the
shape input.
nextpow2 with
a nonscalar produces a warning:
Warning: NEXTPOW2(X) where X is non-scalar will change behavior in future versions: it will operate on each element of X. To retain current behavior, use NEXTPOW2(LENGTH(X)) instead.
This behavior will change in a future release. Replace instances
of
nextpow2 with
nonscalar input
X to
nextpow2(length(X)) to
maintain the current behavior.
MATLAB supports 64-bit integers for matrix dimensions in LAPACK, and BLAS. Linear algebra operations can now handle matrices of dimensions greater than .
MEX files that call BLAS or LAPACK need to
be updated. All integer variables passed into BLAS or LAPACK need
to be of type
mwSignedIndex.
MEX files
compiled in previous versions of MATLAB that call BLAS or LAPACK
could lead to undefined behaviors. If you have existing code that
generates
MEX files that pass variables to BLAS
or LAPACK you need to update the code to use the proper data types
and recompile.
The capability to adjust the number of computational threads in a single MATLAB session is no longer available as of this release. This change removes from the MATLAB preferences panel the ability to set the maximum number of computational threads. The primary reason for this change is that products that MATLAB is dependent upon have the ability to spawn threads from the currently-executing thread. This makes it infeasible to monitor and/or limit the number of computational threads at any given time in a MATLAB process.
MATLAB versions 7.8 and later require that you decide between
threading and no threading at the time you launch your MATLAB session.
Multithreading is enabled by default. To disable this feature, start MATLAB using
the new
singleCompThread option.
If you currently use the preferences panel to enable or disable multithreading or to adjust the number of computational threads, you need to be aware that this capability is no longer available. See the Startup Optionssection in the Desktop Tools and Development Environment documentation to find out how to enable or disable multithreading when launching a new MATLAB session.
The format in which MATLAB saves Timer objects has changed in MATLAB version 7.8. Any Timer objects that you create and save while running MATLAB 7.8 cannot be loaded into an earlier version of MATLAB.
If you need to use a Timer object that you have constructed using MATLAB 7.8, you will have to reconstruct and save the object in an earlier version of MATLAB.
The
mmreader object now supports Linux platforms.
For more information about using
mmreader, see
the
mmreader reference page.
If you have installed Excel 2007 (or Excel 2003 with
the Compatibility Pack) on your Windows system, the
xlswrite function
exports data to XLSX, XLSB, and XLSM formats.
To write data to an Excel file, specify the name and extension
of the output file in the call to
xlswrite. If
the file already exists,
xlswrite writes data in
the existent file format. If the file does not exist,
xlswrite creates
a new file, using the format that corresponds to the file extension
you specify. If you do not specify a file extension,
xlswrite applies
the XLS extension, and writes a new file in the XLS format.
The
xlsread function
imports any file format recognized by your version of Excel,
including XLS, XLSX, XLSB, XLSM, and HTML-based formats. The
importdata function
imports XLS, XLSX, XLSB, and XLSM formats. The Import Wizard imports
XLS and XLSX formats.
The
str2func which, prior to this release,
converted a function name to a function handle, now also converts
an anonymous function definition to a function handle. See the function
reference page for
str2func for
more information.
N = 5; NthPower = str2func(['@(x)x.^', num2str(N)]); NthPower(8) ans = 32768
The
validateattributes function
now enables you to check the size and range of the input value. The
following commands validate the size and range of the values of
x and
y respectively:
x = rand(4,2,6); y = uint8(50:10:200); validateattributes(x, {'numeric'}, {'size', [4,2,6]}); validateattributes(y, {'uint8'}, {'>=', 50, '<=', 200})
The example below describes a bug in the MATLAB software that has been fixed in version 7.8. The bug was caused by misinterpretation of an unassigned variable. For certain names, MATLAB mistakenly interpreted the variable as a stem in dot indexing.
The following example illustrates the problem. The example is a bit artificial (which is why the bug went undiscovered for so long).
Suppose you have a function that is intended to perform two levels of dot-indexing:
function y = dotindextwice_A(j) y = j.lang.String;
Calling this function with no arguments results in an error in all versions of MATLAB, as it should.
Now modify the function slightly so that the input variable
is named
java and run it on a version of MATLAB prior
to Version 7.8:
function y = dotindextwice_B(java) y = java.lang.String;
Now when you run the function without arguments, MATLAB misinterprets
the word
java, treating it as if it were the stem
of a Java class name:
x = dotindextwice_B; % Deliberately called with no arguments
Prior to Version 7.8, this function did not throw an error.
In fact, it returned an instance of the
java.lang.String class:
class(x) ans = java.lang.String
This violates the rule that variables in functions are supposed
to hide all other uses of the name. Beginning in Version 7.8, calling
function
dotindextwice_B without arguments results
in an error, just as calling
dotindextwice_A does.
The R2009a release of MATLAB uses version 1.8.1 of the
HDF5 library. The HDF Group has deprecated two of the HDF5 library
functions,
H5Pget_cache and
H5Pset_cache.
Their M-file counterparts,
H5P.get_config and
H5P.set_config,
may not work as they did in prior releases of MATLAB. To replace
these deprecated functions in your code, consider these four new HDF5
functions:
H5P.get_mdc_config,
H5P.set_mdc_config,
H5F.get_mdc_config,
and
H5F.set_mdc_config.
If your code uses
H5P.get_cache or
H5P.get_cache,
your program will produce a warning message.
You can no longer call an indirect superclass constructor from a subclass constructor. For example, suppose class B is derived from class A, and class C is derived from class B. The constructor for class C should not call the constructor for class A to initialize properties. The call to initialize class A properties should be made from class B.
If you define classes in which subclass constructors call indirect superclass constructors, MATLAB now issues an error when you attempt to create an instance of the subclass. Call Only Direct Superclass from Constructor for information on how to correctly code subsclass constructors.
The following functions have been added to MATLAB from the Image Processing Toolbox:
rgb2ind: Convert RGB image to indexed
image.
dither: Convert image using dithering.
cmunique: Eliminate unneeded colors
in colormap of indexed image.
cmpermute: Rearrange colors in
colormap.
imapprox: Approximate indexed image
by one with fewer colors.
The
dither and
imapprox functions
no longer display their output as an image via a call to
imshow when
called with no output arguments. Instead, the first output argument
appears in the Command Window if no semicolon ends the line.
Function
rgb2ind errors when called
with syntax
rgb2ind(rgb).
Function
imapprox errors when called
with syntax
imapprox(x,map).
A new example in the documentation teaches you how to code a GUI that manages multiple lists, such as to-do and shopping lists, contact information, music or video catalogs, or any set of itemizations. Among other things, it illustrates how to write MATLAB code to:
Share callbacks among uicontrols.
Obtain component handles from their tags.
Create a new version of an existing GUI.
Import and export list data.
Edit, add, delete, and reorder list items.
Save a list in the GUI itself.
Concurrently run multiple GUIs containing different data that call back to the same function.
This example does not use GUIDE. To read about and run it, see A GUI That Manages List Data in the documentation for Creating Graphical User Interfaces.
The Help menu in GUIDE now links to more topics in the documentation than previously. It also links to a set of video tutorials on the MATLAB Central Web site. For details, see Getting Help in GUIDE in the Opening GUIDE section of the Creating Graphical User Interfaces documentation.
The interface to .NET allows you to bring .NET assemblies into the MATLAB environment, to construct objects from classes contained in the assemblies, and to call methods on these objects. For complete documentation of this feature, see Using .NET Libraries from MATLAB. For an overview of the .NET interface, watch this video demovideo demo.
MATLAB Serial Port is now supported on the following platforms:
Microsoft Windows 64-bit
Apple Macintosh OS X
Macintosh OS X 64-bit
Linux
Linux 64-bit
Sun Solaris™ 64-bit
MATLAB Version 7.8 (R2009a) supports these new compilers for building MEX-files:
Microsoft Visual Studio 2008 SP1
gcc Version 4.2.3
GNU gfortran Version 4.2.2
The following compilers are supported in Version 7.8 (R2009a), but will not be supported in a future version of MATLAB:
Intel Visual Fortran Version 9.1
Intel Visual Fortran Version 10.1
Intel C/C++ Version 9.1
Microsoft Visual Studio .NET Version 7.1
Intel Visual Fortran Version 9.1
Intel Visual Fortran Version 10.1
Intel C/C++ Version 9.1
Sun Studio 11 cc / CC Version 5.8
Sun Studio 11 f90 Version 8.2
MATLAB no longer supports the following compilers:
Open Watcom Version 1.3
Microsoft Visual Studio 2005 Express Edition
Microsoft Platform SDK
g95 Version 0.90
To ensure continued support for building your C/C++ programs, consider upgrading to another supported compiler. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
It is improper to call
mxFree on an
mxArray.
Previously, to remedy misleading statements in older documentation,
under limited circumstances, MATLAB issued a warning in code
that made this error. MATLAB no longer issues the warning.
The correct function to use to release memory for an
mxArray is
mxDestroyArray.
Calling
mxFree on an
mxArray could
cause memory corruption, which might result in a segmentation violation.
You are no longer able to build a MEX-file using the MATLAB Version 5 API. If you use any of the functions shown in the Obsolete Functions: MX Array Manipulation table, you must replace them with functions from the Replacement column, if available. These obsolete functions were deprecated when MATLAB Version 6 was released over 5 years ago.
You must update any MEX-file that calls functions in the BLAS or LAPACK math packages on 64-bit platforms. The change occurs as a result of updated support, described in 64-bit Support in LAPACK and BLAS. Existing MEX-files generated in previous versions of MATLAB will result in undefined behavior (likely crashes), if run in R2009a. The previous versions pass 32-bit integer arguments, but the math routines now read and write to 64 bits of memory. The results you see depend on what is stored in the subsequent 32 bits of memory.
On 64-bit platforms, you must use 64-bit integers for all input
and output variables when calling LAPACK and BLAS routines in C and
Fortran source MEX-files. Use the
mwSignedIndex type
for platform-independent code.
MATLAB saves object
.o files when compiling
MEX-files on Apple Mac OS Version 10.5 systems so that you
can use source-level debugging..
It is now possible to use the
char** return
value and to increment the resulting pointer to retrieve all values.
See Passing
an Array of Strings.
Added support for accessing values exported by a library.
All fully and partly sized arrays should now work.
Use the following new functions to work with Sun Java objects on the Event Dispatch Thread (EDT).
The underlying technology used in the
createClassFromWsdl and
parseSoapResponse functions
was modified to better ensure support for WSDL and SOAP standards.
There was no intended change to functionality or results of
the
createClassFromWsdl and
parseSoapResponse functions,
which MathWorks verified through testing. There are
many variations among WSDL files and Web services and they cannot
all be tested. Therefore, it is possible that your results using the
createClassFromWsdl and
parseSoapResponse functions
in this version could differ from a previous version.
Ensure that your results using
createClassFromWsdl and
parseSoapResponse functions
are as expected.
For an overview of the major new features in the MATLAB Desktop Tools and Development Environment area, watch this video demovideo demo. Another way to access this and other video demos is to select the Demos tab in the Help browser, and then select MATLAB > New Features in Version 7.7.
New features and changes introduced in Version 7.7 (R2008b) are:
MATLAB for Apple Macintosh platforms is now installed
like many other applications for Macintosh platforms, as a Macintosh
.app bundle.
This has resulted in some enhancements and changes to starting and
using MATLAB on Macintosh platforms.
To start MATLAB on the Macintosh platform, double-click
the
MATLAB_R2008b icon in the
Applications folder.
This differs from R2008a (V7.6), where you started MATLAB by
double-clicking the
MATLAB 7.6 icon in the
Applications/MATLAB_R2008a folder;
there was an additional folder level in R2008a.
You can now start MATLAB by double-clicking a file with
a file extension that has been associated with MATLAB, such as
a file with a
.m extension. Similarly, you can
drag a file onto the
MATLAB_R2008b icon in the
Applications folder
or in the dock. These actions start MATLAB and open the file.
When you use file browser GUIs to navigate in the MATLAB root
directory,
/Applications/MATLAB_R2008b, (known
as the
matlabroot directory), you cannot
directly view or access its contents. For example, when you select File > Open and navigate to
Applications/MATLAB_R2008b,
no contents display. To access the contents, press Command+Shift+G,
and enter the path to the MATLAB root directory in the resulting
Go To Folder dialog box, for example,
/Applications/MATLAB_R2008b.app.
Similarly, when you select
MATLAB_R2008b in
the
Applications folder using the Finder, you do
not see the contents. To access the contents, right-click (or Ctrl+click)
MATLAB_R2008b,
and from the context menu, select Show Package Contents.
For more information, see Navigating
Within the MATLAB Root Folder on Macintosh Platforms.
You can no longer set startup options using the Start MATLAB
Settings dialog box and you can no longer start MATLAB from any
.smat files
you saved using Start MATLAB Settings. The dialog box is now used
only for diagnostics and only appears if MATLAB experiences a
problem during startup.
To set the startup directory in MATLAB, use the
userpath function.
To instruct MATLAB to run a specified statement upon startup,
start MATLAB using the
matlab command from
a shell, as you would to start MATLAB on any UNIX platform.
For more information, see Startup Options.
In R2008b (V7.7), to start MATLAB from a shell, enter the
path to the executable,
/Applications/MATLAB_R2008b.app/bin/matlab.
This differs from R2008a (V7.6), in which the path was
/Applications/MATLAB_R2008a/bin/matlab.
The compatibility considerations are described along with the above changes.
MATLAB is now using Sun Microsystems™ JVM™ Version 6 Update 4 software on all platforms, except the Apple Macintosh platform. If you specify a version of Java software to use with MATLAB, this change might impact your work.
When you start MATLAB on Microsoft Windows 32-bit
platforms, you can set a startup option to help ensure the largest
available contiguous block of memory after startup, which is useful
if you run memory-intensive operations, such as processing large data
sets. You can use the new
-shield startup option
to specify different levels of protection of the address space during
the MATLAB startup process. This can also help resolve problems
if MATLAB fails to start. For more information, see the
matlab
(Windows) reference page.
When you start MATLAB with the
-nojvm startup
option, Handle Graphics® functionality will no longer be supported.
(The
-nojvm option is available for UNIX platforms;
see background information
hgexport, and
saveas.
Creating GUIs in MATLAB using GUI-building functions
such as
warndlg.
Using Simulink scopes and printing Simulink models.
In MATLAB Version 7.7 (R2008b), if you use the
-nojvm startup
option and use Handle Graphics functionality, MATLAB produces
this warning:
This functionality is no longer supported under the -nojvm startup option.
In a future release, instead of a warning, MATLAB will
produce an error when you start with the
-nojvm option
and use Handle Graphics functionality.
To avoid the warning, the Performance and Memory Usage topics
in the MATLAB Programming Fundamentals documentation.
If you want to continue to use the
-nojvm startup
option, remove the code that is now producing the warnings.
The
matlab command line arguments
-memmgr and
-check_malloc are
deprecated and will be removed in a future release. The environment
variable
MATLAB_MEM_MGR is also deprecated and
will be removed. For information about these options, see
matlab
(Windows) or
matlab
(UNIX).
If you use these options, MATLAB generates a warning message.
New features and changes introduced in Version 7.7 (R2008b) are:
There is a new desktop layout when you select Desktop > Desktop Layout > Default. It includes the same components as the previous default desktop layout, however, they are arranged differently. If you prefer the previous default layout, arrange your desktop in that way and save the layout. You then can reuse the saved layout at any time.
If you have multiple documents open, you can now close a document by clicking the middle mouse button when the pointer is in the document's button on the document bar.
When you open the Preferences dialog box, it displays the last preference pane you viewed in the current session. In prior versions, the Preferences dialog box displayed the pane associated with the tool from which you accessed it.
You now can specify that the desktop text font use the system default font. To do this, select File > Preferences > Fonts. Then, for Desktop text font, select Use system font. For more information, click the Help button in the Fonts Preferences dialog box.
The default settings for the desktop text font and the HTML
Proportional Text font have changed. This only affects existing users
who choose to use a new preferences file (
matlab.prf)
in R2008b.
If you want to access the Internet from MATLAB and your network uses a firewall or another means of protection that restricts Internet access and requires you to provide a username and password, use the new proxy server authentication settings in Web preferences to specify the values. For more information, click the Help button in the Web preferences pane, or see Web Preferences.
While you work, you can find the names of functions and get help for them using the new Function Browser. The Function Browser is useful if you want to find a function whose name you cannot remember, determine if there are functions that do what you want, or view the reference page for a function. The Function Browser uses a subset of the information found in the function reference pages in the Help browser for quick access while you work.
To access the Function Browser, press Shift+F1,
or if you are in the Command Window or Editor, click the Function
Browser button
. The Function Browser
opens. You can specify the products to look in, browse categories
of functions, and search for words that appear in function reference
pages. For more information, see Find
Functions Using the Function Browser.
While you enter statements in the Command Window and Editor, you can view the allowable input argument syntax for a function in a pop-up window. This feature is called function hints. To use function hints:
Type the function name, followed by the left parenthesis,
(,
and pause. The syntax for input arguments automatically displays in
a pop-up window near the statement you are entering.
The arguments you can enter appear in bold. Enter your
first argument and type a comma (
, ) after it.
The syntax options in the pop-up window then change, based on the
argument you just entered.
Continue entering arguments, using the hints as needed. You can dismiss the function hints pop-up window at any time by pressing Esc. When you type the closing parenthesis, ), or when there are no more arguments to enter, the pop-up window automatically closes.
The following illustration shows function hints for the
plot function.
To turn off the function hints feature so the pop-up menu does not automatically display the syntax reminders when you type an opening parenthesis, use Keyboard preferences; for Function Hints, clear the check box that enables them.
For more information, see View Function Syntax Hints While Entering a Statement.
There are two new features that provide help while you work:
Use the new Function Browser to find function names while you work. It is most useful in the Command Window and Editor, but you can access it from any tool. For more information, see Find Function Names and Get Help Using the New Function Browser.
Use function hints to help you complete syntax for statements in the Command Window or Editor. For more information, see View Syntax Hints While Entering Statements.
If you create your own class definition files in MATLAB and
you provide help in the
classdef file for the class,
properties, and methods, you can conveniently view the help in the
Help browser by running
doc
classname.
For more information, see Help
for Classes You Create. The following example shows class
information in the Help browser for the user-created class,
sads,
displayed by running
doc sads
The Find dialog box is now available from the small help windows used for the Help on Selection feature and for context-sensitive help. The find feature is useful when you want to search for a specific word or phrase within one of these help windows. To access the Find dialog box:
In a window used for the Help on Selection feature,
press Ctrl+F on Windows and UNIX platforms
or Cmd+F on Macintosh platforms. You can also
click the Find text
button
In a context-sensitive help window, press Ctrl+F on Windows and UNIX platforms, and Cmd+F on Macintosh platforms
You can quickly access the Product Filter from the search field by selecting the down arrow at the right side of the search field and from it, selecting Filter by Product. The Help pane of the Preferences dialog box opens. For more information about the product filter, click the Help button in the dialog box.
As you enter a term in the search field, a history of terms you previously entered in the current session appears. To view the full history, select the down arrow at the right side of the search field and from it, select Show Search History. You can select an item in the search history to rerun the search.
To execute a search, enter the search terms and press Enter. There is no longer a Go button.
New features and changes introduced in Version 7.7 (R2008b) are:
The Current Directory browser includes new ways to navigate and to view the directory contents. There are also new ways to find files, including a new filter field.
Use the new address bar to view the current directory and to view and navigate to subdirectories within the current directory path.
Access common features from the Actions button
on the toolbar.
Add and remove buttons from the toolbar by right-clicking the toolbar and selecting Customize.
List only files whose names contain a specified string by using the new filter field. To show the filter field, use File > Preferences > Current Directory.
In the Details pane at the bottom of the tool, view a list of elements in the selected file, such as subfunctions in a MATLAB program file. Double-click an element to open the file at the location of the element.
For a MAT-file, drag selected variables from the Details pane to the Workspace browser to load them into MATLAB. Similarly, save workspace variables to a MAT-file by dragging them from the Workspace browser to the Current Directory browser.
Group items in the current directory, that is, view related items together. From the Actions button, select Group By and select the attribute you want to group by.
Some of the major changes are highlighted in the following illustrations.
For more information, see Managing Files in MATLAB.
The following aspects of using the Current Directory browser are different in Version 7.7 (R2008b) than in the previous version. Following is a table of what changed and the way to perform the same action in Version 7.7.
When you run
dir with an output argument
and the results include a nonexistent file or a file that
dir cannot
query for some other reason,
dir now returns
empty matrices for the
date,
bytes,
and
datenum fields. The most common occurrence
is on UNIX.
With empty matrices returned, code you write to use the results
of
dir can be simpler and more robust. For more
information, see the reference page for the
dir function.
In previous versions,
dir returned inappropriate
values for files that could not be queried:
r(n) = name: 'my_file' date: '18-Jan-2038 22:14:07' bytes: 0 isdir: 0 datenum: 7.4438e+05
If you have existing files that rely on the results of
dir for
a file that could not be queried, your code might not produce the
result it used to. If you write new code that depends on the new results
for
dir and run it in a previous version of MATLAB,
it might not produce the results you expect. In either case, there
will probably not be a warning or error.
Rearrange, add, or remove buttons and other controls from the Workspace Browser toolbar using File > Preferences > Toolbars. Alternatively, right-click the toolbar and select Customize from the context menu. By default, the Print button is not on the toolbar.
For more information on customizing the toolbar, see Toolbar Customization.
On UNIX platforms, MATLAB now uses a semicolon (;)
as the character that separates directories in the search path file,
pathdef.m,
which is the character used on Windows platforms. This is beneficial
if you work with the contents of the
pathdef.m file
programmatically on both Windows and UNIX platforms. In
versions prior to Version 7.7 (R2008b), MATLAB used the colon
(:) character as the path separator on UNIX platforms.
MATLAB will continue to accept the colon (:) character as a valid path separator on UNIX platforms, so any existing code you have that relies on it will still work.
You will experience a problem if you have any directories that contain a semicolon in their name. You will need to rename the directories to include them on the search path.
New features and changes introduced in Version 7.7 (R2008b) are:
When you create new functions and class definition files (
classdef),
you can start with a template that reminds you to include standard
information. Select File > New > Function M-File, or File > New > Class M-File. A new file containing template information opens in
the Editor.
While you enter statements in the Editor or Command Window, you can display the syntax for a function in a temporary pop–up window. For more information, see View Syntax Hints While Entering Statements.
You also can find the names of and get help for functions using the new Function Browser—for more information, see Find Function Names and Get Help Using the New Function Browser.
In the Editor, where you can enable a vertical line to indicate a right-hand text limit, you now can set the width and color of the line. Note that the default color for the line is now gray, instead of light red.
Set preferences for the line by selecting File > Preferences > Editor/Debugger > Display, which opens the Preferences dialog box.
Click Help in the Preferences dialog box for more information.
When you press the Home key, the cursor goes to the first nonwhite character on the current line. When you press the Home key twice, the cursor goes to the beginning of the line.
In versions prior to Version 7.7 (R2008b), the Home key always moved the cursor to the first column of the current line.
You can now suppress a specific M-Lint message throughout a
file by right-clicking on an M-Lint indicator that elicits the message,
and then from the context menu, selecting
Suppress All Instances
in this File.
For details, see Suppress
All Instances of a Message in the Current File in the MATLAB Desktop
Tools and Development Environment documentation. For information on
manually inserting the string that tells M-Lint to suppress the message
throughout the file, see the documentation for the
mlint function.
An M-Lint message now appears if you previously suppressed a
message using the
%#ok directive, and that message
no longer appears. This can result if the message is already suppressed
using preferences (File > Preferences > M-Lint), and the code has changed such that the message is
no longer generated, or if the rules M-Lint follows for generating
the message have changed. The new message is:
An M-Lint message was suppressed here, but the message no longer appears. Use the context menu to fix.
For an example, see the Suppressing All Messages on
a Line with mlint example in the
mlint function
documentation.
To open an M-Lint Message ToolTip using the keyboard, place the cursor over the marked code and press Ctrl + M. This feature is offered in addition to the identical behavior available when you use the mouse pointer to hover over code that is marked by M-Lint. For an example of viewing an M-Lint message in a ToolTip, see Check Code for Errors and Warnings in the MATLAB Desktop Tools and Development Environment documentation.
To fix a problem marked by M-Lint as having an automatic fix available, place the cursor over the marked code, and then press Alt + Enter. This feature is offered in addition to the identical behavior available when you use the context menu. For an example of using the M-Lint autofix feature, see Check Code for Errors and Warnings in the MATLAB Desktop Tools and Development Environment documentation.
By default, the Editor now supports code folding for single program, multiple data (spmd) blocks. For more information on code folding, see Code Folding — Expand and Collapse Code Constructs in the MATLAB Desktop Tools and Development Environment documentation.
The File and Directory Comparisons Tool now uses shades of colors to mark differences in the contents of two directories being compared. Light colors indicate files that differ and dark colors indicate subdirectories that differ. For details and an example, see Comparing Folders and Zip Files in the MATLAB Desktop Tools and Development Environment documentation.
In releases prior to Version 7.7 (R2008b), the same color intensity highlighted differences in both files and directories.
The Block Indent option will no longer be provided, starting in the next version of MATLAB. Currently, this option is available for M, Java, and C/C++ programming languages, when you select File > Preferences > Editor/Debugger > Language. To attain the effect of block indenting, you can use the No indent option and indent lines manually using the Tab and space keys.
If you have concerns about the pending removal of the Block
Indent option, please contact Technical Support at.
Starting in MATLAB 7.7 (R2008b), on Macintosh platforms,
you cannot use file browser GUIs to directly access contents of the MATLAB root
directory. For example, when you use File > Open from the Editor, you
cannot directly select a file located within
matlabroot.
For more information, see Contents of MATLAB Root Directory.
You now access Directory Reports by navigating to the directory
containing the MATLAB program files for which you want to produce
reports. Then, on the Current Directory browser toolbar, click the Actions down
arrow
and select the type of report you want
to run for all of the MATLAB program files in the current directory.
Note that these reports are now referred to as Reports, rather than
Directory Reports.
In versions prior to Version 7.7 (R2008b), you navigated to
the directory containing the MATLAB program files for which you
wanted to produce reports. Then, you clicked the Directory
Reports down arrow
on the Current Directory
browser toolbar.
New features and changes introduced in Version 7.7 (R2008b) are:
In versions prior to Version 7.7 (R2008b), when you published
a file that included a figure window, only the graph or figure was
included in the published document. Using the
figureSnapMethod option,
you can now specify that you want the window details included in the
published document. For details, see the
publish reference
page.
In versions prior to Version 7.7 (R2008b), you could publish LaTeX code in a published document as a code block, separate from the rest of your comments, if any. Now, you can publish LaTeX math symbols inline with the rest of your comments. For details, see Inline LaTeX Math Equations.
In versions prior to Version 7.7 (R2008b), there was a Cascading
Style Sheet setting on the Publish Configurations dialog
box (which you access by clicking the Publish down-arrow button
). This setting is now called XSL
File, to more accurately reflect the setting.
The Cascading Style Sheet setting on the Publish Configurations dialog box is now XSL File.
The
randn function
uses a new longer period random number algorithm as its default.
The new function
randi returns
random integers from a uniform discrete distribution.
The
@RandStream class allows you
to construct a random number stream object and set its properties.
For more information, see Random Numbers in
the MATLAB Mathematics documentation.
The
randn function
now produces different results than in previous releases. Because
the values returned by
randn are
intended to be random, this change should not affect most code.
rand and
randn now
draw from the same random number stream. In prior releases,
rand and
randn had
separate independent underlying random number streams. Since
rand and
randn now
access the same stream, using
randn will
affect subsequent values produced by
rand and
vice-versa. See Creating
and Controlling a Random Number Stream in the MATLAB Mathematics
documentation for more information.
bvp5c
lsqnonneg
For Windows, Intel Mac, and Linux platforms, MATLAB software supports the Intel Math Kernel Library (MKL) version 10.0.3.
When you create a histogram display using
hist and
place data tips in the plot in data cursor mode, they now snap to
the top center of the bin you attach them to. The data tip contents
have changed as well, and now consist of:
Number of observations falling into the selected bin
The x-value of the bin's center
The lower and upper x-values for the bin
For details, see Using Data Cursors with Histograms in the MATLAB Graphics documentation.
Data tips for histograms no longer display the x and y coordinates
of their locations and no longer snap to the four corners of the bins,
as they do for
bar plots. The data tips are also
larger, to accommodate the extra information.
This release introduces a new MATLAB class called a Map. An object of the Map class is an array of any MATLAB data type that supports lookup table functionality. Unlike most arrays in MATLAB that only allow access to the elements by means of integer indices, indices for Map containers can be nearly any scalar numeric value or a character string.
The following example creates a Map object that is an array
of strings. It is very much like any other string array except that
with each value of this array there is also
a lookup key associated with it. This particular
Map contains the names of capital cities in the United States. These
are the values of the Map object. Associated with each capital city
value is the US state that it resides in. These are the keys of the
Map object. You look up values in the Map using key indices. Call
the
containers.Map constructor
to create an array of six capital cities indexed by six US states.
(The capital of Alaska has purposely been entered incorrectly):
US_Capitals = containers.Map( ... {'Arizona', 'Nebraska', 'Nevada', ... % 6 States 'New York', 'Georgia', 'Alaska'}, ... {'Phoenix', 'Lincoln', 'Carson City', ... % 6 Capitals 'Albany', 'Atlanta', 'Fairbanks'});
Show the capitals of three of the states by looking them up
in the Map using the string indices
'Nevada',
'Alaska' and
'Georgia':
values(US_Capitals, {'Nevada', 'Alaska', 'Georgia'}) ans = 'Carson City' 'Fairbanks' 'Atlanta'
Correct the capital city of Alaska by overwriting the entry
at string index
'Alaska':
US_Capitals('Alaska') = 'Juneau'; US_Capitals('Alaska') ans = Juneau
The term
containers.Map refers to a
Map class
that is part of a MATLAB package called
containers.
For more information, see Map Containers in
the Programming Fundamentals documentation.
The
tic and
toc timing
functions now support multiple consecutive timings. Call
tic with
an output
t0 to save the current time as the starting
time for some operation. When the operation completes, call
toc with
the same
t0 as its input and MATLAB displays
the time between that particular tic and toc.
In the following example, MATLAB measures the time used by each function call and, at the same time, measures the time required for the overall operation:
t0 = tic; t1 = tic; W = myfun1(A,B); toc(t1) t2 = tic; [X,Y] = myfun2(C,W); toc(t2) t3 = tic; Z = myfun3(A,C,Y); toc(t3) toc(t0)
You can still call
tic and
toc without
any arguments. In this case,
toc just measures
the time since the most recent
tic.
The MException
getReport method has several
new options available in this release. You select these options when
you call
getReport. They give you more control
over the content and format of the information displayed or returned
by
getReport.
The
what function now includes package
information in its output display and a
package field
in the structure array that it returns.
List the packages used in the MathWorks Communications System Toolbox™:
s = what('comm'); s.packages ans = 'crc' 'commdevice' 'commsrc' 'commgui' 'commscope' 'commutils'
You can also call
what on a specific package
name to see what types of directories and files are in the package
directory.
In previous releases, the
addtodate function
supported modifying a date number by a specified number of years,
months, or days. In this release, you can also modify the date by
a specified number of hours, minutes, seconds, or milliseconds.
Add 2 hours, 45 minutes, and 17 seconds to the current time:
d1 = now; datestr(d1) ans = 12-Jun-2008 16:15:38 d2 = addtodate(d1, 2, 'hour'); d2 = addtodate(d2, 45, 'minute'); d2 = addtodate(d2, 17, 'second'); d2 = addtodate(d2, 3000, 'millisecond'); datestr(d2) ans = 12-Jun-2008 19:00:58
There are new syntaxes for the
pause function:
To see whether pausing is enabled or not, use one of the following commands:
pause query state = pause('query')
To return the previous pause state when enabling or disabling pausing, use one of the following:
oldstate = pause('on') oldstate = pause('off')
This release introduces a change in how you select the source to import using the Import Wizard. In previous releases, you could select and view the contents of any number of files within the wizard before choosing the one to import. As of this release, if you need to import from a different source (a specific file or the system clipboard) than the one you had originally selected, you must exit and restart the Import Wizard. This change gives the Import Wizard increased flexibility in handling different types of files, removes redundancy in the import process, and also removes a potential source of unexpected behavior from the product.
The user interface to the Import Wizard is very much the same as in previous versions of MATLAB. However, you should take note of the following changes:
The panel named Select Data Source,
that appears at the top of the Import Wizard preview dialog box in
earlier releases, is no longer available. As before, you select the
source file to import, or the clipboard, at the time you activate
the Import Wizard. This applies whether you use File > Import Data from the MATLAB Command Window menu or the
uiimport function
at the command prompt. To make a new file or clipboard selection,
click the Cancel button in any of the dialog
boxes, and then restart the Wizard.
Calling
uiimport without a file
name displays the following new dialog box. Choosing File opens
the Import Data dialog box. Selecting Clipboard opens
the wizard with the contents of the clipboard in the preview panel.
To import from the clipboard using the MATLAB menus, use Edit > Paste to Workspace instead of using File > Import Data , and then change the source to Clipboard. This method is preferred because it is more direct. The capability of switching from file to clipboard within the wizard is no longer supported.
The only way to make an array of function handles is to use a cell array. Attempting to create any other type of array of function handles is invalid. For the past several releases, MATLAB has issued a warning if you should attempt to put function handles into any type of array other than a cell array. As of this release, MATLAB throws an error instead of a warning when this is attempted.
Replace
A = [@sin @cos @tan]; ??? Error using ==> horzcat Nonscalar arrays of function handles are not allowed; use cell arrays instead.
A = {@sin @cos @tan};
If any of your program code attempts to create a regular array of function handles, this code will now generate an error.
issorted(x), where
x is
a complex integer, and
issorted(x,'rows'), where
x is
an ND array
In this case, a statement such as the following
issorted(int8(complex(1,2)))
now issues the error message
??? Error using ==> issorted ISSORTED on complex inputs with integer class is obsolete. Please use ISSORTED(DOUBLE(X)) or ISSORTED(SINGLE(X)) instead.
In this case, a statement such as
issorted(ones(3,3,3),'rows')
now issues the error message
??? Error using ==> issorted X must be a 2-D matrix.
If any of your program code attempts to use either of these types of statements, this code will now generate an error.
This release introduces a new keyword,
spmd,
that, although used solely by the Parallel Computing Toolbox (PCT),
may cause conflicts with MATLAB users as well. See spmd
Construct in the PCT release notes for more information on
this keyword.
Because
spmd is a new keyword, it will conflict
with any user-defined functions or variables of the same name. If
you have any code with functions or variables named
spmd,
you must rename them.
In the future, on 32-bit Windows systems, MATLAB will
not support MEX-files with a
.dll file extension.
See release note Do Not Use DLL File Extensions for MEX-Files for information
on how this might affect you.
When you pass two MATLAB objects to
isequal, MATLAB dispatches
to the
isequal method of the dominant object (see Object Precedence
in Expressions Using Operators). If the dominant object does
not overload
isequal, then MATLAB uses the
built-in version.
What is different with this release, is that MATLAB now
calls
isequal explicitly for each contained object.
This means that, if any contained object overloads
isequal, MATLAB calls
the overloaded version for that object.
Previously, MATLAB compared contained objects using the
built-in
isequal functionality without regard to
any special behavior programmed into overloaded
isequal methods.
The effect of this change is that, for objects that contain other
objects and those contained objects overload
isequal,
the overloaded behavior establishes the basis with which MATLAB determines
equality for those contained objects.
The behavior of indexed assignment with MATLAB objects
is consistent with the behavior of all MATLAB intrinsic types
and V5 MATLAB objects. For example, attempting the following
assignment, where
d does not previously exist,
gives an error:
>> d(:) = 5; ??? In an assignment A(:) = B, the number of elements in A and B must be the same.
MATLAB objects behave in the same way:
ts_obj = timeseries; t(:) = ts_obj; ??? In an assignment A(:) = B, the number of elements in A and B must be the same.
In MATLAB Version 7.6 Release 2008a, indexed assignment
of the form
p(:) = object did not result in an
error.
'vaxd' or
'd'
'vaxg' or
'g'
'cray' or
'c'
Going forward, MathWorks is planning to leverage
existing operating system (OS) support for printer drivers and devices.
As a result, the ability to specify certain print devices using the
saveas command,
will be removed in a future release.
print -dcommand, and certain graphics formats using the
print -dcommand and/or the
The following Web site provides more detailed information on the file types that will issue warnings and how to suppress the warnings if desired, as well as a form to provide feedback to MathWorks about your use of these options:
If you start MATLAB with
matlab -nojvm (which
disables Java) you will receive a warning when you attempt to
create or load figures, open GUIs, print or capture figures using
getframe.
For information, see Changes to -nojvm Startup Option in the Desktop Tools and Development Environment release notes.
The following set of deprecated functions, all of which were previously undocumented, have been removed. Alternatives to most of them exist, which are described.
axlimdlg — No alternative
cbedit — No alternative
clruprop — Use
rmappdata instead
ctlpanel — No alternative
edtext — Set text object's
Editing property
extent — Get text object's
Extent property
getuprop — Use
getappdata instead
hidegui — Set figure's
HandleVisibility property
hthelp — Use
web instead
layout — No alternative
matq2ws — Combine
save +
load or
uisave +
uiload
matqdlg — Combine
save +
load or
uisave +
uiload
matqparse — Combine
save +
load or
uisave +
uiload
matqueue — Combine
save +
load or
uisave +
uiload
menubar — The string
'none'
menuedit — No alternative
pagedlg — Use
pagesetupdlg instead
setuprop — Use
setappdata instead
umtoggle — Set uimenu's
Checked property
wizard — Use
guide instead
ws2matq — Combine
save +
load or
uisave +
uiload
If you have developed MATLAB code that uses any of the above undocumented functions, you must remove such calls or replace them with other code, as suggested within the above bullets.
If you start MATLAB with
matlab -nojvm (which
disables Java) you will receive a warning when you attempt to
create or load figures, open GUIs, print, or capture figures using
getframe.
For more information, see Changes to -nojvm Startup Option in the Desktop Tools and
Development Environment release notes.
Two new menu options in GUIDE let you hide/show the GUIDE toolbar and status bar. By default both are visible, but you can deselect Show Toolbar, Show Status Bar, or both from the View menu to make the layout area larger.
The GUIDE Preferences option Show Toolbar is no longer available. Use Show Toolbar from the GUIDE View menu instead.
The GUIDE Layout Editor now shows the
Tag property
of any object you select, in the left corner of the status bar that
runs along its bottom. This display saves you from having to open
the Property Inspector to read
Tag names. Information
in the status bar is read-only; you still need to use the Property
Inspector to change a component's
Tag.
The Creating Graphical User Interface documentation has four new extensive examples of building GUIs with GUIDE and programmatically. All of them feature uitables, a feature introduced in R2008a, and all the GUIs plot data. The new examples are:
A Working GUI with Many Components (GUIDE)
GUI for Animating a 3-D View (GUIDE) (GUIDE)
GUI to Interactively Explore Data in a Table (GUIDE) (GUIDE)
GUI that Displays and Graphs Tabular Data (programmatic)
This release includes FIG- and code files for all these examples. The documentation discusses many of their callbacks and includes hyperlinks to code in the code files. to release memory for an
mxArray MATLAB functions an
.m file.
For an overview of the major new features in the MATLAB Desktop Tools and Development Environment area, watch this video demovideo demo. You can also access this and other video demos by selecting the Demos tab in the Help browser, and then selecting MATLAB > New Features in Version 7.6.
New features and changes introduced in Version 7.6 (R2008a) are: Default Startup Directory (Folder) on Windows Platforms
and the
userpath reference
page.
In previous versions, MATLAB automatically added the
My
Documents/MATLAB directory (or
Documents/MATLAB on Windows Vista platforms)
to the search path upon startup, even if you had removed it from the
path and saved your changes during the previous session.
On UNIX.
In previous versions, no directories were added to the search path upon startup.
On Apple Macintosh <trademark Macintosh Platforms
and the
userpath reference
page. Startup Options..
MATLAB is now using Sun Microsystems JVM Version 6 on the Sun Microsystems Solaris platform.:
Rearrange, add, or remove buttons and other controls from the MATLAB desktop or Editor toolbars using File > Preferences > Toolbars. Alternatively, right-click a toolbar and select Customize from the context menu.
For more information, see Toolbar Customization. Software Updates.
The default value for the Command History preference, Save
after
n commands, is now 1.
This allows you to more easily rebuild your state in MATLAB if MATLAB terminates
abnormally, such as after a power failure. For more information about
this preference, see Command History
Preferences. Preferences.
.
Use the new function,
userhome/Documents/MATLAB Locations
for Storing Your Files and the
userpath reference
page. Folders for details.
If your system uses Intel multi-core chips, and you plan to profile using CPU time, set the number of active CPUs to 1 before you start profiling. See Intel Multi-Core Processors — Setting for Most Accurate Profiling on Windows Systems for details.
New features and changes introduced in Version 7.6 (R2008a) are:
The MATLAB stand-alone Editor (
meditor.exe)
is no longer provided. Instead of the stand-alone Editor, you can
use the MATLAB Editor..
You now use the Run button to execute a run configuration and the Continue button to continue execution of an M-file after a breakpoint during debugging. See Run MATLAB Files in the Editor and Step Through a File for details.
The Evaluate Entire File button,
, is no longer on the
Editor Cell Mode toolbar by default. — Expand and Collapse.
With the introduction of nested cells, cells definitions result in cell highlighting that looks different from previous releases. See Define Code Cells for details.
New features and changes introduced in Version 7.6 (R2008a) are: a MATLAB File. Mark Up MATLAB Code for Publishing and Evaluate Subsections of Files Using Code Cells. Nested Code Cells for details.
The Publish button,
, is now located on the Editor toolbar. Trademark Symbols Force
a Snapshot of Output.
On Microsoft Windows systems, users can select the
Pashto language with the Afghanistan country code. This locale setting
is
ps_AF.1256.
On Apple Macintosh OS X systems, for users selecting
the Chinese language and the China country code, the locale setting
is
zh_CN.gb2312. The previous setting was
zh_CN.GBK.
MATLAB software now uses new versions of the Basic Linear Algebra Subroutine (BLAS) libraries. For Windows, Intel Mac, and Linux platforms, MATLAB software supports the Intel Math Kernel Library (MKL) version 9.1. For the Solaris platform, MATLAB software uses the Sun Performance Library from Sun Studio 12.
MATLAB software now uses Version 3.1.1 of the Linear Algebra Package (LAPACK) library.
Multithreaded support has been added to elementwise math functions
that may generate warnings:
rdivide,
ldivide,
log,
log2,
and
rem.
The
ldl,
logm, and
funm functions
include new algorithms based on recent numerical methods research.
This release introduces two new interactive tools for data exploration:
Data brushing — For marking observations on graphs, allowing you to remove or save them to new variables
Data linking — For connecting graphs with data sources (workspace variables) to automatically and interactively update them
In addition, figure windows have a new banner, called the linking and brushing message bar. By default, when you plot data into a figure (i.e., add axes), an informational banner appears across top of the figure that looks like this.
In the figure's message bar, click the first two links to read
about these new tools. Click the Play video link
to open a nine-minute video
tutorialvideo
tutorial about the tools in a browser window (the video also
describes new GUI-building features.) To dismiss the banner, click
the
X. Once you do, the
banner only reappears on subsequent plots if you select Show
linking and brushing message bar in the MATLAB Preferences
Confirmation Dialogs panel.
Use data brushing when you want to isolate observations in a 2-D or 3-D graph for separate analysis, or to remove outliers or noisy data points. Data brushing can be applied to most graphs (some plot types do not support brushing). Data brushing is an exclusive, persistent mode. That is, when using it, you cannot use other figure tools, but the results of brushing data persist when you select a different tool or no tool.
Use data linking to make plots dynamically respond to changes in the variables they plot. Data linking applies to most graphs with identifiable data sources and operates at the figure level. Data linking is not modal and persists until you toggle it off or the connection between a plot and its data sources is broken.
The two tools work smoothly together and with the Variable Editor to visually highlight brushed observations and the data values they represent:
Brushing data-linked observations on a graph highlights them on other graphs that display them.
Brushing highlights values in the Variable Editor when a brushed variable is displayed there.
Using the Brush tool in the Variable Editor highlights values you brush that appear in linked plots.
Changing values of variables causes linked graphs displaying them to update with the changes.
Clearing variables disconnects them from all linked figures displaying graphs of them
You can modify variables from the command line, the Variable Editor, or with M-files. When used within functions, data linking operates in the function's workspace, not the base workspace. This is also the case when debugging.
All figure windows that contain axes now include a data brushing
tool (the Brush/Select data icon
) that lets you enter and exit brushing
mode and select a color with which to brush observations. The tool
draws selection rectangles (in 2-D plots) or prisms (in 3-D plots)
and permits you to select discontiguous regions and negate previously
brushed observations. Undo is also supported.
The Brush/Select data tool is a "split button" control with a brush icon on the left and a drop-down color palette on the right. When you depress the brush icon, you are in brushing mode; all data observations you select are highlighted with the current brush color. The figures below illustrate these operations.
If you leave data brushing mode to zoom, pan, or edit the plot, all brushed observations remain highlighted. You can then reenter brushing mode and pick up where you left off. Brush marks are not preserved when you save a figure and reopen it from the FIG-file, however.
Use the
brush function
to turn brushing on and off, and to select a color for brushing graphs.
You can change brush colors on the fly with either the API or with
the Brush tool.
All figure windows that contain axes now include a data linking
tool (the Linked Plots button
) to toggle linked mode
on and off (the default). When you toggle it on, an information bar
appears underneath the lowest toolbar on the figure, as shown below.
It displays what variables are linked to each series (data sources
for x-, y-, and z- data
in the graphs).
On the left side of the information bar is a drop-down menu
that displays the symbolism and identifies
the data source for each series currently linked. On the right side
is an Edit button that opens the Data Source
Properties dialog box in which you can set display names and data
sources. Usually it is possible to unambiguously determine what data
sources a graph has, but sometimes you need to indicate what data
source to use, for example, when you plot a subrange of a data array.
The information bar explains that you need to do this as soon as you
turn on data linking; then, you can open the Data Source Properties
dialog box to identify your data source(s).
Use the
linkdata function
to turn data linking on or off for the current figure or for a figure
for which you supply a handle.
If you capture figure windows with the
getframe function,
their images will include the message bar if the figures being captured
possess them. To prevent this from happening, click the X on
the right side of the message bar to dismiss it before calling
getframe.
Subsequent figures will not display a message bar. If you want to
restore the message bar at a later time, select Show linking
and brushing message bar in the MATLAB Preferences
Confirmation Dialogs panel.
If the figure has a title, its Linked Plots/Data Brushing message bar can obscure it. This is the case for figures at the default size. Remove the message bar if you want a title to display.
Multithreaded computations, introduced in R2007a, are now on by default.
To disable multithreaded computations, open the Preferences dialog, choose Multithreading, and then disable it explicitly.
Major enhancements to object oriented programming capabilities enables easier development and maintenance of large applications and data structures.
New features include:
The new
classdef keyword enables
you to define properties, methods, and events in a class definition
file. See User-Defined
Classes.
A new
handle class with reference
behavior enables you to create more sophisticated data structures,
such as linked lists and to manage external resources, such as files.
See Comparing
Handle and Value Classes.
Events and listeners enable you to monitoring object property changes and other actions. See Events — Sending and Responding to Messages.
Packages enable scoping of classes and functions. See Create a Namespace with Packages.
Meta-classes provide support for class introspection. See Information from Class Metadata.
JIT/Accelerator support provides significantly improved performance over the previous object oriented-programming system.
For a full description of object-oriented features, see Object-Oriented Programming.
This release provides the capability to manage name space by placing classes and functions in packages.
The new
memory function
provides memory usage information such as largest block available,
allowing you to diagnose memory problems on Microsoft Windows platforms.
The memory function existed in previous versions of MATLAB,
but its purpose has changed. Previously,
memory provided
help text on how to free additional memory space for your MATLAB application.
The function now returns information on the current state of memory
use and availability in your system.
JIT/Accelerator support now extends to statements executed at the MATLAB Command Line and in cell mode in the MATLAB Editor. This provides improved performance in these environments.
The image information and writing functions have the following enhancements:
imfinfo can
now return Exif data for JPEG or TIFF format image files. Information
specific to the digital camera can be found in the
'DigitalCamera' field,
while any global positioning system information can be found in the
'GPSInfo' field.
imwrite now
supports the
'RowsPerStrip' parameter that you
can use to specify how many image rows to include in a strip when
writing TIFF files. By default,
imwrite limits
the number of rows included in a strip so that the size of the strip
does not exceed 8 KB. Now you can specify strips of larger size.
Some of the chapters in the MATLAB Programming documentation have been moved or renamed in this release. Also the title of the Programming documentation has been changed to Programming Fundamentals in order to differentiate this part of the MATLAB help from the new documentation on Developing MATLAB Classes.
Two new toolbar buttons and an information bar have been added in this release that control the new Data Brushing and Data Linking tools. Brushing and linking let you interactively explore and analyze data.
By default, now when you create axes or plot something into a blank figure, an informational banner appears across top of the figure with links to documentation for data brushing and linking capabilities. You can dismiss it by clicking the X button on right-hand side of the message bar. Once you dismiss it, subsequent figures will not display the banner unless you select Show linking and brushing message bar in the MATLAB Preferences Confirmation Dialogs panel.
For more information, see Data Brushing for Graphs and Linked Variables in the Data Analysis release notes and Interactive Data Exploration in the Data Analysis documentation. Also view the video tutorialvideo tutorial that describes these and other new features.
The Version 7.5 (R2007b) release note The "v6" Option for Creating Plot Objects is
Obsolete identified
plotting functions that accept the
v6 option, which
is now obsolete and will be removed in a future version of MATLAB.
There is no change to the status of these functions in R2008a. However,
the list of affected functions in the R2007b release note had errors
and omissions. Below is the correct list of functions that support
the option in their syntax and now warn when it is used:
Note that the updated list adds functions
plot3 and
quiver3.
In the earlier release note, the following functions were incorrectly
identified as accepting the
v6 option:
These functions do not call
v6 code
and are not affected by it becoming obsolete..
The new
uitable component allows you to show
data in a table. This component replaces the undocumented MATLAB
uitable implementation.
If you are using the old
uitable component, please
refer to the uitable
Migration Document for help migrating to the supported
uitable component.
Auto-generated callbacks of GUIDE GUIs can now access event data for Handle Graphics callbacks. The following Handle Graphics callbacks provide event data when triggered:
KeyPressFcn in
uicontrol and
figure
KeyReleaseFcn in
figure
SelectionChangeFcn in
uibuttonGroup
WindowKeyPressFcn in
figure
WindowKeyReleaseFcn in
figure
WindowScrollWheelFcn in
figure
CellEditCallback in
uitable
CellSelectionCallback in
uitable
For example, the event data for keypress provides information on the key that is pressed. See the Callback Templates documentation for more information.
Starting in R2007b, the
uigetfile and
uiputfile functions
interpret
'.',
'..', and
'/' the
same way as does the
cd command.
'.' is
interpreted as the current directory,
'..' is the
directory above the current directory, and
'/' is
the top level directory. When specifying a directory rather than a
filename for either the
Filterspec or
DefaultName argument,
you no longer need to end the string with a
'/'.
However, such strings ending with a
'/' are interpreted
as they were in previous releases.
The hidegui function is being obsoleted and will be removed
in a future version. Instead of this function use the
set function
to set the figure handle's
handlevisibility property
to
on or
off:
set(figurehandle, ‘handlevisibility', 'on')
SelectionType is
a figure property that user interface components set when you click
them. It is a read-only property that describes the gesture used when
clicking the most recently selected object. For single mouse clicks,
components no longer set the figure
SelectionType property
to anything but
'normal' when they are enabled.
By default, all components are enabled (their
Enable property
is
'on'). Previously, enabled components responded
to modifier keys (Ctrl, Alt, Shift,
and Cmd) by setting
SelectionType to
'alt' or
'extend'.
Now all key modifiers set
SelectionType to
'normal' for
UI components.
Disabled components (those with their
Enable property
set to
'off') set
SelectionType to
'alt' or
'extend' in
response to modifier keys.
When
Enable is
'on',
the control is active and your
Callback responds
to clicks. When
Enable is
'off',
the control is not active, and your
ButtonDownFcn responds
to clicks. You can provide components with a
ButtonDownFcn to
detect changes in
SelectionType.
An additional change affects how list box
uicontrol components
respond to double-clicking. The second of two successive clicks sets
the
SelectionType property of an enabled list
box to
'open'. Other types of uicontrols set their
SelectionType to
'normal' after
both the first and the second clicks unless key modifiers were used.
The following table describes the click responses for
uicontrol components.
* Double-click
result is
'open' for list boxes.
For a two-button mouse, pressing the left and right buttons
together (without key modifiers) can set
SelectionType to
either
'normal' or
'extend';
the results are unpredictable, possibly depending on which button
you actually depressed first.
uipushtool and
uitoggletool toolbar
buttons do not set
SelectionType at all, no matter
what keys or mouse buttons you press. When they are disabled,
uipushtool and
uitoggletool controls
do not execute their
ClickedCallback (or
OnCallback/
OffCallback),
nor does using them trigger a
WindowButtonDownFcn callback.
If your callback code depends on the value for
SelectionType,
be aware that for the left mouse button, pressing Ctrl no
longer sets it to
'alt' and that Shift-clicking
no longer sets it to
'extend'.
The
SelectionType behavior for the right
mouse button has not changed.
The ability to load a generic DLL on 64-bit platforms using
loadlibrary is
available in MATLAB Version 7.6 (R2008a).
You must install a C compiler and Perl to use this feature. For a list of supported compilers and how to install them, see Using loadlibrary on 64-Bit Platforms.
The set of compilers that MATLAB supports has changed in MATLAB Version 7.6 (R2008a). For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
MATLAB Version 7.6 (R2008a) supports new compilers for building MEX-files.
Microsoft Visual Studio 2008
Windows SDK for Vista
Intel Visual Fortran 10.1
Microsoft Visual Studio 2008
Open Watcom Version 1.7
Intel Visual Fortran 10.1
Sun Studio 12 cc / CC Version 5.9
Apple Xcode 3.0 (gcc / g++ Version 4.0.1)
The following compilers are no longer supported.
Intel C++ Version 7.1
Intel Visual Fortran Version 9.0
Borland® C++Builder® 6 Version 5.6
Borland C++Builder 5 Version 5.5
Borland C++ Compiler Version 5.5
Compaq Visual Fortran Version 6.1
Compaq Visual Fortran Version 6.6
To ensure continued support for building your C/C++ programs, consider upgrading to another supported compiler. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
The following compilers are supported in Version 7.6 (R2008a), but will not be supported in a future version of MATLAB.
Open Watcom Version 1.3
Sun Studio 11 cc / CC Version 5.8
MATLAB Version 7.6 (R2008a) includes Perl on Windows Version 5.8.8.
Prior to this release, MATLAB contained Perl Version 5.005. Consult your Perl documentation for details on the changes between Perl versions.
MATLAB V7.6 (R2008a) on Linux platforms is built with
a compiler that utilizes
glibc Version 2.3.6.
To work with MATLAB V7.6 (R2008a), MEX-files compiled on a Linux platform must be rebuilt.
may result in a segmentation violation. may cause memory leaks and will be deprecated in a future
version of MATLAB:
propertyValue = get(javaObject, 'PropertyName'); set(javaObject, 'PropertyName', newValue);
The correct commands to use are:
propertyValue = javaObject.getPropertyName; javaObject.setPropertyName(newValue);
In future versions of MATLAB, using
get or
set on Java objects
to manage the properties will generate an error.
You can read and modify properties of MATLAB class objects
using the
mxGetProperty and
mxSetProperty functions.
Beginning with MATLAB Version 7.3 (R2006b), the Windows script
mex.bat is
located in the directory
.
Copies of this file were also in the directory
matlabroot\bin
.
In MATLAB Version 7.6 (R2008a),
matlabroot\bin\
$ARCH
mex.bat is
only located in
.
matlabroot\bin
If you did not make the updates described in Location of mex.bat File Changed, you may need to make changes now. Microsoft® utilize the new API. You should review your source MEX-files and
mex build
scripts.
In MATLAB Version 5.1, all development work for the Dynamic Data Exchange (DDE) server and client was stopped. MathWorks provides, instead, a MATLAB interface to COM technology that is documented in Using COM Objects from MATLAB .
Documentation for the following functions no longer included in External Interfaces.
The following syntax for
enableservice no
longer included in External Interfaces.
enableservice('DDEServer',enable)
If you must support this obsolete functionality, we suggest you print and keep a copy of the relevant MATLAB function reference pages from V7.5 (R2007b) or earlier. Open and Rearrange Desktop Tools and Documents.
directory.
matlabroot/toolbox/matlab/icons
If your code relied on icon files in the
directory
(for example, for adding your entries to the Start button
or the Help browser), you might need to use other image files.
matlabroot/toolbox/matlab/icons
MATLAB now follows the operating system's font settings on Microsoft and Macintosh platforms. This provides smooth fonts without the need for antialiasing within MATLAB.
New features and changes introduced in Version 7.5 (R2007b) are: Quick Search for Entries Beginning with Specified Letters or Numbers.
For more information, see Help on Selection Enhanced in Command Window and Editor.
New features and changes introduced in Version 7.5 (R2007b) are:. To change the window in which this help appears, select File > Preferences > Help, and adjust the option for Help on Selection and More Help. Run
Files with Input Arguments in the Editor.
The Run/Continue button has a new look and new location on the Editor/Debugger toolbar. now supports Microsoft Word for Office 2007. For details, see Creating a MATLAB.
MATLAB software now uses Version 3.1 of the Linear Algebra Package (LAPACK) library.
For AMD® processors, MATLAB software now uses Version 3.6 of the AMD Core Math Library (ACML™) for the Basic Linear Algebra Subroutine (BLAS) libraries.
The binder library,
libmwlapack.lib, containing
both LAPACK and BLAS symbols is now two separate library files:
libmwlapack.lib for
LAPACK symbols and
libmwblas.lib for BLAS symbols.
If you previously linked to the
libmwlapack.lib library
to use the BLAS symbols, you will need to update your code to link
to the
libmwblas.lib library.
Using a colon with characters to iterate a for-loop now returns data of type character. For example,
for x='a':'b',x,end
x = a x = b
Previously, colon operations with characters iterating a for-loop returned data of type double. In previous releases the above example returned:
for x='a':'b',x,end x = 97 x = 98
Calling matrix generating functions, such as
ones,
zeros,
rand,
randn,
true,
and
false, with a complex number as dimensions
input now returns the error:
true([1 i]) ??? Error using ==> true Size vector must be a row vector with real elements.
In previous releases, if you supplied a complex number as a dimension input, MATLAB software returned:
true([1 i]) Warning: Size vector should be a row vector with integer elements. Complex inputs will cause an error in a future release. ans = Empty matrix: 1-by-0
On 64-bit platforms, MATLAB arrays are no longer limited to 231 elements. The limit in MATLAB 7.5 is 248-1. For example, given sufficient memory, many numeric and low-level file I/O functions now support real double arrays greater than 16 GB.
Documentation for "Multiprocessing in MATLAB" has moved from Desktop Tools and Development Environment to the "Improving Performance and Memory Usage" section of MATLAB Programming.
In this release, MATLAB provides a way to set or retrieve
the maximum number of computational threads from within an M-file
program. With the
maxNumCompThreads function,
you can either set the maximum number of computational threads to
a specific number, or indicate that you want the setting to be done
automatically by MATLAB
P-code files have a new internal format in MATLAB Version 7.5. The new P-code files are smaller and more secure than those built with MATLAB 7.4 and earlier, and provide a more robust solution to protect your intellectual property.
Any P-code files that were built using MATLAB 7.4 or earlier also work in 7.5. However, support for these older files will at some point be removed from MATLAB.
P-code files built with MATLAB 7.5 only work on 7.5 or later. They cannot be used with MATLAB 7.4 or earlier versions.
Rebuild any P-code files using MATLAB 7.5 that you expect to need in the future.
Using the regular expressions function
regexp,
you can now split an input string into sections by specifying the
new
'split' option when calling
regexp:
s1 = ['Use REGEXP to split ^this string into ' ... 'several ^individual pieces']; s2 = regexp(s1, '\^', 'split'); s2(:) ans = 'Use REGEXP to split ' 'this string into several ' 'individual pieces'
The
split option returns those parts of the
input string that are delimited by those substrings returned when
using the
regexp
'match' option.
MATLAB extends its error-handling capabilities with the
new
MException class to provide you with a more
secure and extensible system for throwing and responding to errors.
Read about this new feature in the Error Handling section
of the MATLAB Programming documentation and in related function
reference pages such as
MException.
This feature extends the error-handling capabilities available in earlier releases, but does not replace that functionality. Your M-file programs will continue to function the same when using Version 7.5.
As part of new error-handling mechanism, the
catch function
has a new, optional syntax as shown here in a try-catch statement:
try % Try to execute this block of code. Go to 'catch' on error - code that may error - catch ME % Deal with the error captured in MException object, ME - code to handle the error - end
ME is an object of the
MException class.
This command gives you access to the
MException object
that represents the error (i.e., exception) being caught.
In previous versions of MATLAB, warning and error messages that were longer than the width of your terminal screen extended beyond the visible portion of your screen. These messages now wrap onto succeeding lines so that the entire text of the warning or error is visible.
The error message and M-file line number that MATLAB displays
when encountering an error in an anonymous function defined within
a script file or at the MATLAB Command Line has changed in this
release. In MATLAB Version 7.4, the error message included the
line number (set to
1 for anonymous functions),
and the stack information returned by the
lasterror function
also showed the line number as
1. In MATLAB 7.5, the line number is not displayed
in the error message and is set to
0 in the returned
stack information.
For example, when you enter the following two lines at the command line, MATLAB generates an error from the anonymous function:
X = @() error('* Error *'); X()
This example shows the difference between MATLAB Versions 7.4 and 7.5:
e = lasterror; e.message ans = Error using ==> @()error('Error') at 1 % V7.4 response Error using ==> @()error('Error') % V7.5 response * Error * e.stack ans = file: '' name: '@()error('* Error *')' line: 1 % V7.4 response line: 0 % V7.5 response
If you have programs that rely on the line number returned in response to an error in an anonymous function, these programs may not work as expected. Remove dependencies on the returned error message and line number, or update your program code to use the new string and value.
MATLAB now displays a more user-friendly message when you press Ctrl+C. The previous response to Ctrl+C was
Error in ==> testctrlc>waitawhile at 5 pause(100); Error in ==> testctrlc at 2 waitawhile
In this and future releases, pressing Ctrl+C still halts program execution, but now displays the response
??? Operation terminated by user during ==> testctrlc> waitawhile at 5 In ==> testctrlc at 2 waitawhile
You only need to be aware that the change in the text of this message is intentional and does not signify any error on your part.
In previous releases,
hdfread issued
a warning when a requested I/O operation failed. In addition,
hdfread created
an empty variable in the workspace. In this release,
hdfread now
errors when a requested I/O operation fails and does not create an
empty variable in the workspace.
If you call
hdfread in a script to perform
an I/O operation and that operation fails, your script will now terminate.
Previously, because
hdfread only warned when
an I/O operation failed, your script would continue processing.
C:\Temp\tpe51f2ba3_9ad3_490f_8142_58359c98f4a5
when Java is present, or a string like
C:\Temp\tp346976948758473
when
nojvm is selected. Underscores are
included in the name so you can use the filename portion of it as
a valid M-function name. If a string row vector is passed in as an
argument, that string is used instead of
tempdir as
the root.
Because the new string generated by
tempname is
generally longer than the string constructed in earlier versions,
there is a possibility of exceeding length restrictions, especially
if your program code passes a string to the
tempname function.
If you consider this to be a potential problem, verify that the strings
you pass to
tempname will not result in an overly
long string being returned.
MATLAB now includes two new functions that validate the input arguments passed to functions. For example, you can use these functions to make sure that an input argument is numeric and nonempty. The following table lists these functions with a brief description.
On Windows, you can define a current working directory,
cwd,
for each drive letter. For example, entering the command
cd
D:\work at the DOS prompt defines your
D current
working directory as
D:\work. All references to
D: are
then relative to this directory.
(Note the difference between
D:\ and
D:,
where the former is the drive
D, and the latter
is a user-defined working directory that may or may not be equal to
D:\.)
Previous versions of MATLAB have been inconsistent in the
way that volume-relative path specification is handled. For example,
in MATLAB 7.4 and earlier, if
D: were defined
as the directory
D:\work, the following commands
on the left and right returned identical results:
dir D: dir D:\ dir D:matlab dir D:\work\matlab fileparts('D:myfile.m') fileparts('D:\myfile.m')
This has been fixed in MATLAB 7.5 so that the following are now equivalent:
dir D: dir D:\work dir D:matlab dir D:\work\matlab fileparts('D:myfile.m') fileparts('D:\work\myfile.m')
Some MATLAB commands may fail or return unexpected results if you use Windows current working directories on MATLAB. You might have to update hard-coded paths if you have been relying on the incorrect behavior exhibited in earlier versions.
Because Windows Vista, Windows Vista 64-bit, and Windows XP x64
operating systems do not ship with the Indeo® 5 codec, which
is the default codec used by MATLAB Audio-Video functions for file
compression, the functions
movie2avi and
avifile now
generate uncompressed AVI files on these platforms. Also,
aviread on
these platforms cannot read files that were compressed using the Indeo 5
codec.
If you have upgraded your Windows operating system to Windows Vista, Windows Vista 64-bit,
or Windows XP x64, you need to install the Indeo 5 codec
to read or create Indeo 5 compressed AVI files with
aviread,
avifile,
or
movie2avi.
You can learn more about downloading the Indeo 5 codec from
the Ligos Corporation Web site at
The
mmfileinfo function
now reads files on the MATLAB path, not only those in the current
directory. The
mmfileinfo output struct contains
a field called
Path, which indicates the directory
where the file exists.
The
Filename field of the output struct from
mmfileinfo now
contains only the filename itself without any path information, while
the path information is contained in the
Path field.
In previous releases, the
Filename field contained
both path and filename information.
imread reads TIFF files that
use JPEG, LZW, and Deflate compression.
imread reads image data from
TIFF files in any arbitrary samples-per-pixel and bits-per-sample
combination.
imread provides increased performance
when reading large images, when used with the 'PixelRegion' parameter.
The
freeserial function is now obsolete.
Use
fclose to release the serial port.
If your program code still makes use of the
freeserial function,
replace each instance with the
fclose function
instead.
When you save a figure, all datatips existing in it are saved along with other annotations. When you open the FIG-file, the datatips are displayed and can be manipulated or deleted in the same ways they could in the original figure.
If you open a FIG-file containing datatips while using a previous MATLAB version (V7.4 or earlier), no error results, but the datatips do not display.
You can now customize how legends for figures display groups of lines, such as contours. Previously, legends displayed groups of lines such as contourgroups with a glyph that represented the entire group; now users have the flexibility to designate a single legend entry, a legend entry for each child of the group, or no legend entries for the group.
By default, a legend entry for an hggroup now consists of the
DisplayName of
its first child and a glyph representing it (previously, no glyph
appeared, only the
DisplayName). This is what
you now see after clicking the legend tool icon in the figure's toolbar.
However, you can set the new
Annotation property
of hggroups to control how the group is represented in a legend. For
details and examples of its use in customizing legends, see Controlling
Legends in the Graphics documentation.
The
drawnow command can now selectively update
the display of UI components. The
update option
enables you to update only uicontrol objects without allowing callbacks
to execute or processing other events in the queue.
In previous releases, textboxes had fixed sizes that users needed
to adjust to fit the size of their contents. Now, if you create a
textbox annotation using a GUI or the
annotation function,
it can grow or shrink to just fit the text you type into it. This
behavior is controlled by the Annotation Textbox object's
FitBoxToText property,
which can be
'on' or
'off'.
When you create a textbox with the Annotation toolbar (using the
tool), this property is set to
'on' if
you create a textbox without dragging; however, if you drag to make
the new textbox have a certain size, the property is initially
'off'.
When you create a textbox with the annotation function, for example,
htb = annotation('textbox')
FitBoxToTextset to
'on'. If you specify a position vector in the command, for example,
htb = annotation('textbox', [.1 .8 .4 .1])
FitBoxToTextset to
'off'.
Similarly, if you resize a textbox in plot edit mode or change
the width or height of its
position property
directly, its
FitBoxToText property is set to
'off'.
You can toggle this property with
set, with the
Property Inspector, or more conveniently, via the object's context
menu, as the illustration below shows.
If you edit a textbox that has
FitBoxToText set
to
'on', the textbox resizes to accommodate the
number of characters and lines in the text as you type. You can reposition
the textbox without changing the
FitBoxToText property,
but as soon as you resize it, the property becomes (or remains)
'off'.
When you use the Property Inspector (the
inspect command),
you can now ask for a description of any property it shows. The descriptions
come from the property reference page for the type of object being
inspected (e.g., axes, lineseries, annotations, uicontrols, etc.).
To get a description of a property, right-click its name in the left-hand
column of the Property Inspector and select What's This? from
the context menu that appears. A mini-help window opens to show the
property's description from the object's property reference page.
If you need an overview of all properties pertaining to particular
kinds of objects and how these objects relate, scroll through the
entries in the mini-help window or open the Handle Graphics Property
Browser from the Help Browser.
Prior to MATLAB Version 7, handles returned by high-level
plotting functions referenced graphic primitives, such as lines and
patches. In Version 7, MATLAB began bundling the primitives into
"series" objects, for example, lineseries, barseries,
and contourgroups. At that time, the
v6 option
was added to plotting functions to enable users of MATLAB Version
7.x to create FIG-files that previous versions can open. The
v6 option
is now obsolete. It will be removed in a future MATLAB release.
The following functions include the option in their syntax and now
warn when it is used:.
In previous releases, adding toolbars to a GUI had to be done
programmatically, by writing code for the
uitoolbar,
uipushtool and
uitoggletool functions.
GUIDE now has a Toolbar Editor and an associated Icon Editor that
allow you to lay out a toolbar for a GUI and populate it with standard
predefined tools for printing, saving, panning, zooming, annotating,
etc. or with custom tools that you design yourself. You can draw or
modify an icon for any tool on your toolbar with the Icon Editor or
import one from an image file.
When you run GUIDE to create a new GUI or edit an existing one,
click the Toolbar Editor icon in the Layout Editor Toolbar or choose Toolbar
Editor from the Tools menu
to open the Toolbar Editor. To add tools to the toolbar of your GUI,
you drag standard or custom tool icons to the toolbar layout area
at the top. You can modify a tool's properties using the Toolbar Editor
and Property Inspector. You can also create and customize icons for
tools using the new Icon Editor, described next. You control the behavior
of a tool in your toolbar with its
ClickedCallback (and
for toggle tools, their
OnCallback and
OffCallback)
in the GUI's associated M-file. If you use an existing tool, such
as Print or Save, you do not need to modify its callback; it is predefined
as
%default.
The Icon Editor lets you customize the icons for existing tools
or create entirely new icons. Icons are stored as
CData for
each tool, and can also be read from and saved to
.icn files.
The Icon Editor also includes a Color Editor, a palette you can use
for picking predefined colors and defining new ones.
The GUIDE Layout Editor now has two fields in its lower left corner that continuously provide numeric feedback for:
Current Point — The cursor location within the layout window
Position — The Position property of the currently selected object(s) in the layout window
Both measurements are given in pixels, regardless of
the current
Units settings for GUI objects. When
multiple objects are selected, any elements of their
Position properties
that are not identical are read out as
MULTI. The
readouts help you to precisely size and align GUI components.
A new documentation section, Making Multiple GUIs Work Together, has been added to illustrate how multiple GUIDE GUIs can work together by sharing data to create a more complicated GUI. It first summarizes the techniques that GUIDE GUIs can use to share data with one another. It then steps through two examples, accompanied by their M-files and FIG-files, to show how to use those techniques for specific tasks.
MATLAB Version 7.5 (R2007b) supports 64-bit mxArrays. This change allows C/C++ and Fortran files built on 64-bit platforms to handle large data arrays.
In earlier versions of MATLAB,
mxArrays
are limited to 231-1 elements. In Version
7.5 (R2007b) your mxArray can have up to 248-1
elements.
The
mex command
option,
-largeArrayDims, uses the large-array-handling
mxArray API. Use
mwSize to
represents size values, such as array dimensions and number of elements.
Use
mwIndex to
represent index values, such as indices into arrays.
MEX-files that built properly in previous versions of MATLAB continue to build in Version 7.5 (R2007b).
The default option for
mex is
-compatibleArrayDims.
If you use this option,
mex builds the files
using the 32-bit array-handling API.
To work with 64-bit mxArrays, your C, C++ and Fortran source code must comply with the 64-bit array-handling API. To use the API to create C/C++ MEX-files, see Handling Large mxArrays . To use the API to create Fortran MEX-files, see Handling Large mxArrays .
In a future version of MATLAB, the default
mex command
option will change to
-largeArrayDims. Fortran
MEX-files will be required to use the
mwSize and
mwIndex preprocessor
macros
To make your Fortran MEX-file compatible with the
-largeArrayDims option,
and to create platform-independent code, you need to include the
fintrf.h header
file in your Fortran source files, and you need to name your source
files with an uppercase
.F file extension. For
information on creating MEX-files, see the Gateway
Routine in the Fortran MEX-Files topic.
Retrieving and using the proper locale setting is a mandatory
operation in creating and using applications for international audiences.
In R2007b, MATLAB Version 7.5 standardizes the way it initializes
the locale setting across platforms. As a result, on Microsoft Windows platforms,
MEX-files that use C/C++ locale-dependent standard library functions
should note that MATLAB now sets the locale using the
setlocale function.
Because of changes to Microsoft Visual Studio, MEX-Files created on Windows with dMicrosoft Visual Studio 2003 will not have the same locale setting as MATLAB Version 7.5 (R2007b).
In MATLAB Version 7.5 (R2007b). the
mexErrMsgTxt and
mexErrMsgIdAndTxt functions
determine where the error occurred, and display the function name.
In previous versions, these functions only display the error message.
For example, if an error occurs in the function
foo,
mexErrMsgTxt and
mexErrMsgIdAndTxt display
the following information before the error message:
??? Error using ==> foo
To work with MATLAB V7.5 (R2007b), MEX-files compiled on any platform with MATLAB versions earlier than V7 (R14) no longer load correctly and must be rebuilt.
The set of compilers that MATLAB supports has changed in MATLAB Version 7.5 (R2007b). For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
MATLAB V7.5 (R2007b) supports new compilers for building MEX-files.
Microsoft Visual Studio 2005 SP1
gcc / g++ Version 4.1.2
The following compilers are no longer supported.
Microsoft Visual Studio 2005 without SP1
gcc / g++ Version 3.2.3
To ensure continued support for building your C/C++ programs, consider upgrading to another supported compiler. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
The following compilers are supported in Version 7.5 (R2007b), but will not be supported in a future version of MATLAB.
Intel Visual Fortran Version 9.0
Compaq Visual Fortran Version 6.6
Intel C++ Version 7.1
Borland C++Builder 6 Version 5.6
Borland C++Builder 5 Version 5.5
Borland C++ Compiler Version 5.5
Compaq Visual Fortran Version 6.1
MATLAB applications built with Borland Version 5.5 or 5.6 C compilers have changed in MATLAB Version 7.5 (R2007b). MATLAB applications that run under Windows are now implemented as console applications, not Windows applications.
If you have customized the build process based on one of the
bcc*engmatopts.bat options
files, you must edit this file making changes to the appropriate
LINKFLAGS statement,
as described in the
.bat file comments.
When you build a MEX-file, an engine application, or a MAT application
on a Windows 64-bit platform using the Microsoft Platform SDK compiler, MATLAB requires
that you define the environment variable
MSSdk.
The value of this environment variable is the path to the installation
directory for Microsoft Platform SDK. The Microsoft Platform SDK installation
program does not commonly define this environment variable. For example,
you might set the environment variable as follows:
C:\Program Files\Microsoft Platform SDK MATLAB Version 7.4 (R2007a), a change was made to Microsoft ActiveX® methods which was not documented in the release notes. This change is described in Changes to Handling Microsoft ActiveX Methods in the MATLAB Release Notes, Version 7.4 (R2007a).
In MATLAB V5.1, all development work for the Dynamic Data Exchange (DDE) server and client was stopped. This functionality is no longer documented in V7.5 (R2007b). MathWorks provides, instead, a MATLAB interface to COM technology that is documented in Using COM Objects from MATLAB .
Documentation for Dynamic Data Exchange (DDE) is no longer included in External Interfaces.
If you must support this obsolete functionality, we suggest you print a copy of the External Interfaces chapter "COM and DDE Support (Windows Only)" from MATLAB V7.4 (R2007a) or earlier.
Documentation for the following functions is included in the MATLAB Function Reference documentation for MATLAB V7.5 (R2007b), but will not be included in a future version of MATLAB.
The following syntax for
enableservice,
included in the MATLAB Function Reference documentation for MATLAB V7.5
(R2007b), will be removed from the documentation.
enableservice('DDEServer',enable)
If you must support this obsolete functionality, we suggest you print and keep a copy of the relevant MATLAB function reference pages from V7.5 (R2007b) or earlier.
New features and changes introduced in Version 7.4 (R2007a) are
When you open a file from Microsoft Windows Explorer whose type is associated with the MATLAB application, the file opens in the appropriate tool in the existing session of MATLAB, if MATLAB is already running, or if not, starts MATLAB. This assumes you associated the file types with MATLAB by accepting the defaults while installing MATLAB, or by changing the associations. For example, in Explorer, double-click an M-file to open the file in the MATLAB Editor/Debugger, or double-click a MAT-file to open the Import Wizard and load the data into the workspace in MATLAB. For details, including how to change file associations, see Associating Files with MATLAB on Windows Platforms.
In previous versions, when you double-clicked a file in Explorer whose type was associated with MATLAB, the file opened in a new session of MATLAB. The change made in MATLAB Version 7.4 (R2007a) to open the file in an existing session was based on many user requests.
In previous versions, double-clicking a MAT-file associated with MATLAB in Explorer opened a new session ofMATLAB and loaded the data into the workspace. When clicked in the Apple Macintosh Finder, the data loaded into the existing session of MATLAB. Now on Microsoft Windows and Macintosh platforms, the Import Wizard opens in the existing session of MATLAB, and you use it to load the data into the workspace.
By default, in previous versions, double-clicking an M-file in Explorer opened it in the MATLAB stand-alone Editor. For more information about that change, see Stand-Alone Editor No Longer Opens By Default; To Be Removed in a Future Version.
The default startup directory for MATLAB on Microsoft Windows platforms
is now
My Documents\MATLAB, or
Documents\MATLAB on
the Microsoft Windows Vista platform. Upon startup, MATLAB automatically
locates this
MATLAB folder (creating it if it does
not exist), and adds it to the top of the search path. This utilizes
standard folders on Windows and Windows Vista platforms to
provide a unique startup directory for each user. As such, the folder
is part of theWindows (or Windows Vista) user's profile,
and will be accessible when the user runs MATLAB from other machines,
when the profile is set up to roam.
In the Properties dialog box of the shortcut icon for MATLAB,
the Target field includes a new startup option
-sd (for startup directory),
followed by
$documents\MATLAB, where MATLAB interprets
$documents as
the
My Documents folder for the current user (or
Documents for
the Windows Vista platform). If the path for
$documents is
specified in the configuration of the Windows environment via
UNC pathname, MATLAB automatically assigns it a mapped drive,
creating one if necessary. The
-sd startup option
overrides anything in the Start in field, which
is now empty by default.
For more information, see Changing the Startup Directory.
In previous releases, the default startup directory was
\Work,
located in the directory in which MATLAB was installed. For example,
in R2006b, if you installed MATLAB in
C:\Program Files,
the default startup directory was
C:\Program Files\MATLAB\R2006b\Work.
Windows Vista User Account Control (UAC) security features
restrict access to
Program Files. To accommodate
this enhanced security model, the default startup directory in MATLAB has
been moved outside of
Program Files.
These are the differences between the startup directory for R2007a and previous releases:
In previous releases, upon installation, the default
startup directory was specified in the Start in field
of the Properties dialog box for the shortcut icon for MATLAB.
You could change the startup directory by replacing the pathname in
that field. In R2007a, if you want to specify the startup directory
using the Start in field, you must also remove
from the Target field the
-sd startup
option and the pathname that follows it.
The default startup directory is no longer specific
to a release. When you upgrade from R2007a to a future release, files
you created and saved in
My Documents\MATLAB (or
Documents\MATLAB on
Vista) will automatically be in the startup directory for the new
release. Previously, you had to move files you created and saved in
the
Work folder for a release, for example,
R2006a\Work,
to the default startup directory for the new release, for example,
R2006b\Work.
In previous releases, the default startup directory,
Work,
was shared by all users running that installation of MATLAB.
The default startup directory in R2007a,
My Documents\MATLAB (or
Documents\MATLAB on
Vista), provides each user with a unique startup directory.
In previous releases, MATLAB added the default
startup directory,
Work, to the bottom of the search
path. In R2007a, MATLAB adds the default startup directory,
My
Documents\MATLAB (or
Documents\MATLAB on
the Windows Vista platform), to the top.
MATLAB is now using Sun Microsystems Java (JVM) version 1.5.0_07 on Windows platforms. Java is supplied with MATLAB for Windows platforms, so this change requires no action on your part.
If you use a specific version of Java with MATLAB on Windows platforms, this change might impact you.
MATLAB now installs Java Access Bridge 2.0, which is used by Freedom Scientific BLV Group JAWS® software for accessibility support.
When you exit from MATLAB, MATLAB terminates without displaying a confirmation dialog box that asks if you are sure you want to quit. This is the default behavior but you can set a preference to display a confirmation dialog box. In a future version, the confirmation dialog box will appear by default when you quit MATLAB.
When the confirmation dialog appears by default, you will be able to disable it using preferences. If you have files that include exit statements, you might need to ensure the preference for the confirmation dialog box is disabled.
New features and changes introduced in Version 7.4 (R2007a) are
On Windows and UNIX platforms, you can minimize any
tool in the desktop. Minimizing a tool creates a button for it along
the specified edge. When you want to view the tool, hover over or
click the button to temporarily show it in the desktop. Right-click
the button and select Restore
toolname to
return the tool to the desktop. Perform these tasks for the selected
tool using items in the Desktop menu, equivalent
mnemonics (for example Alt+D, N to minimize), or
buttons on the tool's titlebar.
The following illustrations show how to use these features, using the example of the Command History window in the default desktop layout.
On Windows and UNIX platforms, you can maximize a tool so it occupies the entire desktop tool area in MATLAB, then restore it to return it to its previous location. Perform these tasks for the selected tool using items in the Desktop menu, equivalent mnemonics (for example Alt+D, X to maximize), or buttons on the tool's titlebar.
In the desktop, when you tab tools together, that is, arrange them so they occupy the same position, the tools' title bars share the title bar area. To make a tool active, select its name in the title bar.
In previous versions, tools tabbed together each had a tab at the bottom of the area they occupied. The tabs have been removed in favor of tools sharing the titlebar area.
If you run MATLAB on a multiple-CPU system (multiprocessor or multicore), use a new preference to enable multithreaded computation. This can increase performance in MATLAB for element-wise and BLAS library computations.
By default the preference is not set, so you must set it to enable multithreaded computation. With the preference enabled, MATLAB automatically specifies the recommended number of computational threads, although you can change that value. On AMD platforms running the Linux operating system, MATLAB supports multithreaded computation, but requires an extra step to change the default BLAS.
If you are using a multiple-CPU system, you can run the Multithreaded Computation demo to see the performance impact. For more information, see "Enabling Multithreaded Computation" in the MATLAB Desktop documentation.
New features and changes introduced in Version 7.4 (R2007a) are
When you start MATLAB, a getting started message bar appears at the top of the Command Window, that provides links to information that is helpful for new users. You can dismiss the message bar by using the close box in it. Use Command Window preferences to specify whether or not the message bar should appear.
You can now find entries in the Command History window by typing the first few letters of an entry; the previous entry that begins with those letters is selected. Then use up and down arrow keys to extend the find to the next and previous instances. Use the Ctrl key with an arrow key to select the current as well as next or previous instances. Use Ctrl+A to find and highlight all instances at once. The search does not look at entries in sessions that are collapsed. For more information about this search feature, see Quick Search for Entries Beginning with Specified Letters or Numbers.
On Macintosh platforms, some key bindings were changed to make them more consistent with Mac OS XMac OS X standard behaviors.
Key bindings you have been used to in the Command Window might have changed.
New features and changes introduced in Version 7.4 (R2007a) are
When you perform a search in the Help browser, the results now include code and text found in Demos. Also, the Demos listing in the Help Navigator pane now synchronizes with the demo currently open when you have the synchronization preference for the Help browser selected. For more information, see Search Syntax and Tips.
When you select File > Preferences > Help and enable the Product Filter, only demos for selected products are shown in the Demos pane, and searched via the Search for field.
When viewing a page in the Help browser, select View > Page Locations. A window appears providing the location of the current Help page you are viewing. The window provides the page location on both your local system and the MathWorks Web site. Use this feature to
Send the URL to someone else who wants to view that information and might not have MATLAB or the same version of MATLAB, for example, a colleague or technical support.
More easily see if this same documentation page has been updated for the latest product version.
If you create your own HTML help files for use with the MATLAB Help
browser, the Help browser can now search the content of your files.
Create a search database for your help files using the new
builddocsearchdb function.
The function creates a
helpsearch directory that
contains the search database files. For information on this process,
see Making
Your HTML Help Files Searchable.
In previous versions of MATLAB, some users created help search databases for their own help files via assistance from MathWorks Technical Support. If you created a help search database for use with R2006b, it might work in R2007a, but it is recommended that you recreate it for R2007a, even if no content has changed. If you created a help search database prior to R2006b, you must recreate it for R2007a.
Help search databases in prior releases were built from a help
jar file
rather than
html files. The
builddocsearchdb function
only supports
html files. However, it is expected
to support
jar files in a future release. If you
used a
jar file for a prior version and want to
use a
jar file in R2007a, build your R2007a help
search database using the same technique you used in R2006b.
Previously video tutorials were installed when you installed MATLAB. Now the tutorials are on the MathWorks Web site.
You can still link to and play video tutorials from within the Help browser Demos listings or other links to them in the product and documentation, however this now requires an active Internet connection.
New features and changes introduced in Version 7.4 (R2007a) are described here.
When you double-click a Windows shortcut in the Current Directory browser, it runs the shortcut.
When you double-click a
prj file
in the Current Directory browser, it opens in the Deployment Tool.
You can now find entries in the Current Directory browser by typing the first few letters of an entry; the entry that begins with those letters is selected.
When you double-click an object, it opens in the Property Inspector.
You can now undo and redo the last operation you performed in the Array Editor. This applies to cut, paste, insert, delete, and clear contents features.
On Windows platforms, MATLAB now adds the default
startup directory,
My Documents\MATLAB (or
Documents\MATLAB on Windows Vista),
to the top of the search path upon startup.
In previous releases, MATLAB added the default startup
directory,
Work, to the bottom of the search path
on Windows platforms. For example, in R2006b, it added
...\MATLAB\R2006b\Work to
the bottom. For more information, see Changes to Startup Directory (Folder) and Startup Options for MATLAB Application
on Windows.
New features and changes introduced in Version 7.4 (R2007a) are
Starting in this release, by default, double-clicking an M-file in Windows Explorer opens the file in the MATLAB Editor/Debugger rather than in the MATLAB stand-alone Editor. In a future version, the stand-alone Editor will not be provided with MATLAB.
The change to open M-files in the MATLAB Editor/Debugger
rather than the stand-alone Editor was made based on many user requests.
You can still use the MATLAB stand-alone Editor in this release
by starting the application located at:
.
matlabroot\bin\win
##\meditor.exe
Starting MATLAB by double-clicking an M-file requires a MATLAB license, while starting the stand-alone Editor does not require a MATLAB license.
If you want to associate M-files so that when you double-click
them they open in the MATLAB stand-alone Editor rather than in
the MATLAB Editor/Debugger, follow the instructions in Associating
Files with MATLAB on Windows Platforms; rather than specifying
the executable for MATLAB,
matlab.exe, specify
meditor.exe,
which is in the same folder.
Instead of the stand-alone Editor, you can use the MATLAB Editor/Debugger. It provides all the features of the stand-alone Editor plus some not found in the stand-alone Editor, such as debugging and tab completion; for a full list, see Stand-Alone Editor Will Not Be Included in Next Version.
Some users have preferred the stand-alone Editor to the MATLAB Editor/Debugger
because of slightly better startup performance and because it does
not require a license for MATLAB. For those situations, you can
use any text editor you have, such as UltraEdit or Emacs. If you have
concerns about the pending removal of the stand-alone Editor, please
editor-feedback@mathworks.com,
so we can plan to minimize transition issues.
You can now see the match to language keyword pairs using delimiter
matching features that previously existed for parentheses and brackets.
For example, when you type
end, the Editor/Debugger
highlights the matching
if. To set delimiter
matching preferences, select File > Preferences > Keyboard > Delimiter Matching; click Help for
more information.
For some types of warnings or errors, M-Lint can apply an automatic fix to the code. Code that can be automatically corrected appears with a different background color. To perform the fix, right-click the code that is highlighted (for a single single-button mouse, use Ctrl+click); from the resulting context menu, select the auto-fix action.
For more information, see step 8 in the example at Automatically Check Code in the Editor — Code Analyzer.
In previous versions, there was a single output message generated by a line with a missing terminating semicolon:
Terminate statement with semicolon to suppress output.
However, M-Lint suppressed displaying the message for files
with three or more cells (a cell being indicated by a line with an
initial
%%). This was done based on the assumption
that such files were demo programs, and therefore display of the output
was intentional.
In MATLAB Version 7.4 (R2007a), M-Lint no longer makes a distinction for files with three or more cells. Instead, M-Lint displays one message for scripts and a different message for functions:
Terminate statement with semicolon to suppress output (in functions). Terminate statement with semicolon to suppress output (in scripts).
%#ok<NOPRT>for functions, and
%#ok<NOPTS>for scripts.
By default, both of the messages are initially selected in Preferences.
In MATLAB Version 7.3 (R2006b),
%#ok<NOPRT> was
the only tag used to suppress the missing terminating semicolon. The
tag will remain valid for function files, but will not be valid for
script files. If you added any
%#ok<NOPRT> tags
in script files in R2006b, change those tags to the new tag
%#ok<NOPTS>.
On Macintosh platforms, some key bindings were changed to make them more consistent with standard behaviors for Mac OS X.
Key bindings you have been used to in the Editor/Debugger might have changed.
There is a new confirmation preference for displaying a warning about exiting debug mode in order to save a file.
There was a minor change in M-Lint behavior—for details, see M-Lint Detection of Missing End-of-Line Semicolons Enhanced.
See the compatibility considerations associated with M-Lint Detection of Missing End-of-Line Semicolons Enhanced.
New features and changes introduced in Version 7.4 (R2007a) are
You can now publish an M-file function. When publishing an M-file
function, you cannot evaluate the code. This feature effectively allows
you to save M-file functions to output formats such as HTML or Microsoft Word
documents, with formatting. To publish an M-file function, first clear
the Evaluate code preference in Editor/Debugger
Publishing Preferences, or run the
publish function
with the
evalCode option set to
false.
Using the
publish function,
you can specify the maximum number of lines in a published file. Set
the new
maxOutputLines field to a nonnegative value.
The default value is
Inf.
New publishing options provide increased flexibility and control over the appearance of the published document. The added options are for adding inline links, inline links with link text, graphics, and HTML markup. See Mark Up MATLAB Comments for Publishing for more information.
Matrix multiplication for
A'*b now handles
sparse matrices more efficiently.
The
rand function
now uses the Mersenne Twister algorithm as default generator algorithm.
This method generates double precision values in the closed interval
[2^(-53), 1-2^(-53)], with a period of (2^19937-1)/2. Prior to this
release, MATLAB used an algorithm known as the Subtract-with-Borrow
(SWB) algorithm.
The
rand function now produces different
results than in previous releases. However, the results returned
are still pseudorandom values drawn from a standard uniform distribution.
Because the values returned by
rand are intended
to be random, this change should not affect your code.
There are several things to keep in mind regarding this change:
If your code requires the exact values returned by
rand in
previous releases, you should use the statement
rand('state',0);
to reset
rand to use the SWB algorithm.
The new default algorithm's internal state at startup is equivalent
to using the statement
rand('twister',5489);
Note that the
'state' keyword corresponds
specifically to the SWB algorithm; it cannot be used generally to
refer to the internal state of the currently active algorithm.
Existing code that uses the
'state' keyword
to reinitialize
rand in a statement such as
rand('state',sum(100*clock))
causes
rand to switch to using the SWB
algorithm. You may want to use the
'twister' keyword,
which resets
rand but does not switch algorithms.
Existing code that uses the
'state' keyword
to save and restore the internal state of
rand in
statements such as
savedState = rand('state'); ... % code that uses rand rand('state',savedState);
may no longer work as intended. Specifically, the first line
of code saves the state of the SWB generator algorithm (see the
rand documentation
for details). If the default Mersenne Twister algorithm was the active
one at that time, then using the saved state in the last line does
not restore the
rand internal state to its original
conditions. Instead, it switches the
rand algorithm
to SWB. To save and restore the internal state of the Mersenne Twister
algorithm, use the
'twister' keyword.
MATLAB now uses new versions of the Basic Linear Algebra Subroutine (BLAS) libraries. For Windows, Intel Mac, and Intel processors on Linux platforms, MATLAB supports the Intel Math Kernel Library (MKL) version 9.0. For AMD processors on Linux platforms, MATLAB uses the AMD Core Math Library (ACML) version 3.5. For the Solaris platform, MATLAB uses the Sun Performance Library from Sun Studio 11.
The
mode function,
when operating on an empty array (
[]), returns
a 1-by-0 array in previous releases, while related functions
mean,
median,
std,
and
var return
NaN when
given the same input. In this release,
mode returns
NaN for
an empty array input.
Existing program code that relies on mode of an empty array to return an empty array should be modified.
If you change the BLAS library used by MATLAB on Linux platforms, MATLAB now loads libraries in the left-to-right order specified in the syntax. For example, to load the Intel MKL BLAS, from a system prompt, run
setenv BLAS_VERSION mkl.so:mklcompat.so
MATLAB loads
mkl.so first, and then
loads
mklcompat.so.
This also applies if you edit
bin\$(ARCH)\blas.spec directly.
This syntax differs from that used for Linux platforms in prior versions. Parse Function Inputs.
s = mat2str('MATLAB') s = 'MATLAB' eval(s) ans = MATLAB Mac OS X.
In plot edit mode, annotations such as textboxes, lines, arrows, doublearrows, and text now respond to pressing directional arrow keys. Each keypress will move the selected annotation(s) one or more pixels in the indicated direction. If you select multiple objects, they all move together in response to arrow key strokes. Normally, selected objects move one pixel with each press of an arrow key. If you have selected Snap to Layout Grid from the Tools menu, each keypress makes objects move to the next grid position.
The
movie function no longer plays each
frame one extra time. Previously, it would show frames as they were
loaded into memory to speed up display. This behavior is no longer
required and has been eliminated.
If you have code that calls
movie in a
loop a certain number of times and want that number to remain the
same, you need to add one iteration to the loop.
The Ghostscript software used by some print devices has been upgraded from an older version to Version 8.54. Starting in this release, MathWorks is no longer shipping a separate, standalone Ghostscript executable program.
If you have written M-code based on undocumented functions that called the old version of Ghostscript, your code will no longer work.
As a consequence of this upgrade, support for printing on DEC
LN03 printers (
print —dln03) has been removed
from MATLAB.
The Property Inspector (accessed via the Property Editor, GUIDE,
and the
inspect function) now provides tree views
of groups of graphic object properties as well as an alphabetical
list of all properties. You can switch between views via the two buttons
at the top of the window, as shown in the following picture of the
tree view of the Printing category:
In addition, the type of object currently being inspected is now shown in the title bar of the Property Inspector window. Formerly it was shown in the gray area below the title bar, which now contains the view manipulation buttons.
To change view, click a button without the blue background (the
collapse and expand buttons at right are disabled in alphabetic list
view). When you change views, the selected property stays the same.
To inspect properties of graphic objects in the tree view, click the
+ icon
next to a category of interest. Do the same to open properties within
a category that have multiple elements. Note that only Handle Graphics objects
have categories; annotation and most other MATLAB objects can
be displayed only in alphabetic list view.
The functionality of the Property Inspector has not changed; only its GUI has. As previously, if you select a set or array of objects and inspect them, the Property Inspector only displays those properties that all the objects share.
For details on using the Property Inspector, see Accessing Object Properties with the Property Inspector in the MATLAB Graphics documentation and the inspect reference page.
Text that you type or delete after clicking a text field that
has a text widget icon (for example,
XTickLabel),
will not persist unless you press Return before clicking
elsewhere. This mimics the behavior of clicking the text widget icon
to open a text entry dialog box, typing into it, and accepting the
result by clicking OK. This behavior differs
from that which existed prior to R2006b (MATLAB V. 7.3).
The new figure property
WindowScrollWheelFcn enables
you to write a callback function that handles mouse wheel scrolling
events while the figure has focus. See the documentation for the figure
WindowScrollWheelFcn for
more information.
The new figure property
KeyReleaseFcn enables
you to write a callback function that handles key release events (analogous
to
KeyPressFcn). See the documentation for the
figure
KeyReleaseFcn for
more information.
In GUIDE, when you copy a component for which one or more of its callback properties are defined, the callback properties of the newly created component are now set to their default values, the ones you get when adding a component directly from the Component Palette. Previously, their values were copied from the corresponding callback properties of the original component. New callback subfunctions can be generated in the GUI M-file for the new component in the same way as for any component in the GUIDE layout.
If you have relied on the old behavior, in which the callbacks properties of the new component point to the callbacks of the original component, you will now have to explicitly change the callback properties, using the Property Inspector, to do that.
The
handles structure that is provided to
every GUIDE generated callback subfunction in the GUI M-file is constructed
at runtime every time the GUI runs. When the GUI is fully initialized,
the
handles structure contains only handles to
all the components in the GUI and custom data added in any
CreatedFcn callbacks
and/or the
OpeningFcn. Previously, fields that
the M-file had added to the handles structure could sometimes become
a permanent part of the structure.
If your GUI runs well but displays error messages about missing
fields in the
handles structure when starting up,
you may have to update the code in the GUI M-file where those fields
are accessed. You may need to initialize those
handles fields
properly in a
CreateFcn callback and/or in the
OpeningFcn.
For UNIX platforms, the
Location property
of
uigetfile and
uiputfile is
obsolete. Previously, for UNIX platforms only, you could use the
Location property
to specify the screen location at which the dialog box would originally
be displayed.
Since the UNIX
uigetfile and
uiputfile
Location property
is now obsolete, MATLAB ignores any occurrences in existing code
of the
Location property
uigetfile(...,'Location',[X Y])
or the older use of
X and
Y arguments
to specify location
uigetfile(...,X,Y)
A warning is displayed for either syntax, on all platforms.
The following functions are either obsolete or grandfathered
in MATLAB 7.4 (R2007a):
cshelp,
figflag,
getstatus,
menulabel,
popupstr,
setstatus,
hidegui,
uigettoolbar.
The functions shown in the following table will continue to work but their use may generate a warning message. As soon as possible, replace any occurrences you may have of these functions with the function(s) shown in the following table, if any, or with other suitable code.
With the introduction of MATLAB for Macintosh (Intel),
the MEX-files you build have the extension
.mexmaci.
The
mexext command
in MATLAB returns
mexmaci for Macintosh (Intel).
MEX-files built using MATLAB for Macintosh PowerPC®,
which have
.mexmac extensions, cannot be used in MATLAB for Macintosh (Intel).
With the introduction of MATLAB for 64–bit Solaris SPARC®,
you can now build 64-bit MEX-files for the Solaris platform.
These MEX-files have the extension
.mexs64. The
mexext command
in MATLAB returns
mexs64 for Solaris SPARC.
MEX-files built using MATLAB for Solaris 32, which
have
.mexsol extensions, cannot be used in MATLAB for Solaris SPARC.
In order to work with MATLAB V7.4 (R2007a), MEX-files compiled on Microsoft Windows (32–bit) platforms with MATLAB R11 or earlier will no longer load correctly and must be recompiled.
Recompile these MEX-files with MATLAB R12 or later.
The set of compilers that MATLAB supports has changed in MATLAB Version 7.4 (R2007a). For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
MATLAB V7.4 (R2007a) supports new compilers for building MEX-files.
Intel C++ version 9.1
Intel Visual Fortran version 9.1
Intel C++ version 9.1
Intel Visual Fortran version 9.1
Microsoft Visual C++ 2005 version 8.0 Express Edition
Apple Xcode 2.4.1 (gcc / g++ version 4.0.1)
g95 version 0.90
gcc / g++ version 4.1.1
g95 version 0.90
gcc / g++ version 4.1.1
g95 version 0.90
cc / CC version 5.8
gcc / g++ version 3.2.3
f90 version 8.2
In R2007a we have added support for a new Fortran compiler g95 on the Linux and Macintosh platforms. This compiler implements the Fortran 95 language standard. It replaces previously supported Fortran compilers which implemented a previous language standard.
This may cause incompatibilities in your Fortran source code for MEX-files.
Refer to the IBM XL Fortran V10.1 for Linux Language
standards Web site for
information about incompatibilities between language standards.
/index.jsp?topic=/com.ibm.xlf101l.doc/xlflr/languagestandards.htm
The following compilers are no longer supported.
gcc / g++ version 3.4.5
g77 version 3.4.5
gcc / g++ version 3.4.5
g77 version 3.4.5
gcc / g++ version 3.3
Absoft f77 / f90 version 8.2a
To ensure continued support for building your C/C++ programs, consider upgrading to another supported compiler. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
The following compilers are supported in Version 7.4 (R2007a) but will not be supported in a future version of MATLAB.
Intel C++ version 7.1
Intel Visual Fortran 9.0
Borland C++Builder 6 version 5.6
Borland C++Builder 5 version 5.5
Borland C++ Compiler version 5.5
Compaq Visual Fortran version 6.6
Compaq Visual Fortran version 6.1
MATLAB V7.4 (R2007a) supports new linkers for building MEX-files with Intel Visual Fortran 9.0.
Microsoft Visual Studio .NET 2003
Microsoft Visual Studio 2005
Microsoft Visual Studio 2005
Microsoft Platform SDK for Windows Server 2003 (Build 1289 or later)
MATLAB can now programmatically connect to an instance
of a COM Automation server using the new
actxGetRunningServer function.
Changes to the
actxserver function
allow you to create a COM Automation server using a custom interface.
Additional COM data type support has been added. See Handling COM Data in MATLAB Software for a description of supported data types.
MATLAB users can take full advantage of event interfaces
provided by COM Automation servers. This change is implemented in
the
events,
eventlisteners,
isevent,
registerevent,
unregisterevent,
and
unregisterallevents functions.
For an example of this feature, see Responding to Interface Events from an Automation Server.
Using the
enableservice function
you can learn.
A programmatic identifier, or ProgID, is used to create a COM component. MATLAB's version-specific ProgID Matlab.Application.N.M now let's you specify both a major and minor version number.
For example, to specify MATLAB version 7.4, use the ProgID
Matlab.Application.7.4.
Beginning in MATLAB Version 7.4 (R2007a), an ActiveX method with the same name as a class is treated as a constructor and cannot be called in the same way as an ordinary method.
In the following example:
myApp = actxserver('Excel.Application'); op = invoke(myApp.Workbooks, 'open', 'MyFile.xls'); Sheets = myApp.ActiveWorkBook.Sheets; target_sheet = get(Sheets, 'item','Sheet1'); invoke(target_sheet, 'Activate'); Activesheet = myApp.Activesheet; cellname = 'B2'; Range = Activesheet.cells.Range(cellname,cellname);
the term
Range is both a function on the MATLAB path
and a constructor of the class
Range. MATLAB tries
to execute the function
range, which generates
the error:
??? Error using ==> range Too many input arguments. Error in ==> MyScript at 8 Range = Activesheet.cells.Range(cellname,cellname);
For example:
Range = get(Activesheet.cells, 'Range', cellname, cellname);
New features and changes introduced in Version 7.3 (R2006b) are described here.
You can run a utility from the Help browser to associate
.m,
.mat,
.fig,
.p,
and
.mdl files with the MATLAB program in
the Microsoft Windows operating system. After running the
utility, you will be able to start MATLAB by double-clicking
any of those file types in Windows Explorer. You can still use Windows Explorer Folder
Options to perform these file associations, but the utility makes
the task more convenient. For details, see Associating
Files with MATLAB on Windows Platforms.
When you start MATLAB on platforms running The Open Group UNIX operating
system using the
-nodesktop startup option, and
you redirect output, for example to a file, MATLAB now sends
any errors to the shell, while normal output goes to the redirect
target. This change was made so that redirection withMATLAB follows
standard behavior for the UNIX operating system.
For example:
matlab -nodesktop -"r magic(3), magi(5)" > test.txt
starts MATLAB in
nodesktop mode, runs
the statement
magic(3) and writes the output to
test.txt.
When MATLAB runs
magi(5), execution fails
and MATLAB displays the error message in the shell.
In previous versions, MATLAB redirected both output and
error messages, so in the above example, MATLAB wrote the output
of
magic(3) as well as the error message from
magi(5) to
test.txt.
If you have shell scripts that use
> to
redirect output, and you rely on errors appearing in the output target,
you need to modify the
matlab startup statements
in those scripts.
To achieve the former behavior, that is, to redirect both output
and errors to the specified target, use that specific redirect syntax
for your shell. For example, in tcsh, use
>&,
as in
matlab -nodesktop -"r magic(3), magi(5)" >&
test.txt
New features and changes introduced in Version 7.3 (R2006b) are described here.
M-Lint preferences now appear on a new M-Lint panel. There are new M-Lint preferences to disable specific messages or categories of messages, as well as to save the settings for use in a later session. In addition, you can choose to show or hide messages for the MATLAB Compiler™ product if the MATLAB Compiler product is installed. These new M-Lint preferences apply to the M-Lint code analyzer operating automatically in the Editor/Debugger as well as to the M-Lint Code Check Report you run via the Current Directory browser Directory Reports or Tools > M-Lint > Show M-Lint Report.
M-Lint preferences were previously accessed via the Editor/Debugger Language settings for M.
When you have multiple documents open within a tool, such as M-files in the Editor/Debugger, select File > Close to readily close selected files in that tool. Alternatively, right-click the document bar to close all open documents or all open documents except the selected document in that tool.
Accessibility features and assistive technologies are now part of the Desktop documentation. In prior versions, they were documented in the general Release Notes.
MATLAB has a new look and feel on the Linux operating system from Linus Torvalds and the Sun Microsystems Solaris operating system that affects windows, decorations, color schemes, and responsiveness of the interface in MATLAB.
All of the changes are cosmetic, except for file dialog boxes, like Open file. The new file dialog boxes are more conventional and easier to use than in previous versions, and there is no loss in functionality.
When MATLAB finds an
info.xml file on
the search path or in the current directory, it assumes the file is
intended to add information to the Start button
or the Help browser, and automatically validates the file against
the supported schema. If there is an invalid construct in the
info.xml file, MATLAB displays
an error in the Command Window. The error is typically of the form
XML-file failed validation against schema located in ... XML-file name: full path to...\info.xml
and might appear when you start MATLAB, press the Start button, or in other situations. For more information about the error and how to eliminate it, see Add Your Own Toolboxes to the Start Button.
In previous versions, MATLAB displayed a warning when it
encountered an invalid
info.xml file.
New features and changes introduced in Version 7.3 (R2006b) are described here.
These improvements were made to the Help browser search feature. Note that they are not supported on Japanese systems.
Search Field Always Shown — The Search for field is now always in view when the Help browser is open. The list of pages found appears in the Search Results tab.
Exact Phrase Searches for More Relevant Results —
Find an exact phrase by typing quotation marks around the search term.
For example,
"plot tools" finds only pages that
include
plot tools together, but does not find
pages that include
plot in one part of the page
and
tools in another part of the page. You can
specify more than one exact phrase in a search term, such as
"plot
tools" "figure pallette".
Wildcards (
*) in Search Terms for
Variations of a Word (Partial Word Search) — Use the wildcard
character (
*) in place of letters or digits in
your search terms. For example,
plot* finds various
forms of the word
plot, such as
plot,
plots,
and
plotting, while
p*t find
those variations as well as variations of
part,
among others. You can use multiple wildcards in a word or search term.
Boolean Operator Evaluation Order Changed —
Boolean
NOT operators in search terms are now evaluated
first, followed by
ORs, and then
ANDs.
In prior versions, Boolean operators were evaluated in left to right
order.
The search enhancements were facilitated by changing to a new type of database. As a result, any existing Help search databases for non-Mathworks products will not work in R2006b and beyond. The documentation still displays in the Help browser, but it is not included in searches.
If you use Help browser documentation for non-MathWorks products with a pre-R2006b search database, a message will display in the Help browser to notify you that the documentation will not be included in searches. If you want search to work for that documentation, contact the product provider to request an R2006b-compatible search database.
If you provide documentation for the Help browser and want the
documentation to be included in the searches, you need to update the
helpsearch.db entry
in the
info.xml file to the
helpsearch directory,
and prepare an R2006b-compatible help search database. This process
is much easier than in the past. For instructions, contact
Technical Support.
New features and changes introduced in Version 7.3 (R2006b) are described here.
The Workspace browser includes new columns that automatically display results of common statistical calculations: Minimum, Maximum, Range, Mean, Median, Mode, Variance, and Standard Deviation. Use View > Choose Columns to specify the columns to show.
See also File > Preferences > Workspace for associated preferences.
You can open larger arrays in the Array Editor. In previous versions, large arrays would fail to open in the Array Editor.
New features and changes introduced in Version 7.3 (R2006b) are
Use the new File Comparisons tool to highlight the differences between two files. Open a file, select Tools > Compare Against, and then browse to select the second file or drag it into the tool from the Current Directory browser or Windows Explorer. The two files appear aligned in a window with highlights and indicators for any lines that differ, as shown in this example. For more information, see Comparing Files and Folders.
Use elements in the toolbar to exchange the left-right positions of the two files and to specify the number of columns shown.
You can also run the File Comparisons tool from the desktop by selecting Desktop > File Comparisons. Drag a file from the Current Directory browser or Windows Explorer into the tool. Then drag the second file into the tool.
These are the new features and changes to M-Lint:
On Japanese systems, messages now appear in Japanese.
The messages that appear at the indicator bar now includes the line number.
The M-Lint automatic code analyzer in the Editor/Debugger now provides a few ways for you to suppress specific messages and categories of messages:
Ignore Specific Instance — Right-click at the
underline for an M-Lint message, and from the context menu, suppress
just that instance. M-Lint adds
%#ok and a new
message ID tag to the end of the line, which is the syntax in MATLAB for
suppressing an M-Lint message.
Disable All Instances — Right-click at the underline for an M-Lint message, and from the context menu, disable all instances of that message in all files. This changes the preference setting for that message.
Use Preferences to Disable All Instances — Select File > Preferences > M-Lint, and disable specific messages or categories of messages, which applies to all instances in all files. You can save the settings to an M-Lint preference file. From the Editor/Debugger, you can select the M-Lint preference file from the Tools > M-Lint menu.
The M-Lint Code Check report also uses the preferences and suppresses the display of specific messages and categories of messages, per the preference settings.
M-Lint now displays deployment messages for the MATLAB Compiler product,
such as
MCC does not permit the CD function, which
appear if the MATLAB Compiler product is installed and you select
the M-Lint preference to Show MATLAB Compiler deployment
messages. You can also disable or enable all deployment
messages via the Editor/Debugger Tools > M-Lint menu. You can suppress
specific messages using the same methods as for other M-Lint messages.
M-Lint preferences were previously accessed via the Editor/Debugger Language settings for M. See also mlint Message IDs Changed and %#ok Syntax Enhanced
You can save the status of breakpoints to a MAT-file using
s=dbstatus and
restore the breakpoint status at a later time by loading the MAT-file
using the new
dbstop(s) option. For example, set
breakpoints in
collatz. Run
s=dbstatus to
assign the breakpoint status to
s; use the
'completenames' option to save absolute pathnames
and breakpoint function nesting sequence. Save
s to
a MAT-file by running, for example,
save mydebugsession s.
At a later time, run
load mydebugsession to restore
s,
and then run
dbstop(s) to restore the breakpoints.
If you debug multiple files at once, you can exit debug mode
for all files by running
dbquit('all')..
The new
dbquit('all') option ends debugging for
both
file3 and
file4, and as
dbquit does,
ends debugging for
file1 and
file2.
New features and changes introduced in Version 7.3 (R2006b) are described here.
The File Comparison Report, one of the directory reports available in the Current Directory browser, was removed.
The new File Comparisons tool replaces the File Comparison Report. The tool provides the same functionality as the report did, and adds new features. For details, see File Comparisons Tool Added.
You can indicate specific messages or categories of messages you want M-Lint to report. For details, see M-Lint Enhancements for Suppressing Messages, and Showing Messages for the MATLAB Compiler Product.
In previous versions, the M-Lint Code Check report showed all
messages except those suppressed via a
%#ok at
the end of a line. Now, the M-Lint Code Check report will show only
the messages that are enabled via M-Lint preferences.
The
mlint function
with the
-id option returns message IDs using a
new form. For example, when you run
mlint('filename.m', '-id')
MATLAB Version 7.2 (R2006a) returns
L 22 (C 1-9) 2:AssignmentNotUsed : The value ...
whereas MATLAB Version 7.3 (R2006b) returns
L 22 (C 1-9): NASGU: The value ...
The
%#ok syntax used in M-files to suppress
the display of M-Lint messages for a line has been enhanced to support
multiple messages per line. For example, given this line in an M-file,
data{nd} = getfield(flds,fdata{nd});
two M-Lint messages result:
34: 'data' might be growing inside a loop; ... consider preallocating for speed.
34: Use dynamic fieldnames with structures instead of GETFIELD... Type 'doc struct' for more information.
In MATLAB Version 7.2 (R2006a), M-Lint messages could only be suppressed for the entire line:
data{nd} = getfield(flds,fdata{nd}); %#ok
In MATLAB Version 7.3 (R2006b), you can still use
%#ok to
suppress all messages for the line, or you can add an ID tag to indicate
the exact messages to suppress. For example, this suppresses only
the first message about
data growing inside a loop:
data{nd} = getfield(flds,fdata{nd}); %#ok<GFLD>
To suppress more than one message per line, separate the ID tags with a comma. For example, this suppresses both messages:
data{nd} = getfield(flds,fdata{nd}); %#ok<GFLD,AGROW>
In previous versions, the message IDs returned from
mlint with
the
-id option, were of a form that included a
numeric identifier, followed by the category. If you rely on the exact
ID values, you will need to make modifications to use the new form.
If you use M-Lint in MATLAB Version 7.3 (R2006b) and then
run those files a previous version, M-Lint in the previous version
ignores the tag and IDs that follow the
%#ok, and
therefore suppresses all messages for that line, which is the expected
behavior for the previous version.
The
mlintrpt function
now accepts a new option that applies the preferences saved to an
M-Lint settings file. It works with the
file or
dir syntax:
mlintrpt('fullpath_to_file', '
file', 'fullpath_to_configfile.txt') mlintrpt('fullpath_to_dir', '
dir', 'fullpath_to_configfile.txt')
For example, create the file
NoSemiSetting.txt by
saving settings in File > Preferences > M-Lint. Later, use the settings via preferences or M-Lint in
the Editor/Debugger, or via
mlintrpt as in this
example:
mlintrpt('lengthofline.m', 'file', 'I:\MATLABFiles\NoSemiSettings.txt')
which displays an M-Lint report in the MATLAB Web browser
for the
lengthofline file in the current directory
using the M-Lint settings in
I:\MATLABFiles\NoSemiSettings.txt.
The Profiler included a refresh button
on the toolbar. This
button has been removed. It performed an action similar to the Refresh button
that appears in many of the Profiler reports, so use that button instead.
In MATLAB 7.1 (R14SP3), the
notebook function
was enhanced to automatically detect the version of the Microsoft Word application
and other required information. This feature changed the
notebook
-setup syntax—arguments to specify the version of
the Microsoft Word application (
wordversion,
wordlocation,
templatelocation)
were no longer supported. If you used those arguments, MATLAB ignored
them and issued a warning. Now in MATLAB 7.3 (R2006b), if you
use those arguments, MATLAB errors.
If you use notebook with the
wordversion,
wordlocation,
and
templatelocation arguments in any of your files
(for example,
startup.m), remove them to prevent
errors.
For complex input,
min and
max are
computed using the magnitude,
min(abs(x)) and
max(abs(x)) respectively.
In the case of equal magnitude elements, the phase angle,
min(angle(x)) and
max(angle(x)),
is now used.
In previous versions,
min and
max were
computed using the magnitude, and in the case of equal magnitude elements,
the first element was used. This behavior was indeterministic and
not consistent with the
sort function.
Code in previous releases that relied on the output of this functionality for the case described above should be updated.
MATLAB 7.3 supports new versions of the following libraries:
The internal storage of sparse arrays on 64-bit systems has changed in the R2006b release. This change should be invisible to most MATLAB users. However, MEX-file programs that run on a 64-bit system and access sparse arrays must be modified and recompiled in order to run on MATLAB Version 7.3. This applies to existing MEX-files and to any new MEX-files that you write.
If you are affected by this change, you will need to take the following steps to make your code compatible with the new sparse array format:
Modify all sparse array declaration statements in
MEX-files that are to run on a 64–bit system so that they now
use the
mwSize and
mwIndex types
instead of more specific type declarations such as
int or
INTEGER*4.
Change any MEX code that assigns a negative value
to a variable used to hold a sparse array index or size. An example
of this would be code that temporarily uses an array index as a flag,
assigning a -1 to it to mark the index as unset. Do not try to cast
negative
int values to
mwSize or
mwIndex.
Instead, change your code to avoid using negative values.
Recompile these MEX-files using the
-largeArrayDims option
For a full description of what you will need to do, please read the section Sparse Arrays on 64-bit Systems in the MATLAB External Interfaces release notes.
Existing MEX-files that run on 64-bit systems and access sparse
arrays in MATLAB will not operate correctly in MATLAB 7.3
unless the required changes outlined above are made and the files
are recompiled with the
-largeArrayDims option.
New MEX-files that you create must also adhere to these guidelines.
The version of FFTW used in MATLAB has been upgraded from 3.0.2 to 3.1.1 Please read the ??? section, below.
Other changes in MATLAB FFTW support are:
The default planner method is now
estimate.
Previously,
hybrid was the default.
There are new syntaxes for importing from and exporting
to the library's internal single- and double-precision wisdom databases.
These are as follows and are documented in the reference page for
the MATLAB
fftw function:
str = fftw('dwisdom')
str = fftw('swisdom')
fftw('dwisdom', str)
fftw('swisdom', str)
FFTW version 3.1.1 does not support wisdom produced by previous versions of the FFTW library. For this reason, FFTW wisdom that has been exported from a previous version of MATLAB cannot be imported successfully in MATLAB R2006b. Trying to import "old" wisdom results in a warning.
The
betacore function generates a warning
message in R2006b but completes successfully. This function will be
made obsolete in a future release.
You should remove all instances of the
betacore function
from your M-file program code. This function will not be supported
in a future release of MATLAB.
The following uses of MATLAB functions are obsolete as of this release. Attempts to use this functionality in the R2006a release generate a warning message but complete successfully. In R2006b, these operations fail and generate an error message.
The following functions in their entirety:
bvpval,
quad8,
table1,
table8,
bessela
The
sort function, when used
with complex integer inputs
The
gt,
ge,
lt,
and
le functions, when used with complex integer
inputs
The
beta function, when used
with 3 inputs
The
gamma function, when used
with 2 inputs
The
opts.cheb and
opts.stagtol fields
in the options structure of
eigs
You will need to remove all instances that reference these functions at this time. These functions are no longer supported in MATLAB.
In MATLAB version 7.0 (Release 14), the functions
max and
min were
changed to return results of a different data type than in previous
releases. This behavior is described in max and
min Now Have Restrictions on Inputs of Different Data Types.
This change in behavior produced warning messages to assist you with
diagnosing any resulting issues. In R2006b, these warning messages
no longer exist.
The warning messages for mixed-type inputs to the functions
max and
min are
no longer produced. Turning warning messages on will no longer display
messages for this behavior, and you will no longer be able to depend
on the messages for the diagnosis of problems.
The Generate M-File option on the File menu of MATLAB figure windows now generates code that reproduces plot objects created with the Basic Fitting Tool or the Data Statistics Tool. The generated M-file function accepts new data as input and creates plot objects with the same graphics properties as those in the generating figure. In addition, the M-file recomputes fits and statistics for the new data. The code shows you how to program what you do interactively with the Basic Fitting Tool or the Data Statistics Tool.
Time Series Tools are now easier to find. From the MATLAB Start button, select MATLAB > Time Series Tools.
Time series objects are now fully supported by the
Array Editor. When you open a
timeseries object
(using
open or
the Workspace browser), the editor from Time Series Tools appears
in the Array Editor.
Time series objects can now be opened directly in
Time Series Tools. Select a
timeseries object in
the Workspace browser, right click, and choose Open in
Time Series Tools from the context menu.
In Time Series Tools, you can now change subplot indices interactively. Click on a plotted line in a time series view and drag and drop it from one subplot to another. To create a new subplot, drag and drop the plotted line below the bottom axes.
With MATLAB R2006b, you can save data items that are over 2 gigabytes in size. This capability is implemented in MATLAB using a new HDF5-based format for MAT-files.
To save to a MAT-file in this format, specify the new
-v7.3 option
with the
save function:
save -v7.3 myfile v1 v2
In this release,
The default MAT-file format employed by
save is
the standard MAT-file format used in the R14, R14SP, and R2006a releases.
You can explicitly specify this format with the command
save
-v7.
To write an HDF5-based MAT-file, you must use
save
-v7.3.
HDF5-based MAT-files are not compressed.
In a future release,
The default MAT-file format will be the HDF5-based
format. You can explicitly specify the HDF5-based format with the
command
save -v7.3.
To write the standard MAT-file format, you must use
save
-v7.
As of release R2008a, HDF5-based MAT files are compressed.
Here is a summary of the version options that you can use with
save:.
The Import Wizard now includes an automated M-code generation option. Click the Generate M-code button located in the lower right of the Import Wizard window and MATLAB generates an M-file that you can use to import additional files that are similar in type to the file you are currently importing. This simplifies the process of importing multiple files into MATLAB.
The new
(?@cmd) operator specifies
a MATLAB command that
regexp or
regexp is
to run while parsing the overall match expression. Unlike the other
dynamic expressions in MATLAB, this operator does not alter the
contents of the expression it is used in. Instead, you can use this
functionality to get MATLAB to report just what steps it's taking
as it parses the contents of one of your regular expressions. This
can be helpful in debugging regular expressions, for example.
Two new reserved keywords have been added to the MATLAB language in this release:
parfor – designates a
for loop
in the Distributing Computing Toolbox
classdef – signals the beginning
of a MATLAB class definition
The
iskeyword function
returns
true for each of these functions, thus
identifying them as reserved keywords in MATLAB:
MATLAB keywords are reserved for use internal to MATLAB, and should not be used in your own program code as identifiers or function names. If your code uses either of these two new keywords in this manner, you should modify your code and use words that are not reserved.
The visual output of the information returned by
whos looks
slightly different in R2006b than in previous releases. Changes are
as follows:
There is a new column in the output called
Attributes that
identifies values that are
sparse,
complex,
global,
or
persistent.
The words "array" and "object"
have been dropped from items under the
Class heading.
Items formerly listed as
double array or
timer
object , for example, are now displayed as
double,
and
timer.
MATLAB no longer includes summary information
showing the "Grand total" of elements and bytes at the
bottom of the
whos output display.
There is an additional field in the structure returned
by
whos. This new field is
'persistent' and
is set to logical 1 for those variables that are persistent, or logical
0 otherwise.
Here is an example of the information displayed by whos in MATLAB 7.3:
whos Name Size Bytes Class Attributes vCell 5x7 2380 cell vComplex 6x2 192 double complex vDouble 6x5x9 2160 double vFuncHdl 1x1 16 function_handle vGlobal 0x0 0 double global vObject 1x1 248 timer vPersist 0x0 0 double persistent vSparse 15x15 244 double sparse vStruct 1x3 804 struct
If any of your programs depend on the displayed output of
whos,
specifically in relation to the changes listed above, you might have
to modify your program code. Also, if your code relies on a specific
number of fields for the output structure, you should be aware that
this release adds a new field:
persistent.
Using the new
first option with the
unique function
returns a vector with elements that represent the lowest indices
of unique elements in the input vector.
Given the following vector
A
A = [16 7 5 41 2 16 8 2 6 3 16 6 2 5 2 5];
Get a sorted vector of the unique elements of
A:
v = unique(A) v = 2 3 5 6 7 8 16 41
Use the
first and
last options
to get indices of the first and last elements in
A that
make up the sorted vector
v:
[v, m1] = unique(A, 'first'); m1 m1 = 5 10 3 9 2 7 1 4 [v, m2] = unique(A, 'last'); m2 m2 = 15 10 16 12 2 7 11 4
In MATLAB Versions 7.0 through 7.2, you could use the switches
–compress,
–nocompress,
–unicode,
and
–nounicode with the
save function
to enable or disable compression and Unicode character encoding in
the MAT-file being generated. In MATLAB Version 7.3, the
save function
no longer supports these switches. Instead,
save now
creates a MAT-file with compression and Unicode character encoding
by default, or with the following command:
save -v7 filename
You can still save to a MAT-file without using compression or Unicode encoding. In fact, you will have to do this in order to create MAT-files that you can load into a MATLAB Version 6 or earlier. To save to a MAT-file without compression or Unicode encoding, type
save -v6 filename
To disable compression and Unicode encoding for all
save operations
in a MATLAB session, open the MATLAB Preferences dialog,
select General and then MAT-Files,
and then click the button labelled Ensure backward compatibility
(-v6).
If you have code that uses any of these option switches with
the
save function, you will need to modify that
code to use the
–v6 option instead.
To accommodate future changes in the MATLAB error handling
capabilities, MathWorks has added a new restriction to the single-line
syntax of the
try-
catch block.
In this release, the following syntax operates as it did in previous
releases, but now it also generates the following warning message:
try try_statements, catch catch_statements, end Warning: This try-catch syntax will continue to work in R2006b, but may be illegal or may mean something different in future releases of MATLAB.
To make this single-line
try-
catch work
without warning in R2006b, you must insert a separator character (comma,
semicolon, or newline) immediately after the word
catch
try try_statements, catch, catch_statements, end
As with previous releases, the recommended syntax for a
try-
catch block
is as follows:
try try_statements catch catch_statements end
Your M-file programs may generate this warning if correct syntax
for
try and
catch is not
used.
The following warning has been removed from MATLAB in release R2006b:
"Function call foo invokes /somewhere/on/the/path/foo.m, however, function /somewhere/ahead/on/the/path/FOO.m that differs only in case precedes it on the path."
In previous versions of MATLAB, this warning message was
triggered when you called a function such as
foo,
and all of the following were true:
There was more than one MATLAB file of this name on the MATLAB path
The names of these files differed only in letter case, and
A MATLAB file of this name but with different
case (e.g.,
FOO.m) preceded a file of matching
case (e.g.,
foo.m) on the path
Earlier versions of MATLAB displayed this warning for the purpose of helping users cope with newly-introduced case sensitive dispatching changes. The warning is being removed at this time under the assumption that users are now sufficiently well-acquainted with the way MATLAB handles case sensitivity in function calls.
The dispatching behavior regarding to the case sensitivity is NOT changed with the removal of this warning message. If both an exact match and inexact match are present on the path, the exact match is always the one to be invoked.
Commands such as
fprintf(0, ...) and
fwrite(0,
...), in which the file identifier is zero (the same as
stdin)
now result in an error being thrown. In previous releases, MATLAB did
not throw an error in response to these commands, even though printing
or writing to
stdin is clearly not a valid option.
If any of your programs use lower-level MATLAB file I/O
functions that send output to
stdin, because these
functions no longer ignore this type of operation, your code will
now generate an error. You should modify your program code to use
a file identifier other than zero.
In the R14 and R14 service pack releases of MATLAB, assigning
a nonscalar structure array field to a single variable incorrectly
resulted in an error. For example, in the following code, you should
be able to assign
S.A to one, two, three, or four
output variables. However, if you assign to just a single variable, MATLAB throws
an error:
% Create a 1-by-4 structure array S with field A. S(1).A = 1; S(2).A = 2; S(3).A = 3; S(4).A = 4; % Assigning S(1).A and S(2).A works as expected. [x y] = S.A x = 1 y = 2 % Assigning only S(1).A should work, but does not. x = S.A; ??? Illegal right hand side in assignment. Too many elements.
This has been fixed in MATLAB 7.3.
If any of your programs rely on this error being thrown, you will need to modify those programs.
As of Release 14, the function definition line in a function M-file no longer requires commas separating output variables. This now makes the function definition syntax the same as the syntax used when calling an M-file function:
function [A B C] = myfun(x, y)
This new syntax is not valid in MATLAB versions earlier than Release 14. When writing an M-file that you expect to run on versions both earlier and later than R14, be sure to separate any output variables in the function definition line with commas:
function [A, B, C] = myfun(x, y)
In this release, MATLAB offers improved performance in the following areas:
Improved performance on 64-bit Windows XP and Linux platforms. This is independent of the size of data set in use.
Faster scalar indexing into cell arrays.
Faster assignment of cell array data to variables.
The three MATLAB plotting tools (Figure Palette, Property Editor, and Plot Browser) now function as desktop components like the Workspace Browser and the Array Editor. They dock, however, not to the MATLAB desktop but to a Figures window. Figures windows contain one or more figures, each of which is accessible by a tab. Turning on any plotting tool changes your figure group into a mini-desktop. You can undock, rearrange, tab, and resize the plot tools within the mini-desktop, and their state will persist across MATLAB invocations. There are just one set of plot tools for all your figures, but they only operate on figures contained in the group; undocked figures are free of the plotting tools until you redock them.
For more information see Plotting Tools – Interactive Plotting in the MATLAB Graphics documentation.
The MATLAB Version 6 Property Editor, one of the Plotting
Tools, is no longer available. this means that the
'v6' switch
for the
propedit function now produces an error
instead of starting the version 6 property editor. The error message
is
??? Error using ==> propedit The Version 6 property editor is no longer available. Sorry!
If you have code that calls the version 6 property editor, you
will need to modify it to use the modular plotting tools described
above in Plotting Tools Are Now Modular Desktop Components. The
propedit function
remain otherwise the same.
Printing MATLAB figures has become easier as a result of combining the Page Setup, Print Setup, and Print Preview dialogs into one tabbed Print Preview dialog. You can now specify paper size, plot size and layout, color and line weight, header text, rendering, and other printing characteristics in this new dialog. The Page Setup and Print Setup dialogs still exist, and the Print dialog that you call from File —> Print remains the same. The Page Setup dialog is available on all platforms.
For more information, see Using
Print Preview in the MATLAB Graphics documentation and
printpreview in
the MATLAB function reference documentation.
The Page Setup dialog no longer is available
from the figure window File menu. However,
it does continue to exist; you can raise it using the
pagesetupdlg command.
The old Print Preview dialog has been removed,
however. The old Print Setup dialog can be raised
using the command
print -dsetup
If your mouse has a center scroll wheel, you can use it to zoom in and out of axes, as well as by clicking and/or dragging.
You.
You can now easily customize the text of datatips. The
datacursormode function
lets you specify the contents and formatting of text displayed by
the data cursor tool. When the data cursor tool is active, you can
use its context (right-click) menu to edit or specify the text update
function that MATLAB executes to display datatips. For more information,
see Data
Cursor — Displaying Data Values Interactively in the MATLAB Graphics
documentation and
datacursormode in
the MATLAB Function Reference documentation.
You can now customize the behavior of data explore modes by modifying the zoom, pan and rotate3d objects that are dereferenced as follows:
h = pan(figure_handle) h = rotate3d(figure_handle) h = zoom(figure_handle)
Allow, change, or inhibit a mode for a specified axes
Create callbacks for pre- and post-buttonDown events
Change callbacks dynamically
See
pan,
rotate3d,
and
zoom in
the MATLAB Function Reference documentation for details and examples.
Using mode objects can cause a forward incompatibility. In prior releases, explore modes did not return an argument. Therefore, code such as the above examples that you write to take advantage of the new API will not run in MATLAB versions prior to R2006b. zoom, pan, and rotate3d code written for previous MATLAB versions, however, will run as before (there is no backward incompatibility).
A new section in the Graphics User Guide, Types of MATLAB Plots, now includes a gallery of graphs that catalogs the kinds of plots that you can create using MATLAB graphics functions. There are two tables containing labeled icons, one for Two-Dimensional Plotting Functions, and one for Three-Dimensional Plotting Functions, classified by plot type. Clicking the function name above any thumbnail plot in the gallery opens the reference documentation for that function.
Reference pages for functions that create, edit, annotate, and save plots have been enhanced in several ways:
Thumbnail figures at the top of plotting functions and related GUI reference pages illustrate what you see when you invoke these functions.
GUI Alternatives sections above syntax descriptions describe how to invoke a function (or similar capability) from a GUI, and provide links to relevant topics in the Graphics and Desktop Tools User Guides.
Revised printing documentation in user guides and reference pages (see New Desktop Printing GUI, above)
Numerous corrections and clarifications of details in user guides and reference pages
The following functions are obsolete in MATLAB 7.3 (R2006b):
axlimdlg,
edtext,
menubar,
pagedlg,
umtoggle.
The functions shown in the following table will continue to work but their use will generate a warning message. As soon as possible, replace any occurrences you may have of these functions with the function(s) shown in the following table, if any, or with other suitable code.
Setting the background color of user interface control (uicontrol) push buttons and toggle buttons on Windows XP now results in flat, colored buttons.
Prior to this release, if you set the background color of a push button or toggle button to any color other than the factory color on Windows XP, the color displayed only as a border around the button. With this release, any such buttons will display as flat, colored buttons with a simple border.
The Creating GUIs Programmatically section of the documentation now contains information commensurate with information in the Creating GUIs with GUIDE section. It adds, in workflow order, information and many basic examples about:
Adding components, menus, and toolbars to your GUI. Placing and aligning components.
Designing for cross-platform compatibility.
Initializing the GUI and creating callbacks.
Callback examples for the different components.
Version 7.3 (R2006b) defines two new types for API arguments and return values. These are
mwSize —
represents size values, such as array dimensions and number of elements.
mwIndex —
represents index values, such as indices into arrays.
Using these types in array declarations replaces more specific
type declarations such as
int or
INTEGER*4.
In general, using these types consistently in your C or Fortran source
files can insulate your code from changes in the API implementation
that might take place between different versions of MATLAB.
The
mwSize and
mwIndex types
are required when working with functions that access sparse arrays
on a 64-bit system. This is described in the release note on Sparse Arrays on 64-bit Systems, below.
The internal storage of sparse arrays on 64-bit systems has changed in the R2006b release. Due to this change, you will need to
Change declaration statements in your source code
so that you use the new types
mwSize and
mwIndex in
place of specific type declarations such as
int or
INTEGER*4.
This is described in the section New Types for Declaring Size and Index Values, above.
Recompile all MEX-files that interact with sparse
arrays using the new
-largeArrayDims switch. For
more information about the
-largeArrayDims switch,
see the section New MEX Switch,
below.
See the section on ??? to find out if you will need to make any modifications to your existing MEX code to accommodate these changes.
You will need to recompile any MEX-files that use the following sparse functions on a 64-bit system:
In order to build MEX-files that use any of the sparse array
functions listed above, you need to compile these files with the
-largeArrayDims switch,
as shown here:
mex -largeArrayDims filename
Also, any existing MEX-files that interact with sparse arrays
in MATLAB Version 7.3 must be recompiled using the
-largeArrayDims switch.
If you are using any of the functions listed above, then you should be aware of the following potential compatibility issues if your MEX code uses sparse arrays on a 64-bit system:
In release R2006b, you must rebuild all MEX-files
that use sparse arrays using the new
-largeArrayDims switch.
Before building your MEX-files, change your C or Fortran
sources to use the
mwSize or
mwIndex types
introduced in this release. See the
mxArray reference
pages for the types to use for each function.
MEX-files that compiled properly in Version 7.2 (R2006a) and do not use sparse arrays should build and execute correctly in Version 7.3 (R2006b) without changes.
For more information on how the sparse API is affected,
see the
Sparse Arrays on 64-Bit Systems section
in the MATLAB Mathematics release notes.
In Version 7.3 (R2006b), you can save MAT-files in a format based on HDF5. Unlike earlier MAT-file formats, the HDF5-based format is capable of saving variables that occupy more than 2 GB of storage, including large arrays created on 64-bit systems.
To save a MAT-file in the HDF5-based format, use the
-v7.3 option
to the MATLAB
save function
or the
"w7.3" mode argument to the C or Fortran
matOpen function.
The default MAT-file format is the same as that in Version 7.2 (R2006a).
Earlier versions of MATLAB cannot read MAT-files written in the HDF5-based format.
MAT-files written with MATLAB Version 7.3 (R2006b) on a 64-bit system can be read back into MATLAB 7.3 on a 32-bit system, provided that none of the values stored in the MAT-file require more than 32 bits to store.
In MATLAB Version 7.3, the Microsoft Windows script
mex.bat is
located in the directory
$MATLAB\bin.
You may need to change any scripts or environment variables
that relied on the previous location of
mex.bat.
Compaq Visual Fortran version 6.1 is supported in Version 7.3 (R2006b) but will not be supported in a future version of MATLAB.
To ensure continued support for building your Fortran programs, consider upgrading to another supported compiler. For an up-to-date list of supported compilers, see the Supported and Compatible Compilers Web page.
Attempting to insert a COM server into a MATLAB figure
can result in unpredictable behaviors. To prevent this condition,
the
actxcontrol command now checks the ProgID by
looking at the registry's
HKR/CLSID/Control keyword
and throws an error if the ProgID does not belong to a Microsoft ActiveX control.
Before the validation check was added, some server ProgIDs worked
with
actxcontrol , probably because there are cases
where Microsoft software points the server GUID to a control
GUID underneath. An example of a ProgID that might not work with
actxcontrol is
the Windows Media® Player server ProgID
Mediaplayer.mediaplayer.1.
Therefore, depending on how Microsoft software registers the
control, the following command might now return an error:
h = actxcontrol('Mediaplayer.mediaplayer.1'); % Returns an error
The correct ProgID to use for Mediaplayer is the ActiveX control ProgID:
h = actxcontrol('WMPlayer.OCX.7'); % Use control ProgID
Note that methods and properties to open and play files are different when using the control ProgID.
You can disable the validation check with the following command:
feature('COM_ActxProgidCheck',0)
Or reenable it with:
feature('COM_ActxProgidCheck',1)
By default, ProgID checking is on.
New features and changes introduced in Version 7.2 (R2006a) are described here.
The installation directory structure on Microsoft Windows platforms
is slightly different than in previous versions. By default, the structure
now includes a general
MATLAB top level directory,
with a subdirectory for
R2006a. The root directory
for the MATLAB software returned by the
matlabroot function,
is now of the form in this example:
D:\Applications\MATLAB\R2006a
In previous versions, the top-level directory included the version
number, so the root directory for MATLAB, as returned by the
matlabroot function,
was of the form in this example:
D:\Applications\MATLAB 7.1
If you relied on the explicit root directory structure for MATLAB in
your code, change it to reflect the new structure including the top-level
MATLAB directory.
The
matlabroot function might be useful.
If MATLAB experiences a segmentation violation, it generates an error log. Upon the next startup, MATLAB prompts you to e-mail the error log to The MathWorks. The MathWorks uses the log to work on resolving the problem. When you send a log, you receive a confirmation e-mail and will only receive further e-mails if The MathWorks develops a fix or workaround for the problem.
There are some situations where the Error Log Reporter does
not open, for example, when you start MATLAB with a
-r option
or run in deployed mode. If you experience segmentation violations
but do not see the Error Log Reporter on subsequent startups, you
can instead e-mail logs by following the instructions at the end of
the segmentation violation message in the Command Window.
The Sun Microsystems JVM software version that MATLAB uses is now version 1.5.0_04 for 64-bit platforms running the Linux operating system from Linus Torvalds.
New features and changes introduced in Version 7.2 (R2006a) are described here.
Preferences includes a new pane, Keyboard, for setting key bindings, tab completion, and delimiter-matching preferences for the Command Window and Editor/Debugger. Most of these preferences were previously located in the preference panes for the Command Window or Editor/Debugger.
You no longer access keyboard and indenting preferences for the Command Window and Editor/Debugger from the component preferences, but rather from the new Keyboard preferences. In addition, some preferences that were set separately for these components are now shared. For details about the changes, see Keyboard and Indenting Command Window Preferences Reorganized, and Keyboard and Indenting Editor/Debugger Preferences Reorganized.
You can now open (and close) all desktop tools from the Desktop menu. In previous versions, you could not access document-based tools from the Desktop menu. The document-based desktop tools are: Editor/Debugger, Figures, Array Editor, and Web Browser.
Use Help > Web Resources > MathWorks Account menu items to go to your MathWorks Account if you are registered, or to register online. MathWorks Account was previously called Access Login.
New features and changes introduced in Version 7.2 (R2006a) are described here.
The Command Window Keyboard and Indenting preferences pane was removed. The tab size preference is now on the Command Window preferences pane. The tab completion, keybinding, and parentheses matching preferences were moved to the new Keyboard preferences pane. The parentheses-matching preferences are now called delimiter-matching preferences and are shared with the Editor/Debugger.
New features and changes introduced in Version 7.2 (R2006a) are described here.
You can now use the
help function to get
the complete description for MDL-files. For example, run
help f14_dap.mdl
MATLAB displays the description of the F-14 Digital Autopilot High Angle of Attack Mode model in the Simulink software, as defined in its Model Properties > Description:
Multirate digital pitch loop control for F-14 control design demonstration.
New features and changes introduced in Version 7.2 (R2006a) are described here.
The
toolboxdir function
returns the absolute pathname to the specified toolbox. It is particularly
useful with the MATLAB Compiler product because the toolbox root
directory is different than in MATLAB.
The Visual Directory view was removed from the Current Directory browser. Most of the features it provided are accessible from the Current Directory browser standard view.
New features and changes introduced in Version 7.2 (R2006a) are
You can now use tab completion in the Editor/Debugger to complete function names and variable names that are in the current workspace. When you type the first few characters of a function or variable name and press the Tab key, the Editor/Debugger displays a list of all function and variable names that begin with those letters, from which you choose one.
It operates essentially the same way as the existing tab completion feature in the Command Window, with the exception that Editor/Debugger tab completion does not support completion of file and path names.
To enable tab completion in the Editor/Debugger, select File > Preferences > Keyboard, and then under Tab completion, select Tab key narrows completions. By default, the preference is selected.
With tab completion enabled in the Editor/Debugger, you can still include tab spacing, for example, to include a comment at the end of a line. To add tab spacing, include a space after the last character you type and then press Tab. Instead of showing possible completions, the Editor/Debugger moves the cursor to the right where you can continue typing.
If you press the Tab key to add spacing within your statements, you might instead get a completion for a function or see a list of possible completions. For example, if the preference for tab completion is on and you want to create this statement
if a=mate %test input value
where you press Tab after
mate to
achieve the spacing, the following happens instead
if a=material
This is because the tab completion preference completes
mate,
automatically supplying the
material function.
To achieve the spacing with Tab (as in previous
versions), either add a space after
mate and then
press Tab, or turn off the preference Tab key narrows
completions in Keyboard Preferences.
To set, clear, and navigate to bookmarks, use the menu items in the new Go menu, which were previously located in the Edit menu.
The Go To feature for navigating to line numbers, functions in M-files, and cells has moved to the new Go menu. It was previously located in the Edit menu.
Use the new Go menu items instead of Edit > Bookmark features and Edit > Go To.
Use Go > Back (and Go > Forward) to go to lines you previously edited or navigated to in a file, in the sequence you accessed them. The main benefit of this feature is going directly to lines of interest. As an alternative to the menu items, use the Back and Forward buttons on the toolbar.
The Editor/Debugger Keyboard and Indenting preferences pane was renamed to Tab preferences, and keybinding and parentheses-matching preferences were moved to the new Keyboard preferences pane. The parentheses-matching preferences are now called delimiter-matching preferences and are shared with the Command Window.
The M-Lint code analyzer, now built into the Editor/Debugger, continuously checks your code for problems and recommends modifications to maximize performance and maintainability. It performs the same analysis as the existing M-Lint Code Check report, but also provides these features:
Indicates the problem lines and associated M-Lint messages directly in the M-file rather than in a separate report.
Identifies (underlines) code fragments within a line that result in M-Lint messages.
Distinguishes messages that report errors (red) from warnings and suggestions (orange).
Continually analyzes and updates messages as your work so you can see the effect of your changes without having to save the M-file or rerun an M-Lint report.
To use or turn off M-Lint in the Editor/Debugger, select File > Preferences > Editor/Debugger > Language, and for Language, select
M.
Under Syntax, select Enable M-Lint
messages, or clear the check box to turn it off. Use the
associated drop-down list to specify the types of code fragments that
you want M-Lint to underline, for example, Underline warnings
and errors.
The
dbstop function now allows
you to stop at, (not in), a non M-file, allowing you to view code
and variables near it in your M-file. For example, if you want to
stop at the point in your M-file
myfile.m where
the built-in
clear function is called, run
dbstop
in clear; mymfile. Use this feature with caution because
the debugger stops in M-files it uses for running and debugging if
they contain the non M-file, and then some debugging features do not
operate as expected, such as typing
help functionname at
the
K>> prompt.
Cell mode, a useful feature in the Editor/Debugger for publishing
results and rapid code iteration, is now enabled by default. An M-file
cell is denoted by a
%% at the start of a line.
Any M-file that contains
%% at the start of a line
is interpreted as including cells. The Editor/Debugger reflects the
cell toolbar state and the cell display preferences, such as yellow
highlighting of the current cell and gray horizontal lines between
cells.
For quick access to information about using cells in M-files,
use the new information
button on the cell toolbar.
If you do not want cell mode enabled, select Cell > Disable Cell Mode.
MATLAB remembers the cell mode between sessions. If cell mode is disabled when you quit MATLAB, it will be disabled the next time you start MATLAB, and the converse is true.
In MATLAB Version 7.2, the first time you open an M-file
in the Editor/Debugger, the cell toolbar appears. If the M-file contains
a line beginning with
%%, an information bar appears
below the cell toolbar, providing links for details about cell mode.
To dismiss the information bar, click the close box on the right side
of the bar. To hide the cell toolbar, right-click the toolbar and
select Cell Toolbar from the context menu.
In previous versions, cell mode was off by default. The cell
toolbar and yellow highlighting or horizontal rules in M-files that
contain
%% at the start of a line might be unexpected.
If you used the
%% symbols at the start of a line
in M-files for a purpose other than denoting M-file cells, consider
replacing the
%% symbols with a different indicator,
or keep cell mode disabled.
You can set an Editor/Debugger display preference, Show lines between cells, to add a faint gray rule above each cell in an M-file. The line does not print or appear in the published M-file.
Previous versions included an Editor/Debugger display preference to Show bold cell titles. When cleared, cell titles appeared in plain text, rather than bold text. This is no longer a preference you can set — all cell titles now appear in bold text.
New features and changes introduced in Version 7.2 (R2006a) are
The M-Lint code analyzer is now built into the Editor/Debugger where it continuously checks your code for problems and recommends modifications to maximize performance and maintainability. For details, see M-Lint Automatic Code Analyzer Checks for Problems and Suggests Improvements.
The
mlint function
has changed slightly to support its use in the Editor/Debugger. Specifically,
the results returned from
mlint with the
-id option
are of a different form than for previous versions. If you rely on
the exact values, you need to make modifications.
For example, this is the form of a message returned in R2006a:
L
22 (C 1-9) 2:AssignmentNotUsed : The value assigned here to variable
'nothandle' might never be used.
This is the form of the message from R14SP3:
22 (C
1-9) InefficientUsage:AssignmentNotUsed : The value assigned here
to variable 'nothandle' might never be used.
There is now a numeric identifier, followed by the category,
for example:
2:AssignmentNotUsed.
If you do rely on the exact values, note that there have been
very few changes to the message text itself. For example, both R14SP3
and R2006a use the same text:
The value assigned here to
variable 'nothandle' might never be used.
Because of improvements being made to
mlint,
the values returned using the
-id option are expected
to change in the next version as well, particularly the numeric identifier
and category form. Do not rely on the exact values returned using
mlint with
the
-id option or you will probably need to make
modifications.
Use the new
profile
-nohistory option
after having previously set the
-history option
to disable further recording of history (exact sequence of function
calls). All other profiling statistics continue to accumulate.
The Profiler provides more accurate accounting. The total time you see with the Profiler GUI now matches total wall clock time from when you started profiling until you stopped profiling. Overhead associated with the Profiler itself is now applied evenly.
The
profile function now gathers and reports
time for recursive functions in the
FunctionTable's
TotalTime for
the function. In previous versions,
profile attempted
to break out
TotalRecursiveTime, which was not
always accounted for accurately. The value for
TotalRecursiveTime in
FunctionTable is
no longer used.
This change is also reflected in the Profiler GUI reports.
The
FunctionTable now includes the
PartialData value.
A value of
1 indicates the function was modified
during profiling, for example, by being edited or cleared, so data
was only collected up until the point it was modified.
In previous versions,
FunctionTable included
AcceleratorMessages although
it was not used.
AcceleratorMessages is no longer
included.
The Visual Directory view was removed from the Current Directory browser.
Most of the features it provided are accessible from the Current Directory browser standard view.
New features and changes introduced in Version 7.2 (R2006a) are described here.
You can now make designated text comments in cells appear italicized
in the published output. Use Cell > Insert Text Markup > Italic
Text, or use the equivalent markup symbols,
underscores, as in
_SAMPLE ITALIC TEXT_.
New features and changes introduced in Version 7.2 (R2006a) are described here.
The PVCS® source control system (from Merant) now has a new name, ChangeMan® (from Serena®), and the source control interface in MATLAB on UNIX platforms reflects this change.
If you use the ChangeMan software on UNIX platforms,
the
cmopts value
returned for it is
pvcs. If you use PVCS software,
ChangeMan in the Source Control Preferences
pane.
PVCS software users on UNIX platforms formerly selected
PVCS in
the Source Control Preferences pane. Now, PVCS software users
ChangeMan instead.
For sparse matrices, MATLAB now uses CHOLMOD version 1.0
to compute the Cholesky factor. CHOLMOD is a set of routines offering
improved performance in factorizing sparse symmetric positive definite
matrices. See the function reference pages for
chol,
spparms,
and
mldivide for
more information on how CHOLMOD is used by MATLAB.
In this release, MATLAB provides a second solver function,
ddesd,
in addition to the existing
dde23 function,
for delay differential equations (DDEs). This new solver is for use
on equations that have general delays. You supply
a function in the input argument list that returns the vector of delays
to be used by the solver. See the function reference page for
ddesd,
and Delay
Differential Equations in the MATLAB Mathematics documentation
for more information.
MATLAB now uses new versions of the Basic Linear Algebra Subroutine (BLAS) libraries. For Intel processors on Windows and Linux platforms, MATLAB supports the Math Kernel Library (MKL) version 8.0.1. For AMD processors on Linux platforms, MATLAB uses the AMD Core Math Library (ACML) version 2.7.
The
accumarray function
now accepts a cell vector as the
subs input. This
vector can have one or more elements, each element a vector of positive
integers. All the vectors must have the same length. In this case,
subs is
treated as if the vectors formed columns of an index matrix.
In this release, the MATLAB Data Analysis collection has been thoroughly revised to improve content organization and flow. In addition, most examples have been updated and streamlined.
Detailed reference pages are now available for
timeseries and
tscollection objects,
properties, and methods. You can access these reference pages in the
Help contents, under Data Analysis in
the MATLAB Function Reference.
In Time Series Tools, you can now use the Import Wizard to import
data from text files, such as
.csv,
.dat,
and
.txt.
Time Series Tools is now fully enabled on the Linux 64 platform.
On the Linux 64 platform, you no longer need to manually enable the Time Series Tools feature before starting Time Series Tools (as in MATLAB 7.1).
MATLAB support for Windows XP 64-bit edition enables you to handle much larger data sets. To learn more about memory allocation for arrays, see Memory Allocation.
MATLAB currently defaults to using Indeo codecs to compress
video frames when using
avifile/addframe or
movie2avi.
If you attempt to use
avifile and
addframe, or
movie2avi on
a Windows XP 64-bit platform without specifying the compression type,
an error message appears indicating the codec was not found. Nondefault
settings must be explicitly passed in when using these functions on
Windows XP 64 because Microsoft does not provide Indeo codecs on this
platform.
This issue does not affect 32-bit Windows XP installations.
To work around this issue, do the following:
Explicitly specify no compression
when creating the
avifile object or when calling
movie2avi.
Two examples of this are
aviobj = avifile('myvideo.avi', 'compression', 'none'); movie2avi(mov, 'myvideo.avi', 'compression', 'none');
Specify a codec for a compression that is installed. The ones that are included with Windows XP 64 are
IYUV — Intel YUV codec (c:\winnt\system32\iyuv_32.dll)
MRLE — Microsoft RLE codec (c:\winnt\system32\msrle32.dll)
MSVC — Microsoft Video 1 codec (c:\winnt\system32\msvidc32.dll)
For example, to use the Intel YUV codec, use the four-CC code:
aviobj = avifile('myvideo.avi', 'compression', 'IYUV');
Other codecs can be found at.
Note there are restrictions with some codecs. For example, some codecs can only be used with grayscale images.
MATLAB 7.2 introduces the following new features for regular expressions in MATLAB. For more information on these features, see Regular Expressions in the MATLAB Programming documentation.
Dynamic regular expressions — You can now insert MATLAB expressions or commands into regular expressions or replacement strings. The dynamic part of the expression is then evaluated at runtime.
Generating
literals in expressions — Use the new
regexptranslate function
when you want any of the MATLAB regular expression functions
to interpret a string containing metacharacters or wildcard characters
literally.
New parsing modes — Four matching modes (case-sensitive, single-line, multiline, and freespacing) extend the parsing capabilities of the MATLAB regular expression functions.
Warnings
display — Use the new
'warnings' option
with the regular expression functions to enable the display of warnings
that are otherwise hidden.
Files specified as arguments to
gzip,
gunzip,
tar,
and
zip can
now be specified as partial path names. On UNIX machines, directories
can start with
~/ or
~
username
/,
which expands to the current user's home directory or the specified
user's home directory, respectively. The wildcard character
* can
be used when specifying files or directories, except when relying
on the MATLAB path to resolve a filename or partial pathname.
Due to a bug introduced in MATLAB R14, the
str2func function
failed to issue a warning or error when called with an invalid function
name or a function name that includes a path specification. In the
R2006a release,
str2func now generates a warning
under these conditions. In a future version of MATLAB,
str2func will
generate an error under these conditions.
Any existing code that calls
str2func with
an invalid function name or a function name that includes the path
now generates a warning message from MATLAB. In a future version,
this will cause an error. You should note any such warnings when using
R2006a, and fix the input strings to
str2func so
that they specify a valid function name.
The
fopen function
has a new optional argument, a string that specifies a name or alias
for the character encoding scheme associated with the file. If this
argument is omitted or is the empty string (''), the MATLAB default
encoding scheme is used. Given a file identifier as the only argument,
fopen now
returns an additional output value, a string that identifies the character
encoding scheme associated with the file.
Low-level file I/O functions that read data from files, including
fread,
fscanf,
fgetl,
and
fgets,
read characters using the encoding scheme associated with the file
during the call to
fopen. Low-level file I/O functions
that write data, including
fwrite and
fprintf,
write characters using the encoding scheme associated with the file
during the call to
fopen.
Support for character encoding schemes has these limitations:
Surrogate pairs are not supported. Each surrogate
pair is read as a replacement character, the equivalent of
char
(26).
Stateful character encoding schemes are not supported.
Byte order marks are not interpreted in any special way. Your code must skip them if necessary.
Scanning numbers, using
fscanf,
is supported only for character encoding schemes that are supersets
of ASCII. (Most popular character encoding schemes, with the exception
of UTF-16, are such supersets.)
In V7.1 (R14SP3), low-level file I/O functions that read and
write data treated characters as unsigned bytes. Programs using such
functions as
fread may
have called
native2unicode to
convert input to MATLAB characters using a particular encoding
scheme. Programs using such functions as
fwrite may
have called
unicode2native to
convert output from MATLAB characters using a particular encoding
scheme.
For example, on a Japanese Windows platform, where the default
character encoding scheme is Shift-JIS, a program may have used
native2unicode and
unicode2native to
read and write Japanese text in this way:
fid = fopen(file); data = fread(fid, '*char')'; fclose(fid); dataU = native2unicode(data); % operate on data outData = unicode2native(dataU); fid = fopen(file, 'w'); fwrite(fid, outData, 'char'); fclose(fid);
Such a program would produce different and possibly incorrect
results in V7.2 (R2006a). The calls to
native2unicode and
unicode2native are
no longer necessary, because the
fread and
fwrite functions
now convert data to and from MATLAB characters using the character
encoding scheme specified in the calls to
fopen.
In V7.2 (R2006a), the example code can be simplified to produce correct
results:
fid = fopen(file); dataU = fread(fid, '*char')'; fclose(fid); % operate on data fid = fopen(file, 'w'); fwrite(fid, dataU, 'char'); fclose(fid);
Changes to code using fread, fgets, fgetl, and fscanf
If your code calls
native2unicode to convert
input to MATLAB characters using a specified (or default) encoding
scheme, you can, but do not have to, remove the calls to
native2unicode.
This applies to reading from an encoded file using any of the following:
fread with
precision set
to
'*char' or
'char=>char'
fgets or
fgetl
fscanf with the
format specifier
set to either
'%s' or
'%c'
When you remove a call to
native2unicode,
be sure that the call to
fopen supplies the same
encoding argument (if any) as the call to
native2unicode.
You may have used code like these examples in V7.1 (R14SP3):
indata = native2unicode(fread(fid, '*char')'); indata = native2unicode(fread(fid, 'char=>char')'); indata = native2unicode(fgets(fid)); indata = native2unicode(fgetl(fid)); indata = native2unicode(fscanf(fid, '%s')); indata = native2unicode(fscanf(fid, '%c'));
You can, but do not have to, remove the calls to
native2unicode in
V7.2 (R2006a):
indata = fread(fid, '*char')'; indata = fread(fid, 'char=>char')'; indata = fgets(fid); indata = fgetl(fid); indata = fscanf(fid, '%s'); indata = fscanf(fid, '%c');
Changes to code using fwrite
If your code calls
unicode2native to convert
output from MATLAB characters using a specified (or default)
encoding scheme, in most cases you must remove the calls to
unicode2native.
This is especially important if the encoding represents multibyte
characters.
This applies to writing an encoded file using
fwrite with
precision set
to either
'char' or
'char*1'.
When you remove a call to
unicode2native,
be sure that the call to
fopen supplies the same
encoding argument (if any) as the call to
unicode2native.
You may have used code like these examples in V7.1 (R14SP3):
fwrite(fid, unicode2native(outbuff), 'char'); fwrite(fid, unicode2native(outbuff), 'char*1');
You must remove the calls to
unicode2native in
V7.2 (R2006a):
fwrite(fid, outbuff, 'char'); fwrite(fid, outbuff, 'char*1');
The way in which MATLAB handles copying (or cutting) and
pasting children of axes such as lineseries, barseries, or contourgroup
objects has changed slightly. In previous releases, if no destination
axes was selected prior to pasting one or more such objects, they
would be pasted into the current axes (returned by the
gca function). MATLAB no
longer makes this assumption; if no axes is currently selected when
you paste graphic objects, a new axes is created in the destination
figure to contain them.
To avoid creating a new axes where you do not want to do so, you should be in plot edit mode and have selected a destination axes before using Edit -> Paste or typing CTRL-V. You can use the Plot Browser to conveniently select objects to copy and to paste into.
The Property Inspector (the GUI summoned by the MATLAB
inspect command)
has a new look, but no changed functionality. The inspector enables
you to view and change the most commonly used object properties. The
figure below compares the previous version (7.1, left) of the Property
Inspector with the new version (7.2, right):
Note that in addition to having a smaller font and wider line spacing, the new inspector locates pop-up menus at the right margin instead of between the two columns. Also, some icons have been redesigned.
The use of
'&' (ampersand) in the uimenu
'Label' property
string is changed for cases that use the constructs
'A&
B' and
'A&&B'. The changes bring
these constructs in line with the way
'&' is
used in other
'Label' constructs. See "Compatibility
Considerations" below for specific information.
Interpretation of
'Label' property strings
that use the following constructs is changed:
The string
'A& B' now produces
the menu label A& B with no underlined
mnemonic. Previously,
'A& B' produced the label A_B, in which the space is a mnemonic.
The string
'A&&B' now produces
the menu label A & B with no
underlined mnemonic. Previously,
'A&&B' produced
the label A&B with no mnemonic.
If you use either construct,
'A& B' or
'A&&B',
in your menu labels, verify that the new resulting label is acceptable
or change the
'Label' property to a new string.
The MATLAB document Creating Graphical User Interfaces is reorganized and rewritten. It now consists of three sections:
Getting Started—Leads you through the steps needed to create a simple GUI, both programmatically and using GUIDE.
Creating GUIs with GUIDE—Contains the information, previously included in Creating Graphical User Interfaces, that you need to create a GUI using GUIDE. This section is organized in workflow order with many small examples of the various steps. A final chapter provides advanced examples.
Creating GUIs Programmatically—For now, this section contains a summary of the available functions and complete code examples for three GUIs.
One GUI uses a variety of user interface controls to enable a user to calculate the mass of an object after specifying the object's density and volume.
Two other GUIs work together as an icon editor. One GUI, a color palette, is embedded in the other GUI, an icon editor. The color palette passes data to the icon editor whenever the GUI user selects a new color.
In MATLAB V7.2 (R2006a) on Linux and Linux x86-64
platforms, MEX-files built with
gcc must be recompiled
and relinked using
gcc version 3.4 or later. Rebuilding
is required because MATLAB V7.2 (R2006a) on Linux and Linux x86-64
platforms is built with
gcc version 3.4.
Changes in
gcc version 3.4 have caused incompatibilities
between MATLAB V7.2 (R2006a) and MEX-files built with
gcc versions
earlier than 3.4.
On Linux and Linux x86-64 platforms, MEX-files built
with
gcc versions earlier than 3.4 cannot be used
in MATLAB V7.2 (R2006a).
On Linux and Linux x86-64 platforms, MEX-files built
with
gcc version 3.4 or later cannot be used in
versions of MATLAB earlier than V7.2 (R2006a).
With the introduction of MATLAB for Windows x64, you
can now build 64-bit MEX-files. These MEX-files have the extension
.mexw64.
The
mexext command
returns
mexw64 in MATLAB for Windows x64.
MEX-files built using MATLAB for Windows (32-bit),
which have
.mexw32 extensions by default, cannot
be used in MATLAB for Windows x64.
By default, when MATLAB for Windows x64 is installed,
the
mex.pl and
mex.bat scripts
build MEX-files for a Windows x64 platform (with
.mexw64 extensions).
MATLAB V7.2 (R2006a) supports new compilers for building MEX-files on Windows and Windows x64 platforms:
Microsoft Visual C++ 2005, also informally called Visual C++ 8.0, part of Microsoft Visual Studio 2005
Intel Visual Fortran 9.0
When you build a MEX-file or an Engine or MAT application using Intel Visual Fortran 9.0, MATLAB requires an environment variable to be defined, depending on whether you are building in MATLAB for Windows (32-bit) or MATLAB for Windows x64:
MATLAB for Windows (32-bit): The environment
variable
VS71COMNTOOLS must be defined. The value
of this environment variable is the path to the
Common7\Tools directory
of the Visual Studio .NET 2002 or 2003 installation directory.
(Intel Visual Fortran requires Visual Studio .NET 2002 or
2003 on 32-bit Windows platforms.) This environment variable
is commonly defined by the Visual Studio .NET 2003 installation
program.
MATLAB for Windows x64: The environment
variable
MSSdk must be defined. The value of this
environment variable is the path to the installation directory for Microsoft Platform SDK for Windows Server 2003.
(Intel Visual Fortran requires Microsoft Platform SDK for Windows Server 2003
on Windows x64 platforms.) This environment variable is not commonly
defined by the Microsoft Platform SDK installation program.
MATLAB provides a preprocessor macro,
mwPointer ,
that declares the appropriate Fortran type representing a pointer
to an
mxArray or to other data that is not of a
native Fortran type, such as memory allocated by
mxMalloc.
On 32-bit platforms, the Fortran type that represents a pointer is
INTEGER*4;
on 64-bit platforms, it is
INTEGER*8. The Fortran
preprocessor translates
MWPOINTER to the Fortran
declaration that is appropriate for the platform on which you compile
your file.
MATLAB V7.1 (R14SP3) included a Windows Engine and
MAT options file named
df66engmatopts.bat. This
file contained options for Compaq Visual Fortran version 6.6
for use in building Fortran engine or MAT stand-alone programs. The
file name
df66engmatopts.bat originated with an
earlier version of the Fortran compiler, named Digital Fortran.
In V7.2 (R2006a), this file has been renamed
cvf66engmatopts.bat to
match the Compaq Visual Fortran product name.
You may need to change any scripts that depend on the earlier name for the options file.
MATLAB V7.1 (R14SP3) included MEX, Engine, and MAT options files for a number of Windows C and Fortran compilers that were untested. These options files are not included in V7.2 (R2006a). The unsupported compilers, and the supported compilers that replace them, are:
If you were using an untested compiler with a previous version of MATLAB, replace it with a supported compiler. You may need to recompile your MEX-files or applications.
In V7.1 (R14SP3), many MAT-file access, MX array manipulation, MEX-files, and MATLAB engine functions were declared obsolete in the External Interfaces Reference documentation. These functions are no longer documented in V7.2 (R2006a).
This section lists the obsolete functions removed from the documentation, along with replacement functions, if any.
Most of the functions listed as obsolete in this section are unsupported in V6.5 (R13) and later versions. Some obsolete functions are unsupported in earlier versions.
If this section lists a replacement for an obsolete function, change any code that refers to the obsolete function to use the replacement instead.
If you must use an obsolete function in a MEX-file or application,
use the
-V5 option to
mex when
you build the file.
MATLAB supports the use of Microsoft ActiveX controls that require licensing at both design time and runtime.
See the
actxcontrol function
for information on how to specify a design-time license key.
See Deploying ActiveX Controls Requiring Run-Time Licenses for information on how to use ActiveX Controls that require runtime licenses in your MATLAB application.
MATLAB defines a data type to be used with controls requiring input defined as type VT_DATE. See Using Date Data Type for more information.
MATLAB supports dynamic linking of external libraries only on 32-bit Windows systems and 32-bit Linux systems. See Calling C Shared Library Functions from MATLAB for more information.
New features and changes introduced in this version are described here.
The behavior of MATLAB software when started on Microsoft Windows platformswith
the
-nodesktop option has changed. The MATLAB Command
Window no longer displays a menu bar or toolbar. This change resolves
a number of problems that occurred in previous versions when running MATLAB in
-nodesktop mode
on Windows platforms.
Use equivalent functions instead of the menu and toolbar.
Instead of using the File > Preferences menu to modify
the font or colors used in the Command Window, run
preferences
-nodesktop. For more information, see preferences Function Now Supports -nodesktop Option.
New features and changes introduced in this version are organized by these topics:
On Apple Macintosh platforms, figure windows are now dockable.
You can now position the pointer at the intersection of three or four tools or documents to resize all of them at once.
There are now menu items you can select to move and resize the active tool in the desktop. Use the menu item mnemonics to perform those action with the keyboard. For example, if the Command Window is in the desktop along with other tools, press Ctrl+0 (or click in it) to make the Command Window the active tool. Then press Alt+D, V, which is the mnemonic equivalent for selecting Desktop > Move Command Window. The pointer becomes an arrow. Use the arrow keys to move an outline of the Command Window to a new dockable location. Press Enter to dock it there, or press Esc to return the Command Window to its original position.
You can now adjust the width of a name in the document bar when the bar is at the top or bottom of the window.
In previous versions, selecting Desktop > Document Bar displayed only menu items for positioning the document bar. Now, there are additional menu items. The same change was made to the context menu for the document bar. To access the menu items for positioning the document bar, select Desktop > Document Bar > Bar Position.
The Desktop > Document Bar now includes these items: Alphabetize, Width, and Move documentname On Bar. With their inclusion in the menu, you can use the keyboard to access these features via mnemonics. For example, on Windows platforms, press Alt+D, M, A as a shortcut to for Desktop > Document Bar > Alphabetize.
When arranging documents in desktop tools, you can choose Window > Left/Right Split or Window > Top/Bottom Split to show two documents at once in the tool. Those menu items are now called Left/Right Tile and Top/Bottom Tile. This change was made to avoid any confusion with the Editor/Debugger's new split screen feature.
There is a new preferences directory,
R14SP3.
This is the directory name returned when you run the
prefdir function.
When you install R14SP3, MATLAB migrates files from your existing
preference directory,
R14, to the new directory,
R14SP3.
Changes made to files in the directory when you run R14SP3 are not
used when you run previous R14 releases.
This represents a change in the preference directory MATLAB uses for a minor release, and was done to prevent serious backwards compatibility problems. It is primarily relevant if you use R14SP3 and previous R14 releases. If you only run R14SP3, or run R14SP3 with R13 or R12 releases, you will not be affected by this change.
In the past, minor releases and the associated major release
used the same preferences directory. For example, R13 and R13SP1 shared
the
R13 preferences directory. That continues to
be true for all previous releases, but is not true for R14SP3 and
beyond. The
R14 preferences directory will be shared
by the R14 through R14SP2 releases, but the new
R14SP3 preferences
directory is only used by R14SP3. This means that changes made to
files in the directory while running R14SP3 re not used when you run
a previous R14 releases, and the reverse is true. For example, statements
added to the Command History when you run R14SP3 are not in the Command
History when you run R14SP2.
For more information, see the reference page for
prefdir.
This change was made to prevent major backwards compatibility
problems. Use the
R14SP3 preferences directory
instead of the
R14 directory. If you use the
prefdir function
and have code that relies on the result being
R14,
you will need to modify that code.
In Preferences > Fonts, select the new antialiasing preference to provide a smoother appearance to desktop fonts.
There is a new Colors preference for specifying the color of hyperlinks in the Command Window and the Help browser Index pane. In previous releases, this preference only applied to the Command Window hyperlinks and was accessed via Command Window preferences.
Run
preferences -nodesktop after starting MATLAB on Windows platforms
with the
-nodesktop option to change Command Window
font and colors via a special Preferences dialog
box.
To set other available preferences for the Command Window after
starting MATLAB with the
-nodesktop option,
run
preferences and use the resulting Preferences dialog box for all tools and products.
Note that changes you make to font and color preferences in this dialog
box do not apply to the Command Window.
If you add your own toolbox to the Start button,
you can use the schema file for its
info.xml file,
matlabroot
/sys/namespace/info/v1/info.xsd. MATLAB now
automatically validates your
info.xml file against
this schema when you click the Start button
after updating and refreshing your
info.xml file.
If your
info.xml contains invalid constructs,
you will see warnings in the Command Window until you correct the
problems.
In the Edit menu, the name of the Paste Special item has been replaced by Paste to Workspace, but the functionality remains the same. It opens the Import Wizard so you can paste the clipboard contents to the workspace in MATLAB.
You can now rename shortcut categories.
New features and changes introduced in this version are
There is a new Command Window preference, Tab key narrows completion. When selected, with a list of possible completions in view, type another character and press Tab to further narrow the list shown. Repeat to continue narrowing the list. This behavior is similar to tab completion behavior in releases prior to R14.
In previous versions, when completing filenames or function names, a name sometimes appeared twice in the completion list, once with the file extension and once without. Now the entry appears only once..
The preference for specifying the hyperlink color has moved from the Command Window preferences pane to the Colors preferences pane. The hyperlink color now also applies to links in the Help browser Index pane.
Use the Colors preference pane to specify the hyperlink color, and be aware that it also impacts the Help browser Index pane color.
New features and changes introduced in this version are
You can now specify the color for links in the Help browser Index pane using the Colors preferences pane. The hyperlink color also applies to links in the Command Window, so changes you make to the preference apply to both tools.
Stylistic changes were made to the Demos interface in the Help browser. On the summary page for a product, each demo appears with a thumbnail image that provides an indication of the type of output it creates, as well as an icon representing the type of demo (M-file, M-GUI, model, or video).
In this release, all M-file demos include the Run
in the Command Window link, which executes the demo via
echodemo.
In previous releases, some M-file demos provided a Run hyperlink in the display pane. When you
clicked Run, the M-file demo executed
in a GUI via the
playshow function. An example
of this type of demo is the MATLAB Mathematics Basic Matrix Operations
demo,
intro.m. In this release, the Run hyperlink for these M-file demos has been
replaced by Run in the Command Window.
It executes the demo step by step in the Command Window via the
echodemo function.
Double-clicking this type of M-file demo in the Navigator pane no
longer runs the M-file demo, but opens the M-file in the Editor/Debugger
where you can run it step by step using Cell > Evaluate Current Cell and Advance.
The new Run in Command Window hyperlink represent a change in the way demos run.
The
echodemo function MATLAB uses to
run M-file demos in the Command Window runs the demos as scripts.
The
playshow function MATLAB used to run M-file
demos in previous releases ran the demos as a function. This means
that now the demo's variables are created in the base workspace. If
you have variables in the base workspace when you run an M-file demo,
and the demo uses an identical variable name, there could problems
with variable name conflicts. For example, your variable could be
overwritten. The demo's variables remain in the base workspace after
the demo finishes running until you clear them or quit MATLAB.
Another change is that figures are not automatically closed when you
end the demo.
There is a new
echodemo function that replaces
playshow.
The Demos browser uses
echodemo to execute M-file
demos when you click the Run in the Command
Window link.
The
playshow function is deprecated in
favor of the
echodemo function. In a future release,
the
playshow function will be removed. In practice,
both
echodemo and
playshow are
helper functions for running demos. It is unlikely you would ever
call either
playshow or
echodemo directly,
and especially not in M-files.
You now can add published M-file demos to favorites.
If you add demos for your own toolbox, you can use the new
<type> tag
for a
<demoitem> to identify the type of
demo in your toolbox's
demos.xml file.
You now can view bugs fixed with this release, as well as any known bugs using the Bug Reports database in the Support section of the MathWorks Web site. The MathWorks continuously updates the database to add any newly found bugs and compatibility issues, as well as any new workarounds and solutions. The system includes bugs found and fixed in R14SP2 and later releases.
New features and changes introduced in this version are described here.
The Find Files tool has been enhanced. It now allows you to search all file types except those specified. It also lets you ignore files larger than a specified size. Along with enhancements to the Find Files tool, some minor feature changes were made, including the removal of the Restore Defaults button.
In the next release, the Current Directory browser will no longer
support the Visual Directory view (accessed using the
toolbar button).
Some features currently available using the Visual Directory view will not be available in the next release when the feature is removed.
New features and changes introduced in this version are
The Editor/Debugger now supports a horizontal or vertical split screen for displaying two different parts of the same document at once. To split the screen, select Window > Split Screen and the splitting action you want, for example, Top/Bottom. Alternatively, drag the splitter bar that appears above the vertical scroll bar or to the left of the horizontal scroll bar. To remove the splitter, drag it to an edge of the window.
You can set a preference to highlight the current line, that is, the line with the caret (also called the blinking cursor). This is useful, for example, to help you see where copied text will be inserted when you paste. To highlight the current line, select Preferences > Editor/Debugger > Display and under General Display Options, select the check box for Show caret row highlighting. You can also specify the color used to highlight the line.
You can now use the Text > Comment feature to comment
selected lines in Sun Microsystems Java, ANSI® C, and
C++ program files. This adds the
// symbols at
the start of the selected lines. Similarly, Text > Uncomment removes the
// symbols
from the front of selected lines in Java, C, and C++ program
files.
There is a new Editor/Debugger language preference for HTML files to specify block indenting. By default, the preference is selected so block indenting applies when typing text in HTML files.
In addition, you now can select Text > Smart Indent to apply smart indenting to selected text in HTML files.
When typing text in HTML files, you will automatically see block indenting because the preference is selected by default..
With the Emacs key bindings preference selected, use Ctrl+X, H to select all.
Use new items in the Text menu to change the case of selected text. You can also use the keyboard equivalents for changing case that existed in previous versions—these are shown in the menu next to each item.
The Editor/Debugger no longer displays the current nested function name in the status bar. Look in the M-file to view the current nested function name.
New features and changes introduced in this version are described here.
With Directory Reports displayed in the Web browser, you can use these two new buttons:
Rerun This Report — This updates the currently displayed report after you have made changes to the report options or to any files in the current directory.
Run Report on Current Directory — Use this after changing the current directory to run the same type of report for the new current directory.
These new buttons replace the Refresh button.
There is a new option for the
mlint function,
'-notok' you
can use to override any statements that include
%#ok (the
symbol you add to the end of a line instructing
mlint to
ignore the line). That is,
mlint will run for all
lines in the file and will not ignore any statements.
When you run the
mlint function, the line
number in the messages displayed is a hyperlink that when clicked,
opens the file in the Editor/Debugger scrolled to that line number.
There is now a button
on the MATLAB desktop
toolbar to open the Profiler.
New features and changes introduced in this version are described here.
The
notebook function setup behavior and
syntax have changed.
When you run
notebook('-setup'), MATLAB automatically
obtains all the information about your Microsoft Word application
from the system registry for yourWindows environment and you
are no longer prompted to supply the information.
In previous versions, when you configured Notebook, you ran
notebook ('-setup')
Notebook then prompted you to specify the version of Word you
were using, and if needed, the location of Word and its template directory.
You could supply the information using optional arguments to the
notebook function:
notebook('-setup', wordversion, wordlocation, templatelocation)
Now, when you run
notebook('-setup'), MATLAB automatically
obtains all the Word information from the registry for yourWindows environment.
If you use
notebook with the
wordversion,
wordlocation,
and
templatelocation arguments in any of your files
(for example,
startup.m), remove those arguments
in your files. If you specify the optional arguments, the
notebook function
runs and issues a warning, but ignores the values. In a future release, MATLAB will
issue an error when it encounters
notebook with
these arguments.
MATLAB Notebook supports the Microsoft Word version 2000 application. Notebook also supports the Microsoft Word 2002 application and Microsoft Word 2003 application, both for the Microsoft Windows XP platform.
As of MATLAB 7.1 (R14SP3), Notebook no longer supports the Microsoft Word 97 application.
The following functions are new in R14SP3:
A new function name can potentially introduce a backward incompatibility since it can, under certain circumstances, override a variable with the same name as the new function. This is especially true for names that are commonly used as variable names in program code.
An example of such a function name is the
mode function,
introduced in this release. If you have M-file programs that use
mode as
a variable name, it is possible under certain conditions for MATLAB to
interpret these variable names as function names by mistake. Read
the section Variable
Names in the MATLAB Programming documentation to find
out how to avoid having these variables misinterpreted.
If your program code uses a user-written function named
mode,
you may find that MATLAB calls the new MATLAB
mode function
instead of your own
mode function. To correct
this, modify your MATLAB path by placing the location of your
own
mode function closer to the beginning of
the path string than the location of the MATLAB
mode.m file.
The help for the
addpath and
rmpath functions
explains how to modify your MATLAB path.
MATLAB Version 7.1 adds the following new features to the
accumarray function:
The data type for the
val input
can be any numeric type, or logical, or character.
The data type for the
subs input
can be any numeric type.
You can use a cell array of separate index vectors
for the
subs input.
When you specify a
function input
argument, the value returned by
accumarray is given
the same class as the values returned by that function.
You can control the sparsity of the value returned
by
accumarray by specifying the new input argument
issparse.
There is a new integration property called
NonNegative that
you can use when applying ODE initial value problem solvers. If you
need to solve a problem in which certain components of the solution
must be nonnegative, use the
NonNegative property
to impose nonnegativity constraints on the computed solutions.
See Nonnegative Solutions under Calculus in the MATLAB Mathematics documentation for more information on this feature.
The
rand function
now supports a method of random number generation called the Mersenne
Twister. The algorithm used by this method, developed by Nishimura
and Matsumoto, generates double precision values in the closed interval
[2^(-53),
1-2^(-53)], with a period of
(2^19937-1)/2.
For a full description of the Mersenne twister algorithm, see.
The following feature was released in MATLAB 7.0, but was undocumented until this release.
The command
svd(A,'econ') returns economy
decomposition on matrices having few rows and many columns as well
as those with many rows and few columns.
svd(A,0) continues
to behave as it always has, namely to only return economy-sized decomposition
on matrices having many rows and few columns.
The location of the LAPACK libraries has been changed. These libraries are now located in
extern/lib/win32/microsoft/libdflapack.lib extern/lib/win32/microsoft/libmwlapack.lib
This change impacts you only if you build MEX-files that call LAPACK and BLAS functions.
The section of the MATLAB Mathematics documentation on "Data Analysis and Statistics" has been moved to a new MATLAB Data Analysis book. This book documents MATLAB functions and tools that support basic data analysis, including plotting, descriptive statistics, correlation, interpolation, filtering, and Fourier analysis. It also documents the new object-oriented command-line API for analyzing time-series data.
The MATLAB 7.1 documentation includes a new Data Analysis book that describes how to use MATLAB functions and tools for common data-analysis tasks:
Plotting
Filtering
Interpolation
Descriptive statistics
Correlation
Data fitting using linear regression
Fourier analysis
Time-series analysis
Some of the content in Data Analysis is incorporated from the Mathematics and Graphics books, such as data plotting, descriptive statistics, data fitting, and Fourier analysis. All information about time-series analysis is new.
You can analyze time-series data using the new
timeseries and
tscollection objects
and methods, as well as the Time Series Tools graphical user interface.
This new functionality supports the following:
Representation for univariate or multivariate MATLAB time series and Simulink logged-signals data
Built-in management of time units
Removal or interpolation of missing data
Resampling of data
Arithmetic operations for
timeseries objects
Synchronization of time series
To manually enable Time Series Tools on the Linux 64 platform, type the following at the MATLAB prompt:
rehash toolboxcache feature('TimeSeriesTools',1)
This version introduces the following new functions:
A new function name can potentially introduce a backward incompatibility since it can, under certain circumstances, override a variable with the same name as the new function. This is especially true for names that are commonly used as variable names in program code. Read the section Variable Names in the MATLAB Programming documentation to find out how to avoid having these variables misinterpreted. | http://www.mathworks.com/help/matlab/release-notes-older.html?nocookie=true | CC-MAIN-2015-22 | refinedweb | 49,914 | 55.03 |
.
Developers often have to use the same application bar on several pages in their project and they usually end up copying and pasting the XAML and C# code, which isn't recommended..
1. Why Build a Localized App?
Windows Phone users are not all native English speakers. In fact, only 34% of them speak English. This means that 66% speak a language other than English and that is why it's important to build localized apps..
In this tutorial, we will be translating all of our app resources into French and Arabic. Here are some quick tips to keep in mind before we start:
- Make sure to name all the resources you'll be using with meaningful names, because we will be referring to string resources by their name, not their value. Try to give each resource a unique name that makes sense.
- Try to gather all of your string resources in AppResources.resx, including button titles and error messages.
- Enable multiline support and text wrap in controls.
- Always save your work and make sure to rebuild your project often to implement the changes you make to AppResources.resx.
2. Culture & Language Support
Currencies, numbers, date, time, and region formats differ from culture to culture. Fortunately, the
CultureInfo class takes care of these details for each language. Actually, you can even retrieve the current cultural data of the phone and show its information in a
MessageBox using a single line of code:
MessageBox.Show(CultureInfo.CurrentCulture.Name);
However, the
InitializeLanguage() function in App.xaml.cs does the work automatically each time the app is launched and sets
RootFrame.Language based on the value of the
AppResources.ResourceLanguage resource. Note that if your app doesn't support any language other than en-US (English, United States), the app uses the neutral and default AppResources.resx file of the project.
3. Localizing Your App
Step 1: Adding Resources and Binding Text Elements
In this tutorial, we will build a one-page app that will show the user some wise, old sayings. To start, in MainPage.xaml, we'll add a few
TextBlock elements without specifying their content by adding the following two lines of code in the parent
ContentPanel grid:
<TextBlock TextWrapping="Wrap" FontSize="30"></TextBlock> <TextBlock TextWrapping="Wrap" FontSize="30"></TextBlock>
We also make the following changes in the default AppResources.resx file:
- changing the
ApplicationTitlestring value
- adding two strings as shown in the following screenshot
Let's now go back to MainPage.xaml. After adding the strings we'll need in our app, we set the
Text property of the
TextBlock control to specify the content of each
TextBlock. (name),
ApplicationTitle.
Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}"
Each of the two
TextBlock elements will have a saying as well. We'll just use the same line of code, replacing the
ApplicationTitle attribute with our saying's attribute. This is what your code should look like:
>
This is what the result looks like:
We now only need to add other languages and translate.
Step 2: Adding Other Languages
To add another language, go to the project's properties by right-clicking the project in the Solution Explorer window. Make sure to access the project's properties, not the properties of the solution.
In the Application Tab you should see the Supported Languages.
Once you save the changes, you'll notice that Visual Studio has automatically generated two new .resx files:
- AppResources.ar.resx for Arabic
- AppResources.fr.resx for French
Note that the newly generated files have the same content as AppResources.resx. You shouldn't change the attributes (names). You only need to translate the values.
3. Using the Multilingual App Toolkit.
You can download the Multilingual App Toolkit as a Visual Studio extension from Microsoft's developer website. After installing the toolkit, select Enable Multilingual App Toolkit from the Tools menu.
After enabling the MAT, Visual Studio generates new .xlf files for each of the supported languages you added earlier. This means that you can generate machine translations by right-clicking an .xlf file and choosing Generate machine translations. You can also modify the translated string resources in the target tag in all the .xlf files.
4. How to Test a Localized App?
You can test a localized app using the emulator.
- Debug your project and go to Emulator Settings.
- Navigate to the Language tab and add a new language. It's important to not restart your phone.
- Navigate to the Region tab and choose your region.
- Restart the phone.
When the phone restarts, Visual Studio may throw an error, losing the connection with the emulator. After restarting the phone, debug the project again. This is what the app looks like for Arabic:
Now that we're done with string resources, we'll add a localized application bar to our app.
5. Creating a Localized Application Bar
Step 1: Creating the Application Bar
In this step, we'll create an application bar that we can use anywhere in our app. To do so, we'll make use of the App.xaml file, in which we define global XAML styles and resources that will be used across the application.
In the
ApplicationResources tag in App.xaml, we add an application bar with only an icon and a menu item. Don't forget to give a name to the application bar using the
x:key attribute so that we can reference it later.
<shell:ApplicationBar x: <shell:ApplicationBarIconButton <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem </shell:ApplicationBar.MenuItems> </shell:ApplicationBar>
In the
RateReview_Click event handler, we use one of the phone tasks to navigate users to the store if they want to leave a review or rate the app. As for the
Help_Click event handler, we just add some C# code to navigate between the different pages. Note that I added a new XAML page, AboutTheApp.xaml, in which we show information about our app.
In App.xamls.cs, add the following statement so that we can benefit from the phone tasks class:
using Microsoft.Phone.Shell;
When the user taps the rate and review menu item, the app will open the store on a page where the user can rate and/or review the app. We use a
MarketPlaceReviewTask like this:
MarketplaceReviewTask review = new MarketplaceReviewTask(); review.Show();
As for the
Help_Click event handler, the following code snippet takes care of navigating between the two pages:
(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/AboutTheApp.xaml", UriKind.RelativeOrAbsolute));
Step 2: Referencing the Application Bar
After creating the application bar that we want to use, we add a new instance of the application bar using the below code snippet in MainPage.xaml.cs and then we make it refer to the one in App.xaml.
InitializeComponent(); ApplicationBar = new ApplicationBar(); ApplicationBar = ((ApplicationBar)Application.Current.Resources["myAppBar"]);
We haven't used the AppResources at all for building the application bar, which means that text properties are already set independently from the phone's culture. Actually, we can't really use bindings when dealing with application bars.
This is why we'll reference the application bar we created earlier in App.xaml.cs and change the strings value, using a simple block of a code just after the
InitializeComponent() method. The strings used are also added to AppResources.resx.
//;
After adding the string resources, translate them and rebuild the project. Finally, add the information of the AboutTheApp.xaml page. This is what the result looks like:
Conclusion.
And finally, we got to know the way we use phone tasks to help users rate and review the app in the store. Feel free to download the sample project and ask any question that crosses your mind in the comments below.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://code.tutsplus.com/tutorials/working-with-app-resources-on-windows-phone--cms-24262 | CC-MAIN-2018-22 | refinedweb | 1,304 | 57.37 |
Hi everyone. I just spent a very long time tracking down a bug that boiled down to some lingering open file handles, all duplicates of STDERR, that were causing an HTTP connection to remain open longer than it should have.
These "rogue" filehandles had been opened by a module that my code did not load explicitly. In fact, I was not even aware that my code was using this module at all, since it comes in at the end of a long dependency chain...
To avoid this sort of bug in the future, I'm looking for a way for my code to find all the open non-lexical file handles that are duplicates of either STDOUT or STDERR.
Before I go off on a clueless hacking of the symbol table, or some other equally harebrained scheme, I thought I'd ask here if anyone knew of a good way to do what I'm trying to do.
Many thanks in advance!
the lowliest monk
Cheers - L~R
I would use lsof(8)/linux for such problems, because in case some
XS code has done the dup(2), you may not have much luck finding
anything related in the symbol table...
While symbol table hackery is imperfect, it is a reasonable next step after that point.
Both approaches are imperfect. But ultimately, I consider the info
you can retrieve via lsof more useful than what you might find
when digging around in the symbol table. The two main issues with the
symbol table are:
I'd be interested in hearing more details.
I see from the replies I've gotten so far that I did not explain the problem well enough, so here's a second attempt. The application is a CGI script that is meant to perform a lengthy calculation. In its normal operation, when first accessed, it forks a child (call it C) that will perform the calculation and cache the result. The parent (call it P) just returns a short response that includes a job id, and exits immediately. In pseudo-perl, the logic looks like this:
my $job_id = new_job_id();
$SIG{ CHLD } = 'IGNORE';
die "fork failed: $!" unless defined( my $pid = fork );
if ( $pid ) {
# the parent branch (process P)
print_response( $job_id );
}
else {
# the child branch (process C)
# NEED: close_all_dups_to_stdout_and_stderr();
close STDOUT;
close STDERR;
compute_and_cache_results( $job_id );
}
exit;
[download]
Upon receiving the initial response, the client can then use the included job id to periodically check with the server for information on the job's percent completion, and eventually to retrieve the finished results. This allows the client to provide some feedback to the user.
I noticed recently that the client was freezing after sending the request, and not displaying any indication of progress. Instead, after some time of apparent inactivity, it would display the finished results all at once.
The immediate reason for this was that the parent (P) was lingering around as a zombie after exiting (with Apache as its parent), which caused the connection to remain alive until the child (C) finished.
After a lot of trial and error, I narrowed the problem down to a few open() statements in Parse::RecDescent. If I comment out these statements, the code once again works fine: P's process terminates immediately after it exits, and the client receives the job id right away, soon enough to be useful.
I want to avoid another lengthy debugging ordeal in the future, if I ever decide to use a module that somehow leads to a similar case of leftover filehandles.
What I need is a way to implement close_all_dups_to_stdout_and_stderr. Without it, the defunct P lingers around as a zombie until C terminates, which defeats the purpose of forking the child in the first place. It is this lingering P that causes the HTTP connection to remain open far too long.
Now, L-R, the docs for fileno do in fact suggest that it would come in handy here, but, to my surprise, it does not work as advertised. Below is the line in the original module's code, followed immediately by two debugging lines that I've added:
open (ERROR, ">&STDERR");
printf STDERR "fileno( STDERR ): %d\n", fileno( STDERR );
printf STDERR "fileno( ERROR ): %d\n", fileno( ERROR );
[download]
fileno( STDERR ): 2
fileno( ERROR ): 6
[download]
BTW, if anyone cares to verify all of this, the sticking points are in Parse::RecDescent, v. 1.94, lines 2847, 2865, and 2876.
But even if fileno behaved as advertised, to implement close_all_dups_to_stdout_and_stderr in a general way I need a way to find all the open filehandles, so that I can test them with fileno against STDERR and STDOUT. This is what I'd like to figure out how to do cleanly.
almut, I had the same idea of using lsof, but, here again, the results surprised me. I tried the following (somewhat brutal) experiment:;
unless ( open $fh, '<&=', $fd ) {
print "no luck with $line";
}
# per recommendation of The Perl Cookbook, 2nd Ed, p. 262
print "closing $fd\n";
close $fh or die $!;
}
print Parse::RecDescent::ERROR "Nya, nya! I'm still open!\n";
}
__END__
output:
closing 0
closing 1
closing 2
closing 4
closing 5
closing 6
no luck with lsoftest 14113 yt 7r FIFO 0,6 891817
+71 pipe
Nya, nya! I'm still open!
[download]
Bottom line: the problematic handle remains open even after this. And so does STDOUT, for that matter. I'm still scratching my head about this one as well. Cluebricks welcome.
BTW, moving the loading of PRD to after the fork did not help (and would be a very inconvenient solution in any case).
I hope this clarifies the situation.
It's not necessarily the file descriptor number that matters, but
rather the OS-internal info (data structure) it refers to. If you dup(2), (">&" in Perl),
you get another file descriptor (new number) holding the same info.
Consider the following simple sample CGI, which hangs (for
essentially the same reason that you've described):
#!/usr/bin/perl
if (my $pid = fork) {
print "Content-Type: text/plain\n\n";
print `lsof -p $$ -a -d 0-20`; # for parent
print `lsof -p $pid -a -d 0-20`; # for child
} elsif (defined $pid) {
# this creates a dup of file descriptor 2, as descriptor 3
open STDERR2, ">&STDERR" or die "Can't dup STDERR: $!";
close STDOUT;
close STDERR;
# this makes the parent process hang for 5 sec, because
# Apache waits for the pipes associated with stdout/stderr
# to be closed CGI-side
sleep 5;
exit;
} else {
die "Couldn't fork: $!";
}
[download]
The output you get is something like
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
hang.pl 25839 apache 0r FIFO 0,6 429306451 pipe
hang.pl 25839 apache 1w FIFO 0,6 429306452 pipe
hang.pl 25839 apache 2w FIFO 0,6 429306453 pipe
hang.pl 25839 apache 3r FIFO 0,6 429306456 pipe
hang.pl 25839 apache 9w FIFO 0,6 428685687 pipe
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
hang.pl 25840 apache 0r FIFO 0,6 429306451 pipe
hang.pl 25840 apache 3w FIFO 0,6 429306453 pipe
hang.pl 25840 apache 9w FIFO 0,6 428685687 pipe
[download]
As you can see in the NODE column, the unclosed (dup'ed) FD 3 in the
child (the second lsof output) is the same node (i.e. 429306453) as
FD 2 (stderr) in the parent. This is why Apache is still waiting,
despite FD 1/2 already having been closed.
OK, I figured out why my original lsof experiment failed. I was using the recipe from the Perl Cookbook incorrectly. The following works as expected:
use warnings FATAL => 'all';
no warnings 'once';
use strict;;
print "closing $fd\n";
closefd( $fd );
}
printf Parse::RecDescent::ERROR
"Nya, nya! I'm still open! (BTW, I'm fileno %d)\n",
fileno( Parse::RecDescent::ERROR );
}
use Inline C => <<EOC;
#include <unistd.h>
void closefd( int fd ) {
if ( close( fd ) )
Perl_croak( aTHX_ "closefd( %d ) failed", fd );
return;
}
EOC
__END__
[download]
I still need to figure out how to selectively close those handles that correspond to STDERR and STDOUT, but with the clues++ I got from almut, I think I should be able to do it.
I still need to figure out how to selectively close those handles that correspond to STDERR and STDOUT,
Would it not be sufficient to simple close all open files in your child?
use POSIX ();
...
}
else { ## child
POSIX::close( $_ ) for 0 .. 255; ## Or higher if that's a possibil
+it | http://www.perlmonks.org/?node_id=754484 | CC-MAIN-2015-22 | refinedweb | 1,413 | 68.7 |
- 1) How many memory layers are in the shared pool?
Ans: The shared pool portion of the SGA contains three major areas: library cache(contains parsed sql statements,cursor information,execution plans), dictionary cache (contains cache -user account information,priveleges information,datafile,segment and extent information), buffers for parallel execution messages, and control structure.
2) How do you find out from the RMAN catalog if a particular archive log has been backed-up?
Ans: list archivelog all;
3) How can you tell how much space is left on a given file system and how much space each of the file system’s subdirectories take-up?
Ans: df -kh and du-sh
4) Define the SGA and:
i) How you would configure SGA for a mid-sized OLTP environment?
ii) What is involved in tuning the SGA?
Ans: SGA: The System Global Area (SGA) is a group of shared memory areas that are dedicated to an Oracle “instance” (an instance is your database programs and RAM). All Oracle processes use the SGA to hold information. The SGA is used to store incoming data (the data buffers as defined by thedb_cache_size parameter), and internal control information that is needed by the database. You control the amount of memory to be allocated to the SGA by setting some of the Oracle “initialization parameters”. These might include db_cache_size, shared_pool_size and log_buffer.
- i) 40% of RAM can be used for sizing SGA rest is reserved for OS and others in 64 bit machine and in 32 bit machine max SGA configured can be 1.5GB only.
- ii) Check the statspack report. Check hit ratio of Data buffer. If it is less than 90%, then we need to increase the Data buffer. Check hit ratio of Shared pool. If it is less than 95%, then we need to increase the Shared pool. Check log buffer. If redo buffer allocation retries/redo entries is greater than 1%, then we need to increase log_buffer.
5) What is the cache hit ratio, what impact does it have on performance of an Oracle database and what is involved in tuning it?
Ans:
Buffer cache hit ratio: It calculates how often a requested block has been found in the buffer cache without requiring disk access. This ratio is computed using data selected from the dynamic performance view V$SYSSTAT. The buffer cache hit ratio can be used to verify the physical I/O as predicted by V$DB_CACHE_ADVICE.
sql> select name, value From v$sysstat Where name in (‘db block gets’, ‘consistent gets’, ‘physical reads’);
The cache-hit ratio can be calculated as follows: Hit ratio = 1 – (physical reads / (db block gets + consistent gets)) If the cache-hit ratio goes below 90% then: increase the initialisation parameter DB_CACHE_SIZE.
Library cache hit ratio: It calculates how often the parsed representation of the statement can be reused. It also known as soft parse.
sql> select namespace, pins, pinhits, reloads, invalidations from v$librarycache order by namespace;
Library Cache Hit Ratio = sum(pinhits) / sum(pins)
Dictionary cache hit ratio:It is a measure of the proportion of requests for information from the data dictionary, the collection of database tables and views containing reference information about the database, its structures, and its users. On.
6) Other than making use of the statspack utility, what would you check when you are monitoring or running a health check on an Oracle 8i or 9i database?
Ans: Daily Monitoring activities and check different logs for any sort of errors.
7) How do you tell what your machine name is and what is its IP address?
Ans: hostname, uname -n and ifconfig
8) How would you go about verifying the network name that the local_listener is currently using?
Ans: lsnrctl stat or ps-eaf|grep tns
Inclined to build a profession as Oracle DBA Developer?
Then here is the blog post on Oracle DBA Training.
9) You have 4 instances running on the same UNIX box. How can you determine which shared memory and semaphores are associated with which instance?
Ans:
SQL> oradebug setmypid
SQL> oradebug ipc
SQL>oradebug tracfile_name
Also you can check the spfile. The parameters will start with instance_name. parameter_name naming.
10) What view(s) do you use to associate a user’s SQLPLUS session with his o/s process?
Ans: v$process and v$session
sql> select a.spid from v$process a, v$session b where a.addr = b.addr and b.audsid=userenv(‘sessionid’);
11) What is the recommended interval at which to run statspack snapshots, and why?
Ans: Should be in minutes (15-20 mins approx) because where the time between the two snapshots is measured in hours, the events that caused serious performance issues for 20 minutes during peak processing don’t look so bad when they’re spread out over an 8-hour window. It’s also true with STATSPACK that measuring things over too long of a period tends to level them off over time. Nothing will stand out and strike you as being wrong.
12) What spfile/init.ora file parameter exists to force the CBO to make the execution path of a given statement use an index, even if the index scan may appear to be calculated as more costly?
Ans: OPTIMIZER_INDEX_COST_ADJ= FORCE
13) Assuming today is Monday, how would you use the DBMS_JOB package to schedule the execution of a given procedure owned by SCOTT to start Wednesday at 9AM and to run subsequently every other day at 2AM.
Ans:?
Ans: 00 02 * * * /test/test.sh
15)In which dictionary table or view would you look to determine at which time a snapshot or MVIEW last successfully refreshed?
Ans : SQL> SELECT MVIEW_NAME,LAST_REFRESH_DATE from USER_MVIEWS;
16) How would you best determine why your MVIEW couldn’t FAST REFRESH?
Ans: Possibly by checking the MVIEW LOG for errors.
17) How would you begin to troubleshoot an ORA-3113 error?
Ans: End of File Communication Error. Check Alert Logfile. CheckNetwrok Latency. Check sqlnet.ora file has expire_time = 0, delete unwanted files and check the swap and temp spaces.
18) Which dictionary tables and/or views would you look at to diagnose a locking issue?
Ans: v$lock, v$session, v$process
19) An automatic job running via DBMS_JOB has failed. Knowing only that “it’s failed”, how do you approach troubleshooting this issue?
Ans:Check the log and possible reason for the JOB failed.
20) How would you extract DDL of a table without using a GUI tool?
Ans: select dbms_metadata.get_ddl('OBJECT','OBJECT_NAME') from dual;
21) You’re getting high “busy buffer waits” - how can you find what’s causing it?
Ans:;
22) What query tells you how much space a tablespace named “test” is taking up, and how much space is remaining?
Ans:
SET SERVEROUTPUT ON SET LINESIZE 1000 SET FEEDBACK OFF
SET LINESIZE 1000
SET FEEDBACK OFF
rem column dummy noprintcolumn pct_used format 999.9 heading "%|Used"
column name format a25 heading "Tablespace Name"
column Kbytes format 999,999,999 heading "MBytes"
column used format 999,999,999 heading "Used(MB)"
column free format 999,999,999 heading "Free(MB)"
column largest format 999,999,999 heading "Largest"
break on report
compute sum of kbytes on report
compute sum of free on report
compute sum of used on report
set pagesize 100
select nvl(b.tablespace_name,
nvl(a.tablespace_name,'UNKOWN')) name,(kbytes_alloc/1024) kbytes,
((kbytes_alloc-nvl(kbytes_free,0))/1024) used,(nvl(kbytes_free,0)/1024) free,
((kbytes_alloc-nvl(kbytes_free,0))/kbytes_alloc)*100 "%used",
nvl(largest,0)/1024 largest
from ( select sum(bytes)/1024 Kbytes_free,
max(bytes)/1024 largest, tablespace_name
from sys.dba_free_space group by tablespace_name ) a,
( select sum(bytes)/1024 Kbytes_alloc, tablespace_name
from sys.dba_data_files group by tablespace_name )b
where a.tablespace_name (+) = b.tablespace_name
order by 1
/
23) Database is hung. Old and new user connections alike hang on impact. What do you do? Your SYS SQLPLUS session is able to connect.
Ans: Log into the system and find whether there are any deadlocks in the system using the following query.
select 'SID ' || l1.sid ||' is blocking ' || l2.sid blocking from v$lock l1, v$lock l2 where l1.block =1 and l2.request > 0 and l1.id1=l2.id1 and l1.id2=l2.id2 /
from v$lock l1, v$lock l2
where l1.block =1 and l2.request > 0
and l1.id1=l2.id1
and l1.id2=l2.id2
/
If so kill the processes caught in deadlock
alter system kill session 'SID,SERIAL#' immediate;
Also find out which wait events exist in the system using following commands and go in detail as to what events are causing these waits and take appropriate actions.
select event,count(*) from v$session group by event
/
select u.sid,u.serial#, u.username,p.spid,to_char(u.logon_time,'DD-MON-YYYY:HH24:MI:SS') from v$session u, v$session w,v$process p where u.sid = w.sid and w.event like '%&a%' and u.paddr = p.addr
/
24) Database crashes. Corruption is found scattered among the file system neither of your doing nor of Oracle’s. What database recovery options are available? Database is in archive log mode.
Ans: First of all secure all the archives and all the backups you have on the tape or other system. Then run fschk to check the filesystem. If the corruption is detected at the filesystem level and is not recoverable by fschk format the file system and restore the database through RMAN.
25) How do you increase the OS limitation for open files (LINUX and/or Solaris)?
Ans: Set the file-max parameter is /etc/sysctl.conf to the number you want.Save the file and execute it by using command /etc/sysctl.conf-p
26) Provide an example of a shell script which logs into SQLPLUS as SYS, determines the current date, changes the date format to include minutes & seconds, issues a drop table command, displays the date again, and finally exits.
Ans:
export ORACLE_BASE=/oracle
export ORACLE_HOME=/oracle/ora10g
export ORACLE_SID=ora10g
export path=$ORACLE_HOME/lib
sqlplus sys as sysdba << EOF
@/oracle/date.sql
exit;
Now the contents of /oracle/date.sql
select SYSDATE from dual;
select to_char(SYSDATE,'dd-mon-yyyy hh24:mi:ss') from dual;
drop table tablename cascade constraints;
select to_char(SYSDATE,'dd-mon-yyyy hh24:mi:ss') from dual;
/
Interested in mastering Oracle DBA Certification ?
Learn more about Oracle DBA Tutorials in this blog post.
27) Explain how you would restore a database using RMAN to Point in Time?
Ans:
restore database
until time "to_date('Aug 27 2001 02:00:00','Mon DD YYYY HH24:MI:SS')";
recover database
28) How does Oracle guarantee data integrity of data changes?
Ans: Oracle exadata training Bangalore enables you to define and enforce data integrity constraints like PRIMARY KEY CONSTRAINTS, FOREIGN KEY CONSTRAINTS and UNIQUE CONSTRAINTS.
29) Which environment variables are absolutely critical in order to run the OUI?
Ans: ORACLE_BASE, ORACLE_HOME, ORACLE_SID,path and library path
30) What SQL query from v$session can you run to show how many sessions are logged in as a particular user account?
Ans: select count(1) from v$session where USERNAME='username';
31) TABLESPACE is not specified for a user?
a. TEMP
b. DATA
c. SYSTEM
d. ROLLBACK
Answer: c
32) User SCOTT creates an index with this statement: CREATE INDEX emp_indx on employee (empno). In which tablespace would be the index created?
a. SYSTEM tablespace
b. SCOTTS default tablespace
c. Tablespace with rollback segments
d. Same tablespace as the EMPLOYEE table.
Answer: b
33) Which data dictionary view shows the available free space in a certain tablespace?
A. DBA_EXTENTS
B. V$FREESPACE
C. DBA_FREE_SPACE
D. DBA_TABLESPACE
E. DBA_FREE_EXTENTS
Answer: c
34) Which method increase the size of a tablespace?
A. Add a datafile to a tablespace.
B. Use the ALTER TABLESPACE command to increase the MINEXTENTS for the tablespace.
C. Use the ALTER TABLESPACE command to increase the MAXEXTENTS for the tablespace.
D. Use the ALTER TABLESPACE command to increase the MINIMUM EXTENT for the tablespace.
Answer: a
35) What does the command ALTER DATABASE . . . RENAME DATAFILE do? (8-37) (Not proper description of the ans.)
A. It copies a data file.
B. It updates the control file.
C. It copies a data file and updates the control file.
D. It copies a data file, deletes the obsolete file, and updates the control file.
Answer: b
36) Can you drop objects from a read-only tablespace?
A. No
B. Yes
C. Only when using the DBA role
D. Only when the tablespace is online
Answer: b
37) SYSTEM TABLESPACE can be made off-line.
a) Yes
b) No
Answer: b
38) Datadictionary can span across multiple Tablespaces.
a) TRUE
b) FALSE
Answer: b
39) Multiple Tablespaces can share a single datafile.
a) TRUE
b) FALSE
Answer: b
40) All datafiles related to a Tablespace are removed when the Tablespace is dropped?
a) TRUE
b) FALSE
Answer: b
41) In which situation would you need to create a new control file for an existing database?
A. When all redo-log files are lost.
B. When MAXLOGMEMBERS needs to be changed.
C. When RECOVERY_PARALLELISM needs to be changed.
D. When the name of the parameter file needs to be changed
Answer: b
42) When configuring a database for ARCHIVELOG mode, you use an initialisation parameter to specify which action?
A. The size of archived log files.
B. How frequently log files will be archived.
C. That the database is in ARCHIVELOG mode.
d. To Store Archive log Files
Answer: d
43) Which command creates a text backup of the control file?
A. ALTER DATABASE BACKUP CONTROLFILE TO TRACE;
B. ALTER DATABASE BACKUP CONTROLFILE TO BACKUP;
C. ALTER DATABASE BACKUP CONTROLFILE TO filename;
D. ALTER DATABASE BACKUP CONTROLFILE TO TEXT filename;
Answer: a
44) You are configuring a database for ARCHIVELOG mode. Which initialization parameter should you use?
A. LOG_ARCHIVE_SIZE
B. ARCHIVELOG_MODE
C. LOG_ARCHIVE_DEST
Answer: c
45) How does a DBA specify multiple control files?
A. With the ADD CONTROLFILE command.
B. By using the files in the STARTUP command.
C. With the MULTIPLEX control file command.
D. By listing the files in the CONTROL_FILES parameter.
Answer: d
46) Which dynamic view should a DBA query to obtain information about the different sections of the control file?
A. V$CONTROLFILE
B. DBA_CONTROLFILE
C. V$CONTROLFILE_RECORD_SECTION
D. DBA_CONRTOLFILE_RECORD_SECTION
Answer: c
47) Which statements about online redo log members in a group are true?
A. All files in all groups are the same size.
B. All members in a group are the same size.
C. The rollback segment size determines the member size.
D. Differently size of transactions requires that the DBA should differently sized members.
Answer: b
What are the Common Oracle DBA.
For In-depth knowledge on Oracle DBA click on: | https://tekslate.com/oracle-dba-interview-questions-answers | CC-MAIN-2020-16 | refinedweb | 2,461 | 65.93 |
wcwidth − determine columns needed for a wide character
#define
_XOPEN_SOURCE /* See feature_test_macros(7) */
#include <wchar.h>
int wcwidth(wchar_t c);
The wcwidth() function returns the number of columns needed to represent the wide character c. If c is a printable wide character, the value is at least 0. If c is null wide character (L'\0'), the value is 0. Otherwise −1 is returned.
The wcwidth() function returns the number of column positions for c.
For an explanation of the terms used in this section, see attributes(7).
POSIX.1-2001.
Note that glibc
before 2.2.5 used the prototype
int wcwidth(wint_t c);
The behavior of wcwidth() depends on the LC_CTYPE category of the current locale.
iswprint(3), wcswidth(3)
This page is part of release 3.53 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at−pages/. | http://man.linuxtool.net/centos7/u2/man/3_wcwidth.html | CC-MAIN-2019-09 | refinedweb | 151 | 68.47 |
Hello, im having trouble with getting this program I am writing for one of my courses to run. The program has a 4 different classes. I am having trouble getting the program to read input from a file, having it take those items and creating vehicle objects, and then putting those vehicle objects into an array. The code I am providing below is only part of the program but should be enough to help me with the problem im having so far.
the file it is reading from(fleetCars.txt) contains this information. There is a tab between each item for each car.
Hyundai Sonata 2010 ABC236347NM2N2NW2 18455.34 8765 7567
Chevy Blazer 1998 1234H32343LMN3423 29556.65 38559 38559
Code :
public class Fleet { Vehicle[] fleetVehicles = new Vehicle[4]; public Fleet() { super(); } public Fleet(String fileName) throws IOException { Scanner inputFile = new Scanner(fileName); for (int i = 0; i < fleetVehicles.length; i++) { Vehicle vehobj = new Vehicle(); vehobj.readRecord(inputFile); fleetVehicles[i] = vehobj; } } public String toString() { Vehicle obj = new Vehicle(); for (int i = 0; i < fleetVehicles.length; i++) { fleetVehicles[i] = obj; return obj.toString(); } return obj.toString(); }
Code :
public class Vehicle { private String vin; private String make; private String model; private int year; private double value; private int milesDriven; private int lastOilChange; public Vehicle() { super(); } public Vehicle(String vin, String make, String model, int year, double value, int milesDriven, int lastOilChange) { this(vin, make, model, year, value); this.milesDriven = milesDriven; this.lastOilChange = lastOilChange; } public String toString() { return "Make:\t\t" + this.make + "\nModel:\t\t" + this.model + "\nYear:\t\t" + this.year + "\nValue:\t\t" + this.value + "\nVIN:\t\t" + this.getVIN() + "\nMiles Driven: " + this.milesDriven + "\nNext oil change at " + this.getMilesToNextOilChange() + " miles"; } public void readRecord(Scanner inputFile) throws IOException { make = inputFile.next(); model = inputFile.next(); year = inputFile.nextInt(); vin = inputFile.next(); value = inputFile.nextInt(); milesDriven = inputFile.nextInt(); lastOilChange = inputFile.nextInt(); }
The last bit of code is the part that runs the whole program. This part asks the user for the name of the file. It then is supposed to open the file and use it to build the fleet object.
Code :
public class FleetInterfaceApp { private Fleet fleet; private Menu menu; private void createMenu() { String[] choices = { "Add a vehicle", "Delete a vehicle", "Update miles driven", "Record oil change", "Print listing of all fleet vehicles", "Print listing of all vehicles to be replaced", "Print listing of all vehicles that need and oil change", "Quit" }; menu = new Menu(choices); } public void run() throws IOException { Scanner keyboard = new Scanner(System.in); System.out .println("What is the name of the file containing the fleet vehicle information?"); String fileName = keyboard.nextLine(); File file = new File(fileName); Scanner inputFile = new Scanner(file); Fleet fleet = new Fleet(fileName); int choice; this.createMenu(); choice = this.menu.getChoice(); System.out.println("You entered choice " + choice); if (choice == 1) choice1(); if (choice == 2) choice2(); if (choice == 3) choice3(); if (choice == 4) choice4(); if (choice == 5) choice5(); if (choice == 6) choice6(); if (choice == 7) choice7(); }
This is the error I get when I run fleetInterFaceApp
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at Vehicle.readRecord(Vehicle.java:285)
at Fleet.<init>(Fleet.java:51)
at FleetInterfaceApp.run(FleetInterfaceApp.java:47)
at FleetInterfaceApp.main(FleetInterfaceApp.java:166)
Thanks in advance for any help! | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/12907-running-into-problem-my-program-printingthethread.html | CC-MAIN-2016-36 | refinedweb | 555 | 52.76 |
Thank you @andfanilo
@andfanilo, I came across this discussion while looking for PDF file upload and analysis. I am working on PDF files using ‘pdfminer.six’ . I could not find anything in documentation to load file(st.file_uploader object) like you mentioned for pdfplumber.
Any suggestions on handling pdf files using pdfminer.six library in streamlit app will be very helpful. Thanks:)
Don’t have a lot of experience with pdfminer.six but at least the following seems to work with Streamlit’s file uploader:
import pdfminer from pdfminer.high_level import extract_pages import streamlit as st st.write(pdfminer.__version__) uploaded_file = st.file_uploader("Choose a file", "pdf") if uploaded_file is not None: for page_layout in extract_pages(uploaded_file): for element in page_layout: st.write(element)
Hope this can serve as a good starting point.
Fanilo
How can I extract images from a pdf of images
Hi @andfanilo , I am working on a use-case of extracting tabular data from pdf files. For this, I am using camelot as a table extraction library. How to parse the pdf uploaded through st.file_uploader() and pass it to camelot. As per my understanding from camelot documentation, camelot.read_pdf() only accepts file path as input.
Hello @santosh_boina
If it absolutely requires a filepath and not a File-related object, you could try to write the uploaded file in a temporary folder and provide
camelot with the URl to said file, then destroy the temporary file at the end of the job. You can copy the following bit of code:
Hope this gets you started!
Fanilo
Hello @santosh_boina, you might have better luck with this bit of code instead, which fixes a bug in the former:
How to render a pdf file in streamlit?
def show_pdf(file_path):
with open(file_path,“rb”) as f:
base64_pdf = base64.b64encode(f.read()).decode(‘utf-8’)
pdf_display = F’’
st.markdown(pdf_display, unsafe_allow_html=True)
print(‘Done’)
show_pdf('C:/Users/Tarun/Downloads/SOFTWARE ENGINEERING NOTES.pdf')
I tried this, but neither pdf displays nor any errror msg. Pls help… | https://discuss.streamlit.io/t/how-to-upload-a-pdf-file-in-streamlit/2428/2 | CC-MAIN-2022-27 | refinedweb | 336 | 59.4 |
XMonad.Layout.IfMax
Description
Provides IfMax layout, which will run one layout if there are maximum N windows on workspace, and another layout, when number of windows is greater than N.
Synopsis
- data IfMax l1 l2 w = IfMax Int (l1 w) (l2 w)
- ifMax :: (LayoutClass l1 w, LayoutClass l2 w) => Int -> l1 w -> l2 w -> IfMax l1 l2 w
Usage
IfMax layout will run one layout if number of windows on workspace is as maximum N, and else will run another layout.
You can use this module by adding folowing in your
xmonad.hs:
import XMonad.Layout.IfMax
Then add layouts to your layoutHook:
myLayoutHook = IfMax 2 Full (Tall ...) ||| ...
In this example, if there are 1 or 2 windows, Full layout will be used; otherwise, Tall layout will be used. | https://hackage.haskell.org/package/xmonad-contrib-0.15/docs/XMonad-Layout-IfMax.html | CC-MAIN-2019-13 | refinedweb | 130 | 58.82 |
this is the program that i need to do
You are required to write a command line program in Java that declares three numbers.
Write a method called calc() that takes in the three numbers as parameters. Inside this
method, you must add the first two numbers together and divide the answer by the
third. The value of the sum must be returned. Write another method called display()
that prints the following to the screen:
******************************************
* *
* This is a simple program *
* that performs a mathematical *
* calculation. The answer is: *
* [answer] *
******************************************
so far i made this.
import java.util.Scanner;
public class assignmentB
{
public int calc(){
int number1;
int number2;
int number3;
int sum;
Scanner scan=new Scanner(System.in);
System.out.println("Please enter 1st number: ");
number1 = scan.nextInt();
System.out.println("Please enter 2nd number: ");
number2 = scan.nextInt();
System.out.println("Divide the sum of the two numbers by: ");
number3 = scan.nextInt();
sum = (number1 + number2)/ number3;
return sum;
}
public String display(){
System.out.println("****************************** ***");
System.out.println("* *");
System.out.println("* This is a simple program *");
System.out.println("* that performs a mathematical *");
System.out.println("* calculation. The answer is: *");
System.out.println("* "+ sum +" *");
System.out.println("* *");
System.out.println("****************************** ***");
}
}
can anyone fix this for me? so it will work as state above. | http://www.javaprogrammingforums.com/whats-wrong-my-code/15895-can-you-guys-help-me-fix-my-assignment.html | CC-MAIN-2018-26 | refinedweb | 212 | 52.36 |
The App Engine standard environment is based on container instances running on Google's infrastructure. Containers are preconfigured with one of several available runtimes (Java 7, Java 8, Python 2.7, Go, PHP and Node.js)..
The standard environment development kit
Software Development Kits (SDKs) for App Engine are available in some Google Cloud Platform Console manages your application in production. The GCP Console uses a web-based interface to create new applications, configure domain names, change which version of your application is live, examine access and error logs, and much more.
Instance classes
Each application running in the standard environment has an instance class, which determines its compute resources and pricing. This table summarizes the memory and CPU limits of the various instance classes. See the pricing page for billing information.
Quotas and limits.
Features
A feature may be available in every runtime language, or only in a subset of languages. The functionality of a feature is usually the same in all the runtimes where it's available, but there can be exceptions.
Every App Engine feature is classified according to its status and availability:
- General Availability (GA) features are publicly available and are covered by App Engine's SLA and deprecation policy. The implementation of a GA feature is stable; any changes made to it will be backwards-compatible. Unless otherwise noted, the App Engine features described on this page are all in GA.
- Beta features are publicly available. They might or might not become GA features in a future App Engine release, and their implementation can change in backward-incompatible ways.
- Alpha features may or may not become Beta or GA features in a future App Engine release, and their implementation may change in backward- incompatible ways. Some Alpha features are publicly available, while others require that you request access in order to use them.
Some features described here are provided by third-party vendors, others are open source projects. These will be marked third-party or Open Source.
The feature descriptions on this page are grouped according to the general functions they serve:
Index of features
Third-party integrations
Standard environment languages and runtimes
Java 7 runtime
App Engine runs your Java web application using a Java 7 JVM in a safe sandboxed environment. App Engine invokes your app's servlet classes to handle requests and prepare responses in this environment..
Java 8 runtime
- The App Engine Java 8 runtime supports all of the existing features available in the current Java 7 runtime, but with the following upgrades and enhancements:
- Doesn't impose a security manager, as the Java 7 runtime does, which means your code won't be restricted by Java permissions issues.
- Supports the standard public Java library, not just the whitelisted class subset available for Java 7.
- Supports Eclipse Jetty 9
- Supports Servlet 3.1
Supports gRPC based Cloud APIs, such as the Cloud Bigtable client library and the Google Cloud Java library.
Python runtime
App Engine standard environment executes your Python application Python interpreter can run any Python code, including Python services you include with your application, as well as the Python standard library. The interpreter cannot load Python services with C code; it is a "pure" Python environment.
The secured sandbox environment isolates your application for service and security. It ensures that apps can only perform actions that do not interfere with the performance and scalability of other apps. For instance, an app cannot write data to the local file system or make arbitrary network connections. Instead, apps use scalable services provided by App Engine to store data and communicate over the Internet. The Python interpreter raises an exception when an app attempts to import a service from the standard library known to not work within the sandbox restrictions.
PHP runtime
The PHP runtime executes your application code in a sandboxed PHP 5.5 environment. Your app receives web requests, performs work, and sends responses by interacting with this environment. The runtime supports many of the standard PHP extensions. You cannot upload extensions written in C.
App Engine Standard environment runs its own web server, which can be configured using an app.yaml file that's uploaded with your code. This file specifies how incoming HTTP requests to your application are directed to PHP scripts.
The sandbox isolates your application for reliability, scalability and security. For this reason, a small number of PHP functions are not available on App Engine, and others will raise an exception if used incorrectly. For instance, an app cannot write data to the local file system. Instead, apps can use scalable services provided by Google to store and process data and communicate over the Internet.
The PHP runtime provides a built-in Google Cloud Storage stream wrapper that allows you to use many of the standard PHP filesystem functions to access Google Cloud Storage.
Go runtime
App Engine standard environment runs Go version 1.9. The SDK provides an interface similar to the standard Go HTTP package; writing Go apps for App Engine is similar to writing stand-alone Go web servers.
The SDK includes the Go compiler and standard library; it has no additional dependencies. Because the Go runtime executes in a sandboxed environment, some of the standard library functions will return errors and should not be used. For example, an os.ErrPermission will occur if an app tries to write to the local file system or make arbitrary network connections. You must use App Engine's scalable services to store data and communicate over the Internet.
You never need to invoke the Go compiler yourself. Your app is automatically re-built on the server side whenever you upload new code, and if you are running the local development server the SDK automatically recompiles sources on-the-fly when you change them.
The Go runtime environment for App Engine supports goroutines, but they are scheduled on a single thread. Goroutines can run concurrently but not in parallel. An application instance can handle multiple requests. For example, if one request is waiting for a datastore API call, the instance can process another request in the meantime.
Data storage, retrieval, and search
Datastore Datastore holds data objects known as entities. An entity has one or more properties, named values of one of several supported data types: string, can be accessing or manipulating the same data at the same time.
Available in Python | Java | Go
Datastore Backup/Restore Beta
You can use the Datastore Admin tab of the GCP Console to backup selected kinds of entities, or to restore entities from a backup. You can backup using either Blobstore or Google Cloud Storage.
Available in Python | Java | Go.
Google Cloud SQL provides these features:
- Ability to host your MySQL databases in the cloud.
- All data replicated in multiple locations for great availability and durability.
- Choice of billing options:
- Per use option means you only pay for the time you access your data
- Package option allows you to control your costs for more frequent access
- Google Cloud SQL instances can have up to 16GB of RAM and 500GB data storage
- Create and manage instances in the Google Cloud Platform Console
- Data stored in datacenters in the EU or the US
- Cloud SQL customer data is encrypted when on Google’s internal networks and when stored in database tables and temporary files.
- Synchronous or asynchronous geographic replication
- Import or export databases using mysqldump
- Java and Python compatibility
- Support for MySQL wire protocol and MySQL connectors
- Support for connecting with the Secure Sockets Layer (SSL) protocol
Available in Python | Java | PHP | Go
Blobstore.
Available in Python | Java | Go
Google Cloud Storage Client Library
Google Cloud Storage is useful for storing and serving large files. Additionally, Cloud Storage offers the use of access control lists (ACLs), and the ability to resume upload operations if they're interrupted, and many other features. The Google Cloud Storage client library makes use of this resume capability automatically for your app, providing you with a robust way to stream data into Google Cloud Storage.
The Google Cloud Storage client library lets your application read files from and write files to buckets in Google Cloud Storage. This library supports reading and writing large amounts of data to Google Cloud Storage, with internal error handling and retries, so you don't have to write your own code to do this. Moreover, it provides read buffering with prefetch so your app can be more efficient.
Available in Python | Java | PHP | Go
Search
The Search API provides a model for indexing documents that contain structured data, including text and HTML strings, atoms, dates, geopoints, numbers. Documents and indexes are saved in a separate persistent store optimized for search operations. You can search an index, and organize and present search results. The API supports partial text matching on string fields. The Search API can index any number of documents, however, a single search can return no more than 10,000 matching documents. The App Engine Datastore can be more appropriate for applications that need to retrieve very large result sets.
Available in Python | Java | Go
Memcache
App Engine standard environment supports two classes of the memcache service:
- Shared memcache is the free default for App Engine applications. It provides cache capacity on a best-effort basis and is subject to the overall demand of all applications served by App Engine.
- Dedicated memcache provides a fixed cache capacity assigned exclusively to your application. It's billed by the GB-hour of cache size. Having control over cache size means your app can perform more predictably and with fewer accesses to more costly durable storage.
Whether shared or dedicated, memcache is not a durable storage. Keys can be evicted when the cache fills up, according to the cache's LRU policy. Changes in the cache configuration or datacenter maintenance events may also flush some or all of the cache.
Available in Python | Java | PHP | Go
Dedicated Memcache
Dedicated memcache provides a fixed cache capacity assigned exclusively to your application. It's billed by the GB-hour of cache size. Having control over cache size means your app can perform more predictably and with fewer accesses to more costly durable storage.
Available in Python | Java | PHP | Go
- Logs
App Engine standard environment maintains two kinds of logs:
- Application logs contain arbitrary messages with a timestamp and log level.
- Request logs contain entries for each request handled by your app, with information such as the app ID, HTTP version, and so forth. Each request log includes a list of application logs associated with that request.
The Logs API provides access to your application's logs. You can also access the logs from the GCP Console.
Available in Python | Java | PHP | Go
Communications
Google Cloud Endpoints
Google Cloud Endpoints consists of tools, libraries and capabilities that allow you to generate APIs and client libraries from an App Engine standard environment application, referred to as an API standard environment app, the mobile developer can use all of the services and features available in App Engine standard environment, such as Datastore, Google Cloud Storage, Mail, Url Fetch, Task Queues, and so forth. And finally, by using App Engine standard environment for the backend, developers are freed from system admin work, load balancing, scaling, and server maintenance.
It is possible to create mobile clients for App Engine Standard environment backends without Endpoints. However, using Endpoints makes this process easier because it frees you from having to write wrappers to handle communication with App Engine. The client libraries generated by Endpoints allow you to simply make direct API calls.
Available in Python | Java
App Engine standard environment.
Available in Python | Java | PHP | Go
SendGrid Third-party
You can use SendGrid to power your emails on Google App Engine standard environment. Using SendGrid can improve your deliverability and provide transparency into what actually happens to those emails your app sends. You can see statistics on opens, clicks, unsubscribes, spam reports and more through either the SendGrid interface or its API.
Available in Python | Java | PHP
Sockets Beta
App Engine standard environment supports regular outbound sockets in all runtimes, without requiring you to import any special App Engine libraries or add any special App Engine code. However, there are certain limitations and behaviors you need to be aware of when using sockets. The details vary depending on the runtime. Read the runtime documentation for more information.
Available in Python | Java | PHP | Go
Twilio Third-party
Twilio Voice enables your application to make and receive phone calls. Twilio SMS enables your application to send and receive text messages. Twilio Client allows you to make VoIP calls from any phone, tablet, or browser and supports WebRTC.
Available in Python | Java | PHP
URL Fetch
App Engine standard environment applications can communicate with other applications or access other resources on the web by fetching URLs. An app can use the URL Fetch service to issue HTTP and HTTPS requests and receive responses. The URL Fetch service uses Google's network infrastructure for efficiency and scaling purposes.
Available in Python | Java | PHP | Go
Process management
Task Queue standard environment provides two different queue configurations:
- Push queues process tasks based on the processing rate configured in the queue definition. App Engine standard environment. When using pull queues, your application needs to handle scaling of instances based on processing volume, and also needs to delete tasks after processing.
Available in Python | Java | PHP | Go
Task Queue Tagging Beta
The tagging API lets pull queue consumers lease a specified number of tasks with the same tag from a pull queue.
Available in Python | Java | Go
Scheduled Tasks
The App Engine standard environmentrequest, at a given time of day. An HTTP request invoked by cron can run for up to 10 minutes, but is subject to the same limits as other HTTP requests.
Free applications can have up to 20 scheduled tasks. Paid applications can have up to 100 scheduled tasks.
Available in Python | Java | PHP | Go
Computation
Images
The Images API provides the ability to describe and manipulate image data. The API provides information about an image, such as its format, width, height, and a histogram of color values. It can resize, rotate, flip, and crop images. It also has the ability to composite multiple images into one image, enhance images automatically, and convert images between several formats
The Images service can accept image data directly from the app, or it can use data retrieved from Blobstore or Google Cloud Storage.
Available in Python | Java | Go
MapReduce Open Source
App Engine MapReduce is an open source library that is built on top of App Engine services, including Datastore and Task Queues. You must include the library with your application, it provides:
- A programming model for large-scale distributed data processing
- Automatic parallelization and distribution within your existing codebase
- Access to Google-scale data storage
- I/O scheduling
- Fault-tolerance, handling of exceptions
- User tunable settings to optimize for speed/cost
- Tools for monitoring status
Available on GitHub for Java and Python
App configuration and management
App Identity
The Application Identity service provides the ability for an application to identify itself, by retrieving its App ID or the hostname part of its URL. The app's identity can be used to generate a URL or email address, or to make some run-time decision.
Many Google APIs support OAuth 2.0 assertions to identify the source of a request. The App Identity API can create tokens that can be used to assert that the source of a request is the application itself. This token can be included in the HTTP headers of a call to identify the calling application. The OAuth token only works against Google systems. However you can use the underlying signing technology in the API to assert the identity of your application to other systems.
Available in Python | Java | PHP | Go
OAuth Alpha
The App Engine standard environment OAuth API uses the OAuth protocol and provides a way for your app to authenticate a user who is requesting access without asking for user credentials (username and password).
Available in Python | Java | Go
Capabilities
You can use the Capabilities API to detect the availability of services (like the Images service) or specific capabilities of a service (such as datastore reads and writes). You can reduce downtime in your application by testing for the availability of a capability before trying to use it. The services that support this API vary depending which runtime you are using.
Available in Python | Java | Go
Services
Services are used to factor large applications into logical components that can share stateful services and communicate in a secure fashion. An app that handles customer requests might include separate services to handle other tasks:
- API requests from mobile devices
- Internal, admin-like requests
- Backend processing such as billing pipelines and data analysis
Services can have different versions, performance levels, and authorization. While running, a particular service will have one or more instances, which may be managed statically or dynamically. Incoming requests are routed to an existing or new instance of the appropriate service.
Scaling types control the creation of instances. There are three scaling types. Each type offers a variety of instance classes, with different amounts of CPU and Memory:
- A service with manual scaling runs continuously, allowing you to perform complex initialization and rely on the state of its memory over time.
- A service with basic scaling will create an instance when the application receives a request. The instance will be turned down when the app becomes idle. Basic scaling is ideal for work that is intermittent or driven by user activity.
- Automatic scaling is the scaling policy that App Engine has used since its inception. It is based on request rate, response latencies, and other application metrics. Previously users could use the GCP Console to configure the automatic scaling parameters (instance class, idle instances and pending latency) for an application's frontend versions only. These settings now apply to every version of every service that has automatic scaling.
Available in Python | Java | PHP | Go
Multitenancy
Multitenancy is a software architecture in which one instance of an application, running on a remote server, serves many client organizations, or tenants.
Google App Engine standard environment provides the Namespaces API, which includes a namespace manager. The Namespaces API is also incorporated in other namespace-enabled APIs. When you set the namespace in the namespace manager, all the namespace-enabled APIs use that namespace by default. This lets you partition data across tenants by specifying a unique namespace for each tenant. For instance, using namespaces with the Datastore API, all users can share the same data schema, but different users see different content.
The Namespaces API is integrated with G Suite, allowing you to use your G Suite domain as the current namespace. Because G Suite lets you deploy your app to any domain that you own, you can easily set unique namespaces for all domains linked to your G Suite account.
Available in Python | Java | Go
Remote
Lets external applications transparently access App Engine standard environment services. For example, you can use Remote API to access a production datastore from an app running on your local machine.
Available in Python | Java | Go
SSL for custom domains
Allows applications to be served via both HTTPS and HTTP via a custom domain instead of an
appspot.comaddress.
Available in Python | Java | PHP | Go
Traffic splitting
Allows you to roll out features for your app slowly over a period of time and do A/B testing. Traffic Splitting works by splitting incoming requests to different versions of your app.
Available in Python | Java | PHP | Go
Users
App Engine standard environment applications can authenticate users using Google Accounts or accounts on your own G Suite domains. An application can detect whether the current user has signed in, and can redirect the user to the appropriate sign-in page to sign in or, if your app uses Google Accounts authentication, create a new account. While a user is signed in to the application, the app can access the user's email address. The app can also detect whether the current user is an administrator, making it easy to implement admin-only areas of the app.
Available in Python | Java | PHP | Go | https://cloud.google.com/appengine/docs/standard/?hl=ja | CC-MAIN-2018-34 | refinedweb | 3,378 | 51.78 |
Problem : 6 October 16, 2009October 16, 2009 / Shahab #include <stdio.h> #if something == 0 int some = 0; #endif int main () { int thing = 0; printf("%d %d\n", some, thing); return 0; } // What's the output ? [Do not execute / run] // Source : Share this:ShareFacebookTwitterPrintEmailLike this:Like Loading... Related
5 thoughts on “Problem : 6”
0 0
The C preprocessor modifies a source code file before handing it over to the compiler..
~
0 0
can u please explain this line of code
#if something == 0
@anubhav jain
I have explained the theory already .. here is an example
this code will not compile
because, if “something” not equals to zero then variable [int some] won’t get declared! (and assigned)
simply saying, “something” is a global variable and assigned to zero by default
and we are checking if something == 0 then declare int same = 0; | https://tausiq.wordpress.com/2009/10/16/problem-6/ | CC-MAIN-2017-04 | refinedweb | 141 | 69.01 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.