An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.
Experience has shown that writing assertions while programming is one of the quickest and most effective ways to detect and correct bugs. As an added benefit, assertions serve to document the inner workings of your program, enhancing maintainability.
This document shows you how to program with assertions. It covers the topics:
The assertion statement has two forms. The first, simpler form is:
assert Expression1 ;
where Expression1
is a boolean
expression. When the system runs the
assertion, it evaluates Expression1 and if it is false
throws an AssertionError
with no detail message.
The second form of the assertion statement is:
assert Expression1 : Expression2 ;
where:
void
.)Use this version of the assert
statement to provide
a detail message for the AssertionError
. The system
passes the value of Expression2 to the appropriate
AssertionError
constructor, which uses the string
representation of the value as the error's detail message.
The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should allow you to diagnose and ultimately fix the error that led the assertion to fail. Note that the detail message is not a user-level error message, so it is generally unnecessary to make these messages understandable in isolation, or to internationalize them. The detail message is meant to be interpreted in the context of a full stack trace, in conjunction with the source code containing the failed assertion.
Like all uncaught exceptions, assertion failures are generally
labeled in the stack trace with the file and line number from which
they were thrown. The second form of the assertion statement should
be used in preference to the first only when the program has some
additional information that might help diagnose the failure. For
example, if Expression1 involves the
relationship between two variables x
and
y
, the second form should be used. Under these
circumstances, a reasonable candidate for
Expression2 would be "x: " + x + ", y:
" + y
.
In some cases Expression1 may be expensive to evaluate. For example, suppose you write a method to find the minimum element in an unsorted list, and you add an assertion to verify that the selected element is indeed the minimum. The work done by the assert will be at least as expensive as the work done by the method itself. To ensure that assertions are not a performance liability in deployed applications, assertions can be enabled or disabled when the program is started, and are disabled by default. Disabling assertions eliminates their performance penalty entirely. Once disabled, they are essentially equivalent to empty statements in semantics and performance. See Enabling and Disabling Assertions for more information.
The addition of the assert
keyword to the Java
programming language has implications for existing code. See
Compatibility With Existing Programs
for more information.
There are many situations where it is good to use assertions, including:
There are also situations where you should not use them:
Argument checking is typically part of the published
specifications (or contract) of a method, and these
specifications must be obeyed whether assertions are enabled or
disabled. Another problem with using assertions for argument
checking is that erroneous arguments should result in an
appropriate runtime exception (such as
IllegalArgumentException
,
IndexOutOfBoundsException
, or
NullPointerException
). An assertion failure will not
throw an appropriate exception.
Because assertions may be disabled, programs must not assume
that the boolean expression contained in an assertion will be
evaluated. Violating this rule has dire consequences. For example,
suppose you wanted to remove all of the null elements from a list
names
, and knew that the list contained one or more
nulls. It would be wrong to do this:
// Broken! - action is contained in assertion assert names.remove(null);
The program would work fine when asserts were enabled, but would fail when they were disabled, as it would no longer remove the null elements from the list. The correct idiom is to perform the action before the assertion and then assert that the action succeeded:
// Fixed - action precedes assertion boolean nullsRemoved = names.remove(null); assert nullsRemoved; // Runs whether or not asserts are enabled
As a rule, the expressions contained in assertions should be free of side effects: evaluating the expression should not affect any state that is visible after the evaluation is complete. One exception to this rule is that assertions can modify state that is used only from within other assertions. An idiom that makes use of this exception is presented later in this document.
Before assertions were available, many programmers used comments
to indicate their assumptions concerning a program's behavior. For
example, you might have written something like this to explain your
assumption about an else
clause in a multiway
if-statement:
if (i % 3 == 0) { ... } else if (i % 3 == 1) { ... } else { // We know (i % 3 == 2) ... }
You should now use an assertion whenever you would have written a comment that asserts an invariant. For example, you should rewrite the previous if-statement like this:
if (i % 3 == 0) { ... } else if (i % 3 == 1) { ... } else { assert i % 3 == 2 : i; ... }
Note, incidentally, that the assertion in the above example may
fail if i
is negative, as the %
operator
is not a true modulus operator, but computes the
remainder, which may be negative.
Another good candidate for an assertion is a switch
statement with no default
case. The absence of a
default
case typically indicates that a programmer
believes that one of the cases will always be executed. The
assumption that a particular variable will have one of a small
number of values is an invariant that should be checked with an
assertion. For example, suppose the following switch
statement appears in a program that handles playing cards:
switch(suit) { case Suit.CLUBS: ... break; case Suit.DIAMONDS: ... break; case Suit.HEARTS: ... break; case Suit.SPADES: ... }
It probably indicates an assumption that the suit
variable will have one of only four values. To test this
assumption, you should add the following default case:
default: assert false : suit;
If the suit
variable takes on another value and
assertions are enabled, the assert will fail and an
AssertionError
will be thrown.
An acceptable alternative is:
default: throw new AssertionError(suit);
This alternative offers protection even if assertions are
disabled, but the extra protection adds no cost: the
throw
statement won't execute unless the program has
failed. Moreover, the alternative is legal under some circumstances
where the assert
statement is not. If the enclosing
method returns a value, each case in the switch
statement contains a return
statement, and no
return
statement follows the switch
statement, then it would cause a syntax error to add a default case
with an assertion. (The method would return without a value if no
case matched and assertions were disabled.)
The previous example not only tests an invariant, it also checks
an assumption about the application's flow of control. The author
of the original switch
statement probably assumed not
only that the suit
variable would always have one of
four values, but also that one of the four cases would always be
executed. It points out another general area where you should use
assertions: place an assertion at any location you assume will
not be reached. The assertions statement to use is:
assert false;
For example, suppose you have a method that looks like this:
void foo() { for (...) { if (...) return; } // Execution should never reach this point!!! }
Replace the final comment so that the code now reads:
void foo() { for (...) { if (...) return; } assert false; // Execution should never reach this point! }
Note: Use this technique with discretion. If a statement
is unreachable as defined in the Java Language Specification, you
will get a compile time error if you try to assert that it is not
reached. Again, an acceptable alternative is simply to throw an
AssertionError
.
While the assert construct is not a full-blown design-by-contract facility, it can help support an informal design-by-contract style of programming. This section shows you how to use asserts for:
By convention, preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. For example:
/** * Sets the refresh rate. * * @param rate refresh rate, in frames per second. * @throws IllegalArgumentException if rate <= 0 or * rate > MAX_REFRESH_RATE. */ public void setRefreshRate(int rate) { // Enforce specified precondition in public method if (rate <= 0 || rate > MAX_REFRESH_RATE) throw new IllegalArgumentException("Illegal rate: " + rate); setRefreshInterval(1000/rate); }
This convention is unaffected by the addition of the
assert
construct. Do not use assertions to check
the parameters of a public method. An assert is inappropriate
because the method guarantees that it will always enforce the
argument checks. It must check its arguments whether or not
assertions are enabled. Further, the assert
construct
does not throw an exception of the specified type. It can throw
only an AssertionError
.
You can, however, use an assertion to test a nonpublic method's precondition that you believe will be true no matter what a client does with the class. For example, an assertion is appropriate in the following "helper method" that is invoked by the previous method:
/** * Sets the refresh interval (which must correspond to a legal frame rate). * * @param interval refresh interval in milliseconds. */ private void setRefreshInterval(int interval) { // Confirm adherence to precondition in nonpublic method assert interval > 0 && interval <= 1000/MAX_REFRESH_RATE : interval; ... // Set the refresh interval }
Note, the above assertion will fail if
MAX_REFRESH_RATE
is greater than 1000 and the client
selects a refresh rate greater than 1000. This would, in fact,
indicate a bug in the library!
Classes designed for multithreaded use often have non-public methods with preconditions relating to whether or not some lock is held. For example, it is not uncommon to see something like this:
private Object[] a; public synchronized int find(Object key) { return find(key, a, 0, a.length); } // Recursive helper method - always called with a lock on this object private int find(Object key, Object[] arr, int start, int len) { ... }
A static method called holdsLock
has been added to
the Thread
class to test whether the current thread
holds the lock on a specified object. This method can be used in
combination with an assert
statement to supplement a
comment describing a lock-status precondition, as shown in the
following example:
// Recursive helper method - always called with a lock on this. private int find(Object key, Object[] arr, int start, int len) { assert Thread.holdsLock(this); // lock-status assertion ... }
Note that it is also possible to write a lock-status assertion asserting that a given lock isn't held.
You can test postcondition with assertions in both public and
nonpublic methods. For example, the following public method uses an
assert
statement to check a post condition:
/** * Returns a BigInteger whose value is (this-1 mod m). * * @param m the modulus. * @return this-1 mod m. * @throws ArithmeticException m <= 0, or this BigInteger *has no multiplicative inverse mod m (that is, this BigInteger *is not relatively prime to m). */ public BigInteger modInverse(BigInteger m) { if (m.signum <= 0) throw new ArithmeticException("Modulus not positive: " + m); ... // Do the computation assert this.multiply(result).mod(m).equals(ONE) : this; return result; }
Occasionally it is necessary to save some data prior to performing
a computation in order to check a postcondition. You can do this
with two assert
statements and a simple inner class
that saves the state of one or more variables so they can be
checked (or rechecked) after the computation. For example, suppose
you have a piece of code that looks like this:
void foo(int[] array) { // Manipulate array ... // At this point, array will contain exactly the ints that it did // prior to manipulation, in the same order. }
Here is how you could modify the above method to turn the textual assertion of a postcondition into a functional one:
void foo(final int[] array) { // Inner class that saves state and performs final consistency check class DataCopy { private int[] arrayCopy; DataCopy() { arrayCopy = (int[]) array.clone(); } boolean isConsistent() { return Arrays.equals(array, arrayCopy); } } DataCopy copy = null; // Always succeeds; has side effect of saving a copy of array assert ((copy = new DataCopy()) != null); ... // Manipulate array // Ensure array has same ints in same order as before manipulation. assert copy.isConsistent(); }
You can easily generalize this idiom to save more than one data field, and to test arbitrarily complex assertions concerning pre-computation and post-computation values.
You might be tempted to replace the first assert statement (which is executed solely for its side-effect) by the following, more expressive statement:
copy = new DataCopy();
Don't make this replacement. The statement above would copy the array whether or not asserts were enabled, violating the principle that assertions should have no cost when disabled.
A class invariant is a type of internal invariant that applies to every instance of a class at all times, except when an instance is in transition from one consistent state to another. A class invariant can specify the relationships among multiple attributes, and should be true before and after any method completes. For example, suppose you implement a balanced tree data structure of some sort. A class invariant might be that the tree is balanced and properly ordered.
The assertion mechanism does not enforce any particular style for checking invariants. It is sometimes convenient, though, to combine the expressions that check required constraints into a single internal method that can be called by assertions. Continuing the balanced tree example, it might be appropriate to implement a private method that checked that the tree was indeed balanced as per the dictates of the data structure:
// Returns true if this tree is properly balanced private boolean balanced() { ... }
Because this method checks a constraint that should be true before and after any method completes, each public method and constructor should contain the following line immediately prior to its return:
assert balanced();
It is generally unnecessary to place similar checks at the head of each public method unless the data structure is implemented by native methods. In this case, it is possible that a memory corruption bug could corrupt a "native peer" data structure in between method invocations. A failure of the assertion at the head of such a method would indicate that such memory corruption had occurred. Similarly, it may be advisable to include class invariant checks at the heads of methods in classes whose state is modifiable by other classes. (Better yet, design classes so that their state is not directly visible to other classes!)
The following sections discuss topics that apply only to resource-constrained devices and to systems where asserts must not be disabled in the field. If you have no interest in these topics, skip to the next section, "Compiling Files that Use Assertions".
Programmers developing applications for resource-constrained devices may wish to strip assertions out of class files entirely. While this makes it impossible to enable assertions in the field, it also reduces class file size, possibly leading to improved class loading performance. In the absence of a high quality JIT, it could lead to decreased footprint and improved runtime performance.
The assertion facility offers no direct support for stripping assertions out of class files. The assert statement may, however, be used in conjunction with the "conditional compilation" idiom described in the Java Language Specification, enabling the compiler to eliminate all traces of these asserts from the class files that it generates:
static final boolean asserts = ... ; // false to eliminate asserts if (asserts) assert <expr> ;
Programmers of certain critical systems might wish to ensure that assertions are not disabled in the field. The following static initialization idiom prevents a class from being initialized if its assertions have been disabled:
static { boolean assertsEnabled = false; assert assertsEnabled = true; // Intentional side effect!!! if (!assertsEnabled) throw new RuntimeException("Asserts must be enabled!!!"); }
Put this static-initializer at the top of your class.
In order for the javac
compiler to accept code
containing assertions, you must use the
-source 1.4
command-line option as in this
example:
javac -source 1.4 MyClass.java
This flag is necessary so as not to cause source compatibility problems.
By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions.
To enable assertions at various granularities, use the
-enableassertions
, or
-ea
, switch. To disable assertions at
various granularities, use the
-disableassertions
, or
-da
, switch. You specify the granularity
with the arguments that you provide to the switch:
...
...
For example, the following command runs a program,
BatTutor
, with assertions enabled in only package
com.wombat.fruitbat
and its subpackages:
java -ea:com.wombat.fruitbat... BatTutor
If a single command line contains multiple instances of these
switches, they are processed in order before loading any classes.
For example, the following command runs the BatTutor
program with assertions enabled in package
com.wombat.fruitbat
but disabled in class
com.wombat.fruitbat.Brickbat
:
java -ea:com.wombat.fruitbat... -da:com.wombat.fruitbat.Brickbat BatTutor
The above switches apply to all class loaders. With one exception, they also apply to system classes (which do not have an explicit class loader). The exception concerns the switches with no arguments, which (as indicated above) do not apply to system classes.This behavior makes it easy to enable asserts in all classes except for system classes, which is commonly desirable.
To enable assertions in all system classes, use a different
switch: -enablesystemassertions
, or
-esa
. Similarly, to disable assertions in
system classes, use
-disablesystemassertions
, or
-dsa
.
For example, the following command runs the
BatTutor
program with assertions enabled in system
classes, as well as in the com.wombat.fruitbat
package
and its subpackages:
java -esa -ea:com.wombat.fruitbat...
The assertion status of a class (enabled or disabled) is set at the time it is initialized, and does not change. There is, however, one corner case that demands special treatment. It is possible, though generally not desirable, to execute methods or constructors prior to initialization. This can happen when a class hierarchy contains a circularity in its static initialization.
If an assert statement executes before its class is initialized, the execution must behave as if assertions were enabled in the class. This topic is discussed in detail in the assertions specification in the Java Language Specification.
The addition of the assert
keyword to the Java
programming language does not cause any problems with preexisting
binaries (.class
files). If you try to compile an
application that uses assert
as an identifier,
however, you will receive a warning or error message. In order to
ease the transition from a world where assert
is a
legal identifier to one where it isn't, the compiler supports two
modes of operation in this release:
assert
as an identifier, but issues
warnings. In this mode, programs are not permitted to use
the assert
statement.assert
as an identifier.
In this mode, programs are permitted to use the
assert
statement.Unless you specifically request source mode 1.4 with the
-source 1.4
flag, the compiler operates in source mode
1.3. If you forget to use this flag, programs that use the new
assert
statement will not compile. Having the
compiler use the old semantics as its default behavior (that is,
allowing assert
to be used as an identifier) was done
for maximal source compatibility. Source mode 1.3 is likely to be
phased out over time.
Here is a collection of frequently asked questions concerning the design of the assertion facility.
AssertionError
ClassAlthough ad hoc implementations are possible, they are of
necessity either ugly (requiring an if
statement for
each assertion) or inefficient (evaluating the condition even if
assertions are disabled). Further, each ad hoc implementation has
its own means of enabling and disabling assertions, which lessens
the utility of these implementations, especially for debugging in
the field. As a result of these shortcomings, assertions have never
become a part of the culture among engineers using the Java
programming language. Adding assertion support to the platform
stands a good chance of rectifying this situation.
We recognize that a language change is a serious effort, not to
be undertaken lightly. The library approach was considered. It was,
however, deemed essential that the runtime cost of assertions be
negligible if they are disabled. In order to achieve this with a
library, the programmer is forced to hard-code each assertion as an
if
statement. Many programmers would not do this.
Either they would omit the if statement and performance would
suffer, or they would ignore the facility entirely. Note also that
assertions were contained in James Gosling's original specification
for the Java programming language. Assertions were removed from the
Oak specification because time constraints prevented a satisfactory
design and implementation.
We considered providing such a facility, but were unable to convince ourselves that it is possible to graft it onto the Java programming language without massive changes to the Java platform libraries, and massive inconsistencies between old and new libraries. Further, we were not convinced that such a facility would preserve the simplicity that is the hallmark of the Java programming language. On balance, we came to the conclusion that a simple boolean assertion facility was a fairly straight-forward solution and far less risky. It's worth noting that adding a boolean assertion facility to the language doesn't preclude adding a full-fledged design-by-contract facility at some time in the future.
The simple assertion facility does enable a limited form of
design-by-contract style
programming. The assert
statement is appropriate
for nonpublic precondition, postcondition and class invariant
checking. Public precondition checking should still be performed by
checks inside methods that result in particular, documented
exceptions, such as IllegalArgumentException
and
IllegalStateException
.
Providing such a construct would encourage programmers to put complex assertions inline, when they are better relegated to separate methods.
assert
as an
identifier?
Yes, for source files. (Binaries for classes that use
assert
as an identifier will continue to work fine.)
To ease the transition, we implemented a
strategy whereby developers can continue using
assert
as an identifier during a transitional
period.
Yes. Class files will contain calls to the new ClassLoader and Class methods, such as desiredAssertionStatus. If a class file containing calls to these methods is run against an older JRE (whose ClassLoader class doesn't define the methods), the program will fail at run time, throwing a NoSuchMethodError. It is generally the case that programs using new facilities are not compatible with older releases.
There is no compelling reason to restrict the type of this
expression. Allowing arbitrary types provides convenience for
developers who, for example, want to associate a unique integer
code with each assertion. Further, it makes this expression feel
like the argument of System.out.println(...)
, which is
seen as desirable.
AssertionError
is generated by an
assert statement in which Expression2 is absent, why isn't the program
text of the asserted condition used as the detail message (for
example, "height <
maxHeight
")?
While doing so might improve out-of-the-box usefulness of
assertions in some cases, the benefit doesn't justify the cost of
adding all those string constants to .class
files and
runtime images.
AssertionError
allow access to
the object that generated it? Similarly, why not pass an arbitrary
object from the assertion to the AssertionError
constructor in place of a detail message?
Access to these objects would encourage programmers to attempt to recover from assertion failures, which defeats the purpose of the facility.
getFile
, getline
, getMethod
)
on AssertionError
?
This facility is best provided on Throwable
, so it
may be used for all throwables, not just assertion errors. We
enhanced Throwable
with the getStackTrace
method to provide this functionality.
AssertionError
a subclass of
Error
rather than RuntimeException
?
This issue was controversial. The expert group discussed it at
length, and came to the conclusion that Error
was more
appropriate to discourage programmers from attempting to recover
from assertion failures. It is, in general, difficult or impossible
to localize the source of an assertion failure. Such a failure
indicates that the program is operating "outside of known space,"
and attempts to continue execution are likely to be harmful.
Further, convention dictates that methods specify most runtime
exceptions they may throw (with @throws
doc comments).
It makes little sense to include in a method's specification the
circumstances under which it may generate an assertion failure.
Such information may be regarded as an implementation detail, which
can change from implementation to implementation and release to
release.
It is a firm requirement that it be possible to enable assertions in the field, for enhanced serviceability. It would have been possible to also permit developers to eliminate assertions from object files at compile time. Assertions can contain side effects, though they should not, and such a flag could therefore alter the behavior of a program in significant ways. It is viewed as good thing that there is only one semantics associated with each valid Java program. Also, we want to encourage users to leave asserts in object files so they can be enabled in the field. Finally, the spec demands that assertions behave as if enabled when a class runs before it is initialized. It would be impossible to offer these semantics if assertions were stripped from the class file. Note, however, that the standard "conditional compilation idiom" described in the Java Language Specification can be used to achieve this effect for developers who really want it.
Hierarchical control is useful, as programmers really do use package hierarchies to organize their code. For example, package-tree semantics allow assertions to be enabled or disabled in all of Swing at one time.
setClassAssertionStatus
return a
boolean
instead of throwing an exception if it is
invoked when it's too late to set the assertion status (that is, if
the named class has already been initialized)?
No action (other than perhaps a warning message) is necessary or desirable if it's too late to set the assertion status. An exception seems unduly heavyweight.
setDefaultAssertionStatus
and
setAssertionStatus
?
Clarity in method naming is for the greater good. Overloading tends to cause confusion.
It's not clear that there would be any use for the resulting method. The method isn't designed for application programmer use, and it seems inadvisable to make it slower and more complex than necessary.
RuntimePermission
to prevent
applets from enabling/disabling assertions?
While applets have no reason to call any of the
ClassLoader
methods for modifying assertion status,
allowing them to do so seems harmless. At worst, an applet can
mount a weak denial-of-service attack by enabling assertions in
classes that have yet to be initialized. Moreover, applets can only
affect the assert status of classes that are to be loaded by class
loaders that the applets can access. There already exists a
RuntimePermission
to prevent untrusted code from
gaining access to class loaders (getClassLoader
).
Such a construct would encourage people to inline complex assertion code, which we view as a bad thing. Further, it is straightforward to query the assert status atop the current API, if you feel you must:
boolean assertsEnabled = false; assert assertsEnabled = true; // Intentional side-effect!!! // Now assertsEnabled is set to the correct value
Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization. When this happens, it is quite likely that the class's invariants have not yet been established, which can cause serious and subtle bugs. Any assertion that executes in this state is likely to fail, alerting the programmer to the problem. Thus, it is generally helpful to the programmer to execute all assertions encountered while in this state.


Transparency Supervisor
You are safe!
Don't worry we prevent websites sending
data to known tracker domains.
⚑


The Symantec Enterprise Security business is now a part of Broadcom
Secure your IT Infrastructure with Us
All your security needs under one roof
Choose our services for Secure and User-Friendly outcomes!
In Digital World, Precaution is always better than Cure.
About Cyber Defender
Cyber Defender is India’s upcoming organization in the field of Information and Cyber Security. We aim to digitally shield the cyberspace by offering various products and services. We are providing Cyber Security Services and Consultancies like Web & Mobile based Application Penetration Testing, Infrastructure & Network Audits. We are hovering to Influence our Proficiency and Global Footprint in the field of Information Security and Cyber Crime Investigation.
;
Total Cyber Security Solutions
We aim to digitally shield the cyberspace by offering various products and services. We have dedicated our highly skilled and expert advisers to offer services like VAPT and cybercrime consultancy to encase the digital sphere with secure cyberspace
VAPT
Data is crucial for Organizations and data loss lead to compliance, monetary and reputational loss.
Vulnerability Assessments and Penetration Testing
“A cyber security breach can strike at any time, putting your organization at risk”
Vulnerability Assessments and Penetration Testing (VAPT) offer wide-ranging services to perform security audit and provide recommendation for security disruption, monitor security for risk analysis, forensics and penetration testing.
Vulnerability Assessment
Vulnerability Assessment is a comprehensive scanning through various security validations to locate the vulnerable flaws in the pre-existing code. Vulnerability Assessment is limited to locate the vulnerability but it doesn’t reveal the impact or destruction level that can be caused due to the identified flaws.
Penetration Testing
Penetration Testing is a method to exploit the analyzed vulnerabilities using appropriate tools as well as manually. Penetration Testing shows that out of N no. of flaws found in Vulnerability assessment which particular flaw may lead to highest degree of penetration of malicious attack so it measures the impact of vulnerability and possible destruction level.
Vulnerability Assessment and Penetration Testing (VA / PT)
So VAPT is a combination of both VA & PT, which locates the flaws in the system, measures the vulnerability of each flaw, classifies the nature of possible attack and raises the alarm before these flaws lead to any exploitation.
Vulnerability: A flaw or weakness in system security procedures, design, implementation, or internal controls that may result in a security breach or a violation of the system’s security policy.


pip_services_runtime.config.Connection module¶
pip_services_runtime.config.Connection¶
Connection configuration implementation
| copyright: | Digital Living Software Corp. 2015-2016, see AUTHORS for more details. |
|---|---|
| license: | MIT, see LICENSE for more details. |
-
class
pip_services_runtime.config.Connection.
Connection
(content)¶ Bases:
object
Database connection configuration as set in the component config. It usually contains a complete uri or separate host, port, user, password, etc.
-
get_database
()¶ Gets the database name. Returns: the database name
-
get_host
()¶ Gets the connection host name or ip address. Returns: a string representing connection host
-
get_password
()¶ Gets the connection user password. Returns: the user password
-
get_port
()¶ Gets the connection port number Returns: integer representing the connection port.
-
get_raw_content
()¶ Gets connection as free-form configuration set.
Returns: DynamicMap with connection configuration.
-
get_type
()¶ Gets the connection type Returns: the connection type
-
get_uri
()¶ Gets the connection uri constructed from type, host and port Returns: uri as <type>://<host>:<port>
-
get_username
()¶ Gets the connection user name. Returns: the user name
-


|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: REQUIRED | OPTIONAL | DETAIL: ELEMENT |
@Documented @Retention(value=RUNTIME) @Target(value=TYPE) public @interface ReportsCrashes
Provide configuration elemets to the ACRA.init(android.app.Application)
method. The only mandatory
configuration item is the formKey()
parameter which is the Id of your Google Documents form which will
receive reports.
| Required Element Summary | |
|---|---|
String |
formKey
The id of the Google Doc form. |
| Optional Element Summary | |
|---|---|
String[] |
additionalDropBoxTags
You can provide here a list of tags that will be fetched when collecting DropBox entries. |
String[] |
additionalSharedPreferences
Add here your SharedPreferences identifier Strings if you use others than your application's default. |
ReportField[] |
customReportContent
Specifies the list of fields to be included in reports with their order. |
boolean |
deleteUnapprovedReportsOnApplicationStart
Controls whether unapproved reports are deleted on application start or not. |
int |
dropboxCollectionMinutes
How many minutes will be looked back when collecting events from DropBoxManager. |
boolean |
forceCloseDialogAfterToast
In ReportingInteractionMode.TOAST mode, set this to true if you prefer displaying the native Force Close
dialog after the Toast. |
String |
formUri
The Uri of your own server-side script that will receive reports. |
String |
formUriBasicAuthLogin
When using the formUri() parameter to send reports to a custom server-side script, you can set here and
in formUriBasicAuthPassword() the credentials for a BASIC HTTP authentication. |
String |
formUriBasicAuthPassword
When using the formUri() parameter to send reports to a custom server-side script, you can set here and
in formUriBasicAuthLogin() the credentials for a BASIC HTTP authentication. |
boolean |
includeDropBoxSystemTags
If enabled, DropBox events collection will include system tags: system_app_anr system_app_wtf system_app_crash system_server_anr system_server_wtf system_server_crash BATTERY_DISCHARGE_INFO SYSTEM_RECOVERY_LOG SYSTEM_BOOT SYSTEM_LAST_KMSG APANIC_CONSOLE APANIC_THREADS SYSTEM_RESTART SYSTEM_TOMBSTONE data_app_strictmode Requires #includeDropBox() true. |
String[] |
logcatArguments
Arguments to be passed to the logcat command line. |
String |
mailTo
Add your crash reports mailbox here if you want to send reports via email. |
ReportingInteractionMode |
mode
The interaction mode you want to implement. |
int |
resDialogCommentPrompt
Resource id for the user comment input label in the crash dialog. |
int |
resDialogEmailPrompt
Resource id for the user email address input label in the crash dialog. |
int |
resDialogIcon
Resource id for the icon in the crash dialog. |
int |
resDialogOkToast
Resource id for the Toast text triggered when the user accepts to send a report in the crash dialog. |
int |
resDialogText
Resource id for the text in the crash dialog. |
int |
resDialogTitle
Resource id for the title in the crash dialog. |
int |
resNotifIcon
Resource id for the icon in the status bar notification. |
int |
resNotifText
Resource id for the text in the status bar notification. |
int |
resNotifTickerText
Resource id for the ticker text in the status bar notification. |
int |
resNotifTitle
Resource id for the title in the status bar notification. |
int |
resToastText
Resource id for the Toast text triggered when the application crashes if the notification+dialog mode is not used. |
int |
sharedPreferencesMode
If using a custom sharedPreferencesName() , pass here the mode that you need for the
SharedPreference file creation: Context.MODE_PRIVATE , Context.MODE_WORLD_READABLE or
Context.MODE_WORLD_WRITEABLE . |
String |
sharedPreferencesName
Name of the SharedPreferences that will host the ACRA.PREF_DISABLE_ACRA or ACRA.PREF_ENABLE_ACRA
preference. |
int |
socketTimeout
Value in milliseconds for network operations timeout (default 3000ms). |
| Element Detail |
|---|
public abstract String formKey
public abstract String formUri
public abstract ReportingInteractionMode mode
The interaction mode you want to implement. Default is ReportingInteractionMode.SILENT
which does not
require any resources configuration.
Other modes have resources requirements:
ReportingInteractionMode.TOAST
requires resToastText()
to be provided to define the text
that you want to be displayed to the user when a report is being sent.ReportingInteractionMode.NOTIFICATION
requires resNotifTickerText()
,
resNotifTitle()
, resNotifText()
, resDialogText()
public abstract int resDialogCommentPrompt
public abstract int resDialogEmailPrompt
public abstract int resDialogIcon
public abstract int resDialogOkToast
public abstract int resDialogText
public abstract int resDialogTitle
public abstract int resNotifIcon
public abstract int resNotifText
public abstract int resNotifTickerText
public abstract int resNotifTitle
public abstract int resToastText
public abstract String sharedPreferencesName
ACRA.PREF_DISABLE_ACRA
or ACRA.PREF_ENABLE_ACRA
preference. Default is to use the default SharedPreferences, as retrieved with
PreferenceManager.getDefaultSharedPreferences(Context)
.
public abstract int sharedPreferencesMode
sharedPreferencesName()
, pass here the mode that you need for the
SharedPreference file creation: Context.MODE_PRIVATE
, Context.MODE_WORLD_READABLE
or
Context.MODE_WORLD_WRITEABLE
. Default is Context.MODE_PRIVATE
.
Context.getSharedPreferences(String, int)
public abstract boolean includeDropBoxSystemTags
#includeDropBox()
true.
public abstract String[] additionalDropBoxTags
public abstract int dropboxCollectionMinutes
public abstract String[] logcatArguments
Arguments to be passed to the logcat command line. Default is { "-t", "200", "-v", "time" } for:
logcat -t 200 -v time
Do not include -b arguments for buffer selection, use #includeEventsLogcat()
and
#includeRadioLogcat()
to activate alternative logcat buffers reporting. They will use the same other
arguments as those provided here.
See Listing of logcat Command Options.
public abstract String formUriBasicAuthLogin
formUri()
parameter to send reports to a custom server-side script, you can set here and
in formUriBasicAuthPassword()
the credentials for a BASIC HTTP authentication.
public abstract String formUriBasicAuthPassword
formUri()
parameter to send reports to a custom server-side script, you can set here and
in formUriBasicAuthLogin()
the credentials for a BASIC HTTP authentication.
public abstract ReportField[] customReportContent
public abstract String mailTo
#reportFields()
. Default fields are:
ReportField.USER_COMMENT
, ReportField.ANDROID_VERSION
, ReportField.APP_VERSION_NAME
,
ReportField.BRAND
, ReportField.PHONE_MODEL
, ReportField.CUSTOM_DATA
,
ReportField.STACK_TRACE
public abstract boolean deleteUnapprovedReportsOnApplicationStart
public abstract int socketTimeout
public abstract boolean forceCloseDialogAfterToast
ReportingInteractionMode.TOAST
mode, set this to true if you prefer displaying the native Force Close
dialog after the Toast.
public abstract String[] additionalSharedPreferences
SharedPreferences
identifier Strings if you use others than your application's default.
They will be added to the ReportField.SHARED_PREFERENCES
field.
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: REQUIRED | OPTIONAL | DETAIL: ELEMENT |


Howard House
Wagon Lane
Bingley
BD16 1WA
West Yorkshire
United Kingdom
Emerald Group Publishing Limited is committed to maintaining and protecting your privacy when using its website. Our privacy policy explains the types of information we collect from you and how this is used. This policy applies solely to the information you provide while visiting this website and does not relate to information collected or distributed by means other than the site, e.g. via telephone or postal mail.
We sometimes request users of our website to voluntarily provide personal information. This information may include your name, e-mail address, contact address and/or delivery address and credit/debit card details. All credit/debit card information is encoded to maximize security before being sent over the Internet. We may also ask you for demographic and job-related information when conducting our market-research surveys.
The website also collects information through the use of “cookies”. Follow the link for more information on our cookie policy.
We use the personal information that you provide for such purposes as:
Access to your personal information is restricted to our employees, agents, representatives , printing and fulfilment operations. We occasionally share information with carefully selected companies or third parties, but only when we have received your permission to do so. Some of these companies or third parties may be located in countries outside the European Economic Area (EEA) which do not have the same data protection laws as the EEA. If we transfer your information outside of the EEA, we will ensure that your privacy rights continue to be protected.
We will not otherwise disclose any personal information without your consent, except under the following circumstances:
You may access your personal information by contacting our customer support team at the address or telephone number detailed below. You may correct any errors or update information, submitted to us via the website, by accessing the “My Profile” facility, located on each of the sub-domains of our site. Alternatively, information may be updated by contacting our customer support team at the address or telephone number detailed below.
If you wish to receive newsletters or new product announcements, please tick the appropriate check box within the “Newsletters” section, when registering with “My Profile”. If you do not wish to continue receiving any of this information, please use the “Unsubscribe” option within the “Newsletters” section of “My Profile”. Alternatively, you may contact our customer support team at the address or telephone number detailed below.
Your personal information is stored by us for as long as the information is relevant to our business purposes or until you request that we remove it from our records. You may request that your information is removed by contacting our customer support team at the address or telephone number detailed below.
We follow strict security procedures in the storage and disclosure of the information you have given to us in order to protect your privacy. Your personal information is stored on servers that are behind a firewall and physically located within a secured data centre. In addition, our internal practices limit access to and use of your personal information and therefore help to secure your privacy.
If you have any questions, comments or complaints regarding this privacy policy, please contact our customer support team at:
Emerald Group Publishing Limited
Howard House
Wagon Lane
Bingley
BD16 1WA
West Yorkshire
United Kingdom
Tel: +44 (0) 1274 777700
Fax: +44 (0) 1274 785200
E-mail<EMAIL_ADDRESS>© Emerald Group Publishing Limited


FunRetro is still free. But there's now a premium version with more features and security. Check it out


Space, Time, Motion, Reference Frames and Reminder on vectors and other mathematical quantities¶
Our studies will start with the motion of different types of objects such as a falling ball, a runner, a bicycle etc etc. It means that an object’s position in space varies with time. In order to study such systems we need to define
choice of origin
choice of the direction of the axes
choice of positive direction (left-handed or right-handed system of reference)
choice of units and dimensions
These choices lead to some important questions such as
is the physics of a system independent of the origin of the axes?
is the physics independent of the directions of the axes, that is are there privileged axes?
is the physics independent of the orientation of system?
is the physics independent of the scale of the length?
Dimension, units and labels¶
Throughout this course we will use the standardized SI units. The standard unit for length is thus one meter 1m, for mass one kilogram 1kg, for time one second 1s, for force one Newton 1kgm/s\(^2\) and for energy 1 Joule 1kgm\(^2\)s\(^{-2}\).
We will use the following notations for various variables (vectors are always boldfaced in these lecture notes):
position \(\boldsymbol{r}\), in one dimention we will normally just use \(x\),
mass \(m\),
time \(t\),
velocity \(\boldsymbol{v}\) or just \(v\) in one dimension,
acceleration \(\boldsymbol{a}\) or just \(a\) in one dimension,
momentum \(\boldsymbol{p}\) or just \(p\) in one dimension,
kinetic energy \(K\),
potential energy \(V\) and
frequency \(\omega\).
More variables will be defined as we need them.
It is also important to keep track of dimensionalities. Don’t mix this up with a chosen unit for a given variable. We mark the dimensionality in these lectures as \([a]\), where \(a\) is the quantity we are interested in. Thus
\([\boldsymbol{r}]=\) length
\([m]=\) mass
\([K]=\) energy
\([t]=\) time
\([\boldsymbol{v}]=\) length over time
\([\boldsymbol{a}]=\) length over time squared
\([\boldsymbol{p}]=\) mass times length over time
\([\omega]=\) 1/time
Elements of Vector Algebra¶
Note: This section is under revision
In these lectures we will use boldfaced lower-case letters to label a vector. A vector \(\boldsymbol{a}\) in three dimensions is thus defined as
and using the unit vectors in a cartesian system we have
where the unit vectors have magnitude \(\vert\boldsymbol{e}_i\vert = 1\) with \(i=x,y,z\).
Using the fact that multiplication of reals is distributive we can show that
Similarly we can also show that (using product rule for differentiating reals)
We can repeat these operations for the cross products and show that they are distribuitive
We have also that
The rotation of a three-dimensional vector \(\boldsymbol{a}=(a_x,a_y,a_z)\) in the \(xy\) plane around an angle \(\phi\) results in a new vector \(\boldsymbol{b}=(b_x,b_y,b_z)\). This operation can be expressed in terms of linear algebra as a matrix (the rotation matrix) multiplied with a vector. We can write this as
We can write this in a more compact form as \(\boldsymbol{b} = \boldsymbol{R}\boldsymbol{a}\), where the rotation matrix is defined as
Falling baseball in one dimension¶
We anticipate the mathematical model to come and assume that we have a model for the motion of a falling baseball without air resistance. Our system (the baseball) is at an initial height \(y_0\) (which we will specify in the program below) at the initial time \(t_0=0\). In our program example here we will plot the position in steps of \(\Delta t\) up to a final time \(t_f\). The mathematical formula for the position \(y(t)\) as function of time \(t\) is
where \(g=9.80665=0.980655\times 10^1\)m/s\(^2\) is a constant representing the standard acceleration due to gravity. We have here adopted the conventional standard value. This does not take into account other effects, such as buoyancy or drag. Furthermore, we stop when the ball hits the ground, which takes place at
which gives us a final time \(t_f=\sqrt{2y_0/g}\).
As of now we simply assume that we know the formula for the falling object. Afterwards, we will derive it.
Our Python Encounter¶
We start with preparing folders for storing our calculations, figures and if needed, specific data files we use as input or output files.
%matplotlib inline
# Common imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
#in case we have an input file we wish to read in
#infile = open(data_path("MassEval2016.dat"),'r')
You could also define a function for making our plots. You can obviously avoid this and simply set up various matplotlib commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function.
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
def MakePlot(x,y, styles, labels, axlabels):
plt.figure(figsize=(10,6))
for i in range(len(x)):
plt.plot(x[i], y[i], styles[i], label = labels[i])
plt.xlabel(axlabels[0])
plt.ylabel(axlabels[1])
plt.legend(loc=0)
Thereafter we start setting up the code for the falling object.
%matplotlib inline
import matplotlib.patches as mpatches
g = 9.80655 #m/s^2
y_0 = 10.0 # initial position in meters
DeltaT = 0.1 # time step
# final time when y = 0, t = sqrt(2*10/g)
tfinal = np.sqrt(2.0*y_0/g)
#set up arrays
t = np.arange(0,tfinal,DeltaT)
y =y_0 -g*.5*t**2
# Then make a nice printout in table form using Pandas
import pandas as pd
from IPython.display import display
data = {'t[s]': t,
'y[m]': y
}
RawData = pd.DataFrame(data)
display(RawData)
plt.style.use('ggplot')
plt.figure(figsize=(8,8))
plt.scatter(t, y, color = 'b')
blue_patch = mpatches.Patch(color = 'b', label = 'Height y as function of time t')
plt.legend(handles=[blue_patch])
plt.xlabel("t[s]")
plt.ylabel("y[m]")
save_fig("FallingBaseball")
plt.show()
| t[s] | y[m] | |
|---|---|---|
| 0 | 0.0 | 10.000000 |
| 1 | 0.1 | 9.950967 |
| 2 | 0.2 | 9.803869 |
| 3 | 0.3 | 9.558705 |
| 4 | 0.4 | 9.215476 |
| 5 | 0.5 | 8.774181 |
| 6 | 0.6 | 8.234821 |
| 7 | 0.7 | 7.597395 |
| 8 | 0.8 | 6.861904 |
| 9 | 0.9 | 6.028347 |
| 10 | 1.0 | 5.096725 |
| 11 | 1.1 | 4.067037 |
| 12 | 1.2 | 2.939284 |
| 13 | 1.3 | 1.713465 |
| 14 | 1.4 | 0.389581 |
Here we used pandas (see below) to systemize the output of the position as function of time.
Average quantities¶
We define now the average velocity as
In the code we have set the time step \(\Delta t\) to a given value. We could define it in terms of the number of points \(n\) as
Since we have discretized the variables, we introduce the counter \(i\) and let \(y(t)\rightarrow y(t_i)=y_i\) and \(t\rightarrow t_i\) with \(i=0,1,\dots, n\). This gives us the following shorthand notations that we will use for the rest of this course. We define
This applies to other variables which depend on say time. Examples are the velocities, accelerations, momenta etc. Furthermore we use the shorthand
Compact equations¶
We can then rewrite in a more compact form the average velocity as
The velocity is defined as the change in position per unit time. In the limit \(\Delta t \rightarrow 0\) this defines the instantaneous velocity, which is nothing but the slope of the position at a time \(t\). We have thus
Similarly, we can define the average acceleration as the change in velocity per unit time as
resulting in the instantaneous acceleration
A note on notations: When writing for example the velocity as \(v(t)\) we are then referring to the continuous and instantaneous value. A subscript like \(v_i\) refers always to the discretized values.
A differential equation¶
We can rewrite the instantaneous acceleration as
This forms the starting point for our definition of forces later. It is a famous second-order differential equation. If the acceleration is constant we can now recover the formula for the falling ball we started with. The acceleration can depend on the position and the velocity. To be more formal we should then write the above differential equation as
With given initial conditions for \(y(t_0)\) and \(v(t_0)\) we can then integrate the above equation and find the velocities and positions at a given time \(t\).
If we multiply with mass, we have one of the famous expressions for Newton’s second law,
where \(F\) is the force acting on an object with mass \(m\). We see that it also has the right dimension, mass times length divided by time squared. We will come back to this soon.
Integrating our equations¶
Formally we can then, starting with the acceleration (suppose we have measured it, how could we do that?) compute say the height of a building. To see this we perform the following integrations from an initial time \(t_0\) to a given time \(t\)
or as
When we know the velocity as function of time, we can find the position as function of time starting from the defintion of velocity as the derivative with respect to time, that is we have
or as
These equations define what is called the integration method for finding the position and the velocity as functions of time. There is no loss of generality if we extend these equations to more than one spatial dimension.
Constant acceleration case, the velocity¶
Let us compute the velocity using the constant value for the acceleration given by \(-g\). We have
Using our initial time as \(t_0=0\)s and setting the initial velocity \(v(t_0)=v_0=0\)m/s we get when integrating
The more general case is
We can then integrate the velocity and obtain the final formula for the position as function of time through
With \(y_0=10\)m and \(t_0=0\)s, we obtain the equation we started with
Computing the averages¶
After this mathematical background we are now ready to compute the mean velocity using our data.
# Now we can compute the mean velocity using our data
# We define first an array Vaverage
n = np.size(t)
Vaverage = np.zeros(n)
for i in range(1,n-1):
Vaverage[i] = (y[i+1]-y[i])/DeltaT
# Now we can compute the mean accelearatio using our data
# We define first an array Aaverage
n = np.size(t)
Aaverage = np.zeros(n)
Aaverage[0] = -g
for i in range(1,n-1):
Aaverage[i] = (Vaverage[i+1]-Vaverage[i])/DeltaT
data = {'t[s]': t,
'y[m]': y,
'v[m/s]': Vaverage,
'a[m/s^2]': Aaverage
}
NewData = pd.DataFrame(data)
display(NewData[0:n-2])
| t[s] | y[m] | v[m/s] | a[m/s^2] | |
|---|---|---|---|---|
| 0 | 0.0 | 10.000000 | 0.000000 | -9.80655 |
| 1 | 0.1 | 9.950967 | -1.470982 | -9.80655 |
| 2 | 0.2 | 9.803869 | -2.451638 | -9.80655 |
| 3 | 0.3 | 9.558705 | -3.432292 | -9.80655 |
| 4 | 0.4 | 9.215476 | -4.412948 | -9.80655 |
| 5 | 0.5 | 8.774181 | -5.393602 | -9.80655 |
| 6 | 0.6 | 8.234821 | -6.374258 | -9.80655 |
| 7 | 0.7 | 7.597395 | -7.354913 | -9.80655 |
| 8 | 0.8 | 6.861904 | -8.335567 | -9.80655 |
| 9 | 0.9 | 6.028347 | -9.316222 | -9.80655 |
| 10 | 1.0 | 5.096725 | -10.296878 | -9.80655 |
| 11 | 1.1 | 4.067037 | -11.277533 | -9.80655 |
| 12 | 1.2 | 2.939284 | -12.258187 | -9.80655 |
Note that we don’t print the last values!
Including Air Resistance in our model¶
In our discussions till now of the falling baseball, we have ignored air resistance and simply assumed that our system is only influenced by the gravitational force. We will postpone the derivation of air resistance till later, after our discussion of Newton’s laws and forces.
For our discussions here it suffices to state that the accelerations is now modified to
where \(\vert v(t)\vert\) is the absolute value of the velocity and \(D\) is a constant which pertains to the specific object we are studying. Since we are dealing with motion in one dimension, we can simplify the above to
We can rewrite this as a differential equation
Using the integral equations discussed above we can integrate twice and obtain first the velocity as function of time and thereafter the position as function of time.
For this particular case, we can actually obtain an analytical solution for the velocity and for the position. Here we will first compute the solutions analytically, thereafter we will derive Euler’s method for solving these differential equations numerically.
Analytical solutions¶
For simplicity let us just write \(v(t)\) as \(v\). We have
We can solve this using the technique of separation of variables. We isolate on the left all terms that involve \(v\) and on the right all terms that involve time. We get then
We scale now the equation to the left by introducing a constant \(v_T=\sqrt{g/D}\). This constant has dimension length/time. Can you show this?
Next we integrate the left-hand side (lhs) from \(v_0=0\) m/s to \(v\) and the right-hand side (rhs) from \(t_0=0\) to \(t\) and obtain
We can reorganize these equations as
which gives us \(v\) as function of time
Finding the final height¶
With the velocity we can then find the height \(y(t)\) by integrating yet another time, that is
This integral is a little bit trickier but we can look it up in a table over known integrals and we get
Alternatively we could have used the symbolic Python package Sympy (example will be inserted later).
In most cases however, we need to revert to numerical solutions.
Our first attempt at solving differential equations¶
Here we will try the simplest possible approach to solving the second-order differential equation
We rewrite it as two coupled first-order equations (this is a standard approach)
with initial condition \(y(t_0)=y_0\) and
with initial condition \(v(t_0)=v_0\).
Many of the algorithms for solving differential equations start with simple Taylor equations. If we now Taylor expand \(y\) and \(v\) around a value \(t+\Delta t\) we have
and
Using the fact that \(dy/dt = v\) and \(dv/dt=a\) and keeping only terms up to \(\Delta t\) we have
and
Discretizing our equations¶
Using our discretized versions of the equations with for example \(y_{i}=y(t_i)\) and \(y_{i\pm 1}=y(t_i+\Delta t)\), we can rewrite the above equations as (and truncating at \(\Delta t\))
and
These are the famous Euler equations (forward Euler).
To solve these equations numerically we start at a time \(t_0\) and simply integrate up these equations to a final time \(t_f\), The step size \(\Delta t\) is an input parameter in our code. You can define it directly in the code below as
DeltaT = 0.1
With a given final time tfinal we can then find the number of integration points via the ceil function included in the math package of Python as
#define final time, assuming that initial time is zero
from math import ceil
tfinal = 0.5
n = ceil(tfinal/DeltaT)
print(n)
5
The ceil function returns the smallest integer not less than the input in say
x = 21.15
print(ceil(x))
22
which in the case here is 22.
x = 21.75
print(ceil(x))
22
which also yields 22. The floor function in the math package is used to return the closest integer value which is less than or equal to the specified expression or value. Compare the previous result to the usage of floor
from math import floor
x = 21.75
print(floor(x))
21
Alternatively, we can define ourselves the number of integration(mesh) points. In this case we could have
n = 10
tinitial = 0.0
tfinal = 0.5
DeltaT = (tfinal-tinitial)/(n)
print(DeltaT)
0.05
Since we will set up one-dimensional arrays that contain the values of various variables like time, position, velocity, acceleration etc, we need to know the value of \(n\), the number of data points (or integration or mesh points). With \(n\) we can initialize a given array by setting all elelements to zero, as done here
# define array a
a = np.zeros(n)
print(a)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Code for implementing Euler’s method¶
In the code here we implement this simple Eurler scheme choosing a value for \(D=0.0245\) m/s.
# Common imports
import numpy as np
import pandas as pd
from math import *
import matplotlib.pyplot as plt
import os
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
g = 9.80655 #m/s^2
D = 0.00245 #m/s
DeltaT = 0.1
#set up arrays
tfinal = 0.5
n = ceil(tfinal/DeltaT)
# define scaling constant vT
vT = sqrt(g/D)
# set up arrays for t, a, v, and y and we can compare our results with analytical ones
t = np.zeros(n)
a = np.zeros(n)
v = np.zeros(n)
y = np.zeros(n)
yanalytic = np.zeros(n)
# Initial conditions
v[0] = 0.0 #m/s
y[0] = 10.0 #m
yanalytic[0] = y[0]
# Start integrating using Euler's method
for i in range(n-1):
# expression for acceleration
a[i] = -g + D*v[i]*v[i]
# update velocity and position
y[i+1] = y[i] + DeltaT*v[i]
v[i+1] = v[i] + DeltaT*a[i]
# update time to next time step and compute analytical answer
t[i+1] = t[i] + DeltaT
yanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT))
if ( y[i+1] < 0.0):
break
a[n-1] = -g + D*v[n-1]*v[n-1]
data = {'t[s]': t,
'y[m]': y-yanalytic,
'v[m/s]': v,
'a[m/s^2]': a
}
NewData = pd.DataFrame(data)
display(NewData)
#finally we plot the data
fig, axs = plt.subplots(3, 1)
axs[0].plot(t, y, t, yanalytic)
axs[0].set_xlim(0, tfinal)
axs[0].set_ylabel('y and exact')
axs[1].plot(t, v)
axs[1].set_ylabel('v[m/s]')
axs[2].plot(t, a)
axs[2].set_xlabel('time[s]')
axs[2].set_ylabel('a[m/s^2]')
fig.tight_layout()
save_fig("EulerIntegration")
plt.show()
| t[s] | y[m] | v[m/s] | a[m/s^2] | |
|---|---|---|---|---|
| 0 | 0.0 | 0.000000 | 0.000000 | -9.806550 |
| 1 | 0.1 | 0.049031 | -0.980655 | -9.804194 |
| 2 | 0.2 | 0.098034 | -1.961074 | -9.797128 |
| 3 | 0.3 | 0.146963 | -2.940787 | -9.785362 |
| 4 | 0.4 | 0.195770 | -3.919323 | -9.768915 |
Try different values for \(\Delta t\) and study the difference between the exact solution and the numerical solution.
Simple extension, the Euler-Cromer method¶
The Euler-Cromer method is a simple variant of the standard Euler method. We use the newly updated velocity \(v_{i+1}\) as an input to the new position, that is, instead of
and
we use now the newly calculate for \(v_{i+1}\) as input to \(y_{i+1}\), that is we compute first
and then
Implementing the Euler-Cromer method yields a simple change to the previous code. We only need to change the following line in the loop over time steps
for i in range(n-1):
# more codes in between here
v[i+1] = v[i] + DeltaT*a[i]
y[i+1] = y[i] + DeltaT*v[i+1]
# more code
Python practicalities, Software and needed installations¶
We will make extensive use of Python as programming language and its myriad of available libraries. You will find Jupyter notebooks invaluable in your work.
If you have Python installed (we strongly recommend Python3) and you feel pretty familiar with installing different packages, we recommend that you install the following Python packages via pip as
pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
For Python3, replace pip with pip3.
For OSX users we recommend, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example
brew install python3
For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, you can use pip as well and simply install Python as
sudo apt-get install python3 (or python for pyhton2.7)
etc etc.
Python installers¶
If you don’t want to perform these operations separately and venture into the hassle of exploring how to set up dependencies and paths, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely
which is an open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment. Package versions are managed by the package management system conda.
is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
Furthermore, Google’s Colab is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud. Try it out!
Useful Python libraries¶
Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)
NumPy is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays
The pandas library provides high-performance, easy-to-use data structures and data analysis tools
Xarray is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!
Scipy (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering.
Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.
Autograd can automatically differentiate native Python and Numpy code. It can handle a large subset of Python’s features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives
SymPy is a Python library for symbolic mathematics.
scikit-learn has simple and efficient tools for machine learning, data mining and data analysis
TensorFlow is a Python library for fast numerical computing created and released by Google
Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano
Your jupyter notebook can easily be converted into a nicely rendered PDF file or a Latex file for further processing. For example, convert to latex as
pycod jupyter nbconvert filename.ipynb --to latex
And to add more versatility, the Python package SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.
Numpy examples and Important Matrix and vector handling packages¶
There are several central software libraries for linear algebra and eigenvalue problems. Several of the more popular ones have been wrapped into ofter software packages like those from the widely used text Numerical Recipes. The original source codes in many of the available packages are often taken from the widely used software package LAPACK, which follows two other popular packages developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.
LINPACK: package for linear equations and least square problems.
LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK’s website http://www.netlib.org it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.
BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from http://www.netlib.org.
Basic Matrix Features¶
Matrix properties reminder.
The inverse of a matrix is defined by
| Relations | Name | matrix elements |
|---|---|---|
| $A = A^{T}$ | symmetric | $a_{ij} = a_{ji}$ |
| $A = \left (A^{T} \right )^{-1}$ | real orthogonal | $\sum_k a_{ik} a_{jk} = \sum_k a_{ki} a_{kj} = \delta_{ij}$ |
| $A = A^{ * }$ | real matrix | $a_{ij} = a_{ij}^{ * }$ |
| $A = A^{\dagger}$ | hermitian | $a_{ij} = a_{ji}^{ * }$ |
| $A = \left (A^{\dagger} \right )^{-1}$ | unitary | $\sum_k a_{ik} a_{jk}^{ * } = \sum_k a_{ki}^{ * } a_{kj} = \delta_{ij}$ |
Some famous Matrices¶
Diagonal if \(a_{ij}=0\) for \(i\ne j\)
Upper triangular if \(a_{ij}=0\) for \(i > j\)
Lower triangular if \(a_{ij}=0\) for \(i < j\)
Upper Hessenberg if \(a_{ij}=0\) for \(i > j+1\)
Lower Hessenberg if \(a_{ij}=0\) for \(i < j+1\)
Tridiagonal if \(a_{ij}=0\) for \(|i -j| > 1\)
Lower banded with bandwidth \(p\): \(a_{ij}=0\) for \(i > j+p\)
Upper banded with bandwidth \(p\): \(a_{ij}=0\) for \(i < j+p\)
Banded, block upper triangular, block lower triangular….
More Basic Matrix Features¶
Some Equivalent Statements.
For an \(N\times N\) matrix \(\mathbf{A}\) the following properties are all equivalent
If the inverse of \(\mathbf{A}\) exists, \(\mathbf{A}\) is nonsingular.
The equation \(\mathbf{Ax}=0\) implies \(\mathbf{x}=0\).
The rows of \(\mathbf{A}\) form a basis of \(R^N\).
The columns of \(\mathbf{A}\) form a basis of \(R^N\).
\(\mathbf{A}\) is a product of elementary matrices.
\(0\) is not eigenvalue of \(\mathbf{A}\).
Numpy and arrays¶
Numpy provides an easy way to handle arrays in Python. The standard way to import this library is as
import numpy as np
Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,
n = 10
x = np.random.normal(size=n)
print(x)
[-1.04569783 1.68833083 1.59472197 -0.22027464 -1.12477388 0.78480985
0.8799874 -0.43301111 -0.53140431 0.2976373 ]
We defined a vector \(x\) with \(n=10\) elements with its values given by the Normal distribution \(N(0,1)\). Another alternative is to declare a vector as follows
import numpy as np
x = np.array([1, 2, 3])
print(x)
[1 2 3]
Here we have defined a vector with three elements, with \(x_0=1\), \(x_1=2\) and \(x_2=3\). Note that both Python and C++ start numbering array elements from \(0\) and on. This means that a vector with \(n\) elements has a sequence of entities \(x_0, x_1, x_2, \dots, x_{n-1}\). We could also let (recommended) Numpy to compute the logarithms of a specific array as
import numpy as np
x = np.log(np.array([4, 7, 8]))
print(x)
[1.38629436 1.94591015 2.07944154]
In the last example we used Numpy’s unary function \(np.log\). This function is highly tuned to compute array elements since the code is vectorized and does not require looping. We normaly recommend that you use the Numpy intrinsic functions instead of the corresponding log function from Python’s math module. The looping is done explicitely by the np.log function. The alternative, and slower way to compute the logarithms of a vector would be to write
import numpy as np
from math import log
x = np.array([4, 7, 8])
for i in range(0, len(x)):
x[i] = log(x[i])
print(x)
[1 1 2]
We note that our code is much longer already and we need to import the log function from the math module. The attentive reader will also notice that the output is \([1, 1, 2]\). Python interprets automagically our numbers as integers (like the automatic keyword in C++). To change this we could define our array elements to be double precision numbers as
import numpy as np
x = np.log(np.array([4, 7, 8], dtype = np.float64))
print(x)
[1.38629436 1.94591015 2.07944154]
or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0])
print(x)
File "<ipython-input-20-f6d7a289d493>", line 3
print(x)
^
SyntaxError: invalid syntax
To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the itemsize functionality (the array \(x\) is actually an object which inherits the functionalities defined in Numpy) as
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0])
print(x.itemsize)
Matrices in Python¶
Having defined vectors, we are now ready to try out matrices. We can define a \(3 \times 3 \) real matrix \(\hat{A}\) as (recall that we user lowercase letters for vectors and uppercase letters for matrices)
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
print(A)
If we use the shape function we would get \((3, 3)\) as output, that is verifying that our matrix is a \(3\times 3\) matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[:,0])
We can continue this was by printing out other columns or rows. The example here prints out the second column
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[1,:])
Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the Numpy website for more details. Useful functions when defining a matrix are the np.zeros function which declares a matrix of a given dimension and sets all elements to zero
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to zero
A = np.zeros( (n, n) )
print(A)
or initializing all elements to
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to one
A = np.ones( (n, n) )
print(A)
or as unitarily distributed random numbers (see the material on random number generators in the statistics part)
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1]
A = np.random.rand(n, n)
print(A)
Meet the Pandas¶
Another useful Python package is pandas, which is an open source library providing high-performance, easy-to-use data structures and data analysis tools for Python. pandas stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. pandas has two major classes, the DataFrame class with two-dimensional data objects and tabular data organized in columns and the class Series with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. pandas allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations.
The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of pandas, in particular in connection with classification of data.
import pandas as pd
from IPython.display import display
data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"],
'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"],
'Place of birth': ["Shire", "Shire", "Eriador", "Shire"],
'Date of Birth T.A.': [2968, 2890, 2931, 2980]
}
data_pandas = pd.DataFrame(data)
display(data_pandas)
In the above we have imported pandas with the shorthand pd, the latter has become the standard way we import pandas. We make then a list of various variables and reorganize the above lists into a DataFrame and then print out a neat table with specific column labels as Name, place of birth and date of birth. Displaying these results, we see that the indices are given by the default numbers from zero to three. pandas is extremely flexible and we can easily change the above indices by defining a new type of indexing as
data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
display(data_pandas)
Thereafter we display the content of the row which begins with the index Aragorn
display(data_pandas.loc['Aragorn'])
We can easily append data to this, for example
new_hobbit = {'First Name': ["Peregrin"],
'Last Name': ["Took"],
'Place of birth': ["Shire"],
'Date of Birth T.A.': [2990]
}
data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
display(data_pandas)
Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix of dimensionality \(10\times 5\) and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations.
import numpy as np
import pandas as pd
from IPython.display import display
np.random.seed(100)
# setting up a 10 x 5 matrix
rows = 10
cols = 5
a = np.random.randn(rows,cols)
df = pd.DataFrame(a)
display(df)
print(df.mean())
print(df.std())
display(df**2)
Thereafter we can select specific columns only and plot final results
df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
df.index = np.arange(10)
display(df)
print(df['Second'].mean() )
print(df.info())
print(df.describe())
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
df.cumsum().plot(lw=2.0, figsize=(10,6))
plt.show()
df.plot.bar(figsize=(10,6), rot=15)
plt.show()
We can produce a \(4\times 4\) matrix
b = np.arange(16).reshape((4,4))
print(b)
df1 = pd.DataFrame(b)
print(df1)
and many other operations.
The Series class is another important class included in pandas. You can view it as a specialization of DataFrame but where we have just a single column of data. It shares many of the same features as _DataFrame. As with DataFrame, most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. For multidimensional arrays, we recommend strongly xarray. xarray has much of the same flexibility as pandas, but allows for the extension to higher dimensions than two.


|
Elektra
0.8.23
|
Allows applications to automatically update registered variables when the value of a specified key has changed.
Application developers should use the Notification API instead of the functions exported by this plugin. The API is easier to use and decouples applications from this plugin.
This plugin exports the following functions. The functions addresses are exported below system/elektra/modules/internalnotification/exports/
.
All functions have a similar signature:
If the given key
is contained in a KeySet on a kdbGet or kdbSet operation a action according to the function's description is executed. Cascading keys as key
names are also supported.
Parameters
handle
is exported as system/elektra/modules/internalnotification/exports/handle
.Returns
1 on success, 0 otherwise
Please note that the plugin API may change as this plugin is experimental.
The key's value is converted to integer and the registered variable is updated with the new value.
Additional Parameters
When the key changes the callback is called with the new key.
Additional Parameters
void (*ElektraNotificationChangeCallback) (Key * key)
.


NetworkResourceWithBody
public class NetworkResourceWithBody: NetworkResource
A subclass of NetworkResource, with support for carrying a request body.
-
Sets the HTTP Body of the resource with form encoded data
Internally sets the Content-Type header of the resource to
application/x-www-form-urlencoded
Declaration
Swift
@discardableResult func fields(_ dictionary: Dictionary<String, Any>) -> NetworkResourceWithBody
Parameters
dictionary
Dictionary containing key value pairs
Return Value
NetworkResourceWithBody
-
Sets the HTTP Body of the resource to the given Data
Declaration
Swift
@discardableResult func data(_ data: Data, mimeType: String?) -> NetworkResourceWithBody
Parameters
data
data to be sent
mimeType
MIME/Content-Type to be set in the resource’s headers
Return Value
NetworkResourceWithBody
-
Sets the HTTP Body as JSON
Internally sets the Content-Type header of the resource to
application/json
Declaration
Swift
@discardableResult func json(body: Dictionary<AnyHashable, Any>, options: JSONSerialization.WritingOptions = []) -> NetworkResourceWithBody
Parameters
body
key-value pairs
options
JSONSerialization.WritingOptions, empty [] by default.
Return Value
NetworkResourceWithBody
-
Sets the HTTP Body as JSON Array
Internally sets the Content-Type header of the resource to
application/json
Declaration
Swift
@discardableResult func jsonArray(array: Array<Any>, options: JSONSerialization.WritingOptions = []) -> NetworkResourceWithBody
Parameters
body
Array
options
JSONSerialization.WritingOptions, empty [] by default.
Return Value
NetworkResourceWithBody


Question Details
Category
Question (en)
Question (ru)
Short Answer (en)
Short Answer (ru)
Preferred Answer
Comment
Usages
Edit Question
Add Key Term
Add New Question
Add New Answer
Key Terms
Name
Answers
Prefer
Answer
Ответ
Source
Actions
View
Edit
Save Selected Preferred Answer
No answers found


model_share.profile_from_model_savefile¶
-
model_share.
profile_from_model_savefile
(nc, fname, ctdname=None)[source]¶ Load the ambient.Profile data pointed to by the netCDF file
Each netCDF model save file for the TAMOC suite models stores the file name and path to the ambient CTD data used in the simulation. This prevents the save files from having to encapsulate all of the ambient CTD data with results for every simulation run. This block of code looks for the ambient data and loads it into memory if found.
- Parameters
- ncnetCDF4.Dataset object
The netCDF dataset object containing the saved model simulation
- fnamestr
File name of the netCDF file. This is used to get the complete path to the current directory so that the Profile data can be found.
- Returns
- profileambient.Profile object
The profile data as an ambient.Profile object.
See also
single_bubble_model.Model.save_sim
,stratified_plume_model.Mode.save_sim
bent_plume_model.Model.save_sim
Notes
If the profile data are not found, a message is echoed to the command line. No other warnings or errors are thrown.


A Title Trope, where Oddly Named Sequel 2: Electric Boogaloo inherits the previous installment's title as its subtitle. Can overlap with Appropriated Title.
Examples:
open/close all folders
Film - Animation
- Kingsglaive: Final Fantasy XV is an inversion. This prequel movie to Final Fantasy XV was released before the game.
- Ralph Breaks the Internet. This sequel to Wreck-It Ralph was originally named Ralph Breaks the Internet: Wreck-It Ralph 2 from its announcement until the subtitle was removed a few months before release.
Film - Live Action
- Abomination: The Evilmaker II
- Book of Shadows: Blair Witch 2, sequel to The Blair Witch Project.
- Braddock: Missing in Action III
- Brahms: The Boy II
- Citizen Toxie: The Toxic Avenger IV
- The Disney movie The Mighty Ducks had two sequels: D2: The Mighty Ducks and D3: The Mighty Ducks. D3: The Mighty Ducks is in no way related to D3 Publisher at all.
- Damien: Omen II
- Hellbound: Hellraiser II. Interesting in that it is actually derived from The Hellbound Heart, the original novella that Clive Barker based the first Hellraiser on.
- Hello Mary Lou: Prom Night II, which is accomplished by combining Titled After the Song ("Hello Mary Lou" is a pop song from the sixties) and Numbered Sequels.
- Initiation: Silent Night, Deadly Night 4
- Intercessor: Another Rock 'n' Roll Nightmare, sequel to Rock 'n' Roll Nightmare. The "original title" in this instance is the name of the character Intercessor, the real, angelic identity of the main character in the previous film.
- Although its poster reads Jason Lives: Friday the 13th Part VI, the film is universally referred to as Friday the 13th Part VI: Jason Lives.
- Leatherface: The Texas Chainsaw Massacre III, which gives the main focus on the chainsaw-toting Leatherface.
- The Lost World: Jurassic Park, sequel to Jurassic Park. Averted with Jurassic Park III and Jurassic World.
- The Rage: Carrie 2
- Rambo: First Blood Part II. The next sequel abandoned the original title altogether and just went with Rambo III.
- Son of Darkness: To Die For II
- T2 Trainspotting is the sequel to Trainspotting. It's not named Porno like the book sequel, though.
Literature
- Peter David's Star Trek Expanded Universe novel Imzadi was followed by Triangle: Imzadi II.
Live Action TV
- The Red Dwarf episode, Emohawk: Polymorph II was supposed to be called Polymorph II: Emohawk but Doug Naylor thought it sounded too much like a football score.
Video Games
- Riven: The Sequel to Myst. It's all in the title.
- Dreamfall: The Longest Journey, the sequel to The Longest Journey.

- Lightning Returns: Final Fantasy XIII, the sequel to Final Fantasy XIII and Final Fantasy XIII-2.
- Partial example: the first Modern Warfare game actually had Modern Warfare as a subtitle to Call of Duty 4. Its direct sequels, however, had numbers attached to the "subtitle" instead, keeping "Call of Duty" in the title purely for brand awareness.
- The Japanese versions of Castlevania: Lords of Shadow 2 play with this. When the first two Lords of Shadow games directly used Castlevania name, this sequel uses Akumajō Dracula (Demon's Castle Dracula) as noting for Dracula's involvement in the story.
- Frontier: Elite II, whose sequel dropped "Elite" completely and became Frontier: First Encounters. The series goes back to normal in Elite: Dangerous.
- Most of the Total War games use the series title "Total War" as a subtitle, as in Rome: Total War. Total War: Shogun 2 is the first game to not do this.
- Played straight with Ironsword: Wizards and Warriors II but averted with the third game.
- Inverted by No One Lives Forever 2: A Spy in H.A.R.M.'s Way, the sequel to The Operative: No One Lives Forever.
- Played straight or inverted (depending on how you look) by the Dark Forces Saga: the second game is alternatingly called Dark Forces II: Jedi Knight or Jedi Knight: Dark Forces II. The latter notation plays this trope straight, while the former leads to an inversion in the sequel, titled Jedi Knight II: Jedi Outcast.
- Arcania: A Gothic Tale, alternatively known as Arcania: Gothic 4.
- Enemy Territory: Quake Wars, part of the Enemy Territory series, set in the Quake universe.
- An adaptation rather than a sequel, but an example nonetheless. 007: From Russia with Love makes the movie it's based on its subtitle.
- Travis Strikes Again: No More Heroes, the second sequel to No More Heroes
- Senua's Saga: Hellblade II, an upcoming sequel to Hellblade: Senua's Sacrifice, is named that way.
- Super Mario Bros.:
- The third game in the Super Mario Land series is titled Wario Land: Super Mario Land 3, to signify the change of protagonist from Mario to Wario, and the subsequent start of the Wario Land series. This only applies to the overseas versions, though; in Japanese, the original title comes first, followed by the Wario Land subtitle.
- The full Japanese title of Super Mario World is Super Mario World: Super Mario Bros. 4.
- All the Super Mario Advance titles (except for the last, oddly).
- Anubis: Zone of the Enders, the Japanese title of Zone of the Enders: The 2nd Runner.
- The sequel to StarTropics is titled Zoda's Revenge: StarTropics II
- Kagero: Deception II. Averted with III, Trapt and IV.
- Hexen: Beyond Heretic
- Rainbow Islands:
- Rainbow Islands: The Story of Bubble Bobble 2
- Parasol Stars' subtitle is The Story of Bubble Bobble 3 or The Story of Rainbow Islands 2, depending on the version you have.
- The band-centric games in the Rock Band series feature this, with The Beatles: Rock Band and Green Day: Rock Band
- Ultima VIII is titled Pagan: Ultima VIII.
- The sequel to Another World is titled Heart of the Alien: Out of This World Part II (Out of This World being the U.S. title for Another World being later re-releases went back to the original European title).


Created by Rajendrasinh Parmar / @RAJENDRASINH_09
Docker provides an additional layer of abstraction and automation of operating-system-level virtualization on Windows and Linux.
A VM is essentially an emulation of a real computer that executes programs like a real computer.
VMs run on top of a physical machine using a “hypervisor”. A hypervisor, in turn, runs on either a host machine or on “bare-metal”.
Container provides operating-system-level virtualization by abstracting the “user space”
The one big difference between containers and VMs is that containers share the host system’s kernel with other containers.
Docker engine is the layer on which Docker runs
A Dockerfile is file where you write the instructions to build a Docker image
# Nginx
#
# VERSION 0.0.1
FROM ubuntu
LABEL Description="Description of docker image"
RUN apt-get update
RUN apt-get install -y nginx
Images are read-only templates that you build from a set of instructions written in your Dockerfile
Docker uses Union File Systems to build up an image
Benefits of Union File system
Documentation - https://docs.docker.com


{%load static%}
Our Team
Looks like bootstrap's CSS may be taking precedent over your custom CSS. To resolve this, try changing to 'border:0px !important', or be sure to load your custom css file before bootstrap's.
Mohammad Danish


Room:
Userlist:
Encrypted Text:
The room encryption is only as secure as the ROOM-ID!
Public key is RSA 2048bit key generated each server start.
Private Room key is generated with the RSA Public key.
Messages and Usernames are Encrypted with AES sha256.
Room:
Allow Links
Allow Special Chars
Userlist:
Encrypted Text:


@(error: Option[String] = None)
Click the button below to login.
This page is used to redirect failed login attempts and display any errors.
@error.map { message =>The error was: @message
}You can also go to a page that requires authentication or logout.


Class Creport
Cpdf
A PHP class to provide the basic functionality to create a pdf document without any requirement for additional modules.
Note that they companion class CezPdf can be used to extend this class and dramatically simplify the creation of documents.
IMPORTANT NOTE there is no warranty, implied or otherwise with this software.
LICENCE This code has been placed in the Public Domain for all to enjoy.
Package: Cpdf
Author: Wayne Munro<EMAIL_ADDRESS>Version: 009
Located at app/vendors/ezpdf/readme.php
Author: Wayne Munro<EMAIL_ADDRESS>Version: 009
Located at app/vendors/ezpdf/readme.php
public
|
|
public
|
|
public
|
public
array
|
$reportContents | array() |
$ez,
$ezPageCount,
$ezPages,
$y
|


Sorry, the KBase Narrative appears to be taking a long time to load. This could be due to a slow internet connection, or a problem with the Narrative itself. If this seems to be taking much longer than you expect, you can try holding the shift key and reloading this page.
Loading your Narrative document...
Loading your Narrative's data...
Loading available apps...
Connecting to Jupyter backend...
Fetching current job information...


Just for the hell of it, I have decided to send in a brief retrospective comparison of a few of the serotonin releasing research chems I have experimented with in the past. Most of these were known substances from reliable suppliers taken in precise, measured doses, but a few were street drugs or mystery pills that were only identified in retrospect.
Since MDMA is well known to many people, and my experiences were fairly typical, I will not give a detailed description, and will use MDMA as the basis of comparison. The first serotonin releaser I experimented with after MDMA was fenfluramine, chemically 3-(1,1,1 trifluoromethyl)-N-ethylamphetamine. This compound has been widely abused in the South African rave scene, and I can see why. Though it lacks the dopaminergic stimulation and euphoria of MDMA, it is a very potent and intoxicating (as well as cheap) drug that has several features that make it a good rave drug. It has even less psychedelic effect than MDMA (less likely to cause freakouts in unexperienced users), is much longer acting and considerably less dangerous. Though it does lack the empathogenic 'magic' of MDMA, it is quite anxiolytic, easing social interaction. Dosage is about 20-80 mg, though some recreational users have taken up to 400mg. Overall, the effect is simiar to that described for 4-MTA, calm yet stimulating.
The next serotonin releaser I experienced was PMA. This substance has a bad reputation, only partially deserved. The practice of passing this drug off as MDMA is reprehensible. PMA is an interesting substance in its own right, but it is not an MDMA substitute, is really not even similar except at threshold doses. The first time I tried PMA has been described in a previous report. The pills were being sold under the name Heaven in Louisiana, and were introduced as being PMA to my friend who bought them, though they were probably made for the purpose of misrepresentation. A few years later I got to try the mitsubishi PMA pills, which from net research might have contained
PMA plus traces of amphetamine and PMMA. I have never taken more than half of one of these, and have had several very pleasant experiences. Though the come-up is a little slower than MDMA, and the come-down a bit more drawn-out, overall the duration is similar. I find PMA to be more relaxing and less physically stimulating than MDMA, and much more euphoric, psychedelic and mentally interesting than fenfluramine.
When I finally got around to trying AMT, I was very surprised to find that it affected me very much like MDMA. Indeed, AMT is by far the best substitute for ecstacy that I have known. If anything, I prefer AMT, it gives me a very euphoric, empathogenic experience without hangover or overt psychedelic effects. Personally, I find AMT to be quite habit forming, more so than any other compound of this type that I have tried.
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


Toggl Report Viewer
v0.1.0 (Sep 8, 2016)
Allows you to view a toggl report in week view.
Usage
- Create an account or log into toggl.com
- Go to the app page
- Check your settings
- First day of the week: Monday
- (Unknown if the following settings are required)
- Date format: MM/DD/YYYY
- Time format: 24-hour
- Mouse over the "Reports" tab and select "Detailed" from the dropdown list
- Click the "Export" button and select "Download as CSV" from the dropdown list
- Use the file submission interface below to submit the csv file


We had to make 15 designs that would either light up or make a speaker work on the circuit board. Those are my 15 designs of the circuit board. The next rask was to saughter and we had to make a clock on a circuit board and saughter the back parts to the board.
Go Back to Index


Ok, we'll go deliver this crate like professionals, and then we'll go ride the bumper cars. Goodbye, friends. I never thought I'd die like this. But I always really hoped. I barely knew Philip, but as a clergyman I have no problem telling his most intimate friends all about him. Quite possible. We live long and are celebrated poopers. Leela, Bender, we're going grave robbing.