text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Collection of Large Number of Java Interview Questions!
;
The Jakarta Struts Interview Questions
...
Questions - Struts Interview Question -2 ... Interview Questions
Collection of large number related Question
Struts related Question Hi All,
I have a one question on validation framework for client side validation please help me on that.
suppose i don't want to put required=true in our JSP then what will happen.
what error will come
Which is the good website for struts 2 tutorials?
Which is the good website for struts 2 tutorials? Hi,
After... for learning Struts 2.
Suggest met the struts 2 tutorials good websites.
Thanks
Hi,
Rose India website is the good
struts collection problem in Mozilla
struts collection problem in Mozilla I used the to get list of records, if records are more than 15-20 then this is not seen properly with vertical scroll bar on Mozilla. Plz help me
Display Tag Related - Struts
IMP - Struts
IMP Hi...
I want to have the objective type questions(multiple choices) with answers for struts.
kindly send me the details
its urgent...: questions
struts questions what is purpose of inceptors in struts
Can you suggest any good book to learn struts
Can you suggest any good book to learn struts Can you suggest any good book to learn struts
java - Struts
of questiond they may ask.i have scjp and scwcd and good knowledge in struts,hibernate...java good morning sir.i have completed my mca at 2009.now i want...://
Thanks
Scrollbar problem with struts <layout:collection>
Scrollbar problem with struts How activate the vertical scrollbar in struts in mozilla firefox
Visibal Certical scrollbar with struts collection layout.
Visibal Certical scrollbar with struts collection layout. how to Visibal Vertical scroll bar with struts collection layout
thread related - Java Interview Questions
Garbage collection
collection is also called automatic memory management. In Java, it is good idea...Garbage collection why garbage collection? How it works?
Garbage collection is one of the most important features of Java. The purpose
Software Questions and Answers
related information in which users can ask, respond and share their questions... any software development related questions
ask it now. You can
also help... Server Faces Questions - The JSF is
another good framework to develop Rich
collection frame - Java Interview Questions
collection frame starting from jdk1.0 to jdk 1.5,what are the feature s added in each version of collection frame up to jdk1.5 . Hi friend,
(1)Generics:Provides compile-time (static) type safety
Internet and Web related questions for Web Master.
Internet and Web related questions for Web Master.
Explain the difference between the Internet and Web.
What are Web browsers? Explain the two main functions of a Web browser.
Write a note on the structure of a Web page.
What
Software Questions and Answers
related questions
ask it now. You can
also help the developers....
EJB - Discuss EJB related questions and see
the answers of the questions...
related questions.
Mobile Applications - Discuss how you can
Collection Framework - Java Interview Questions
Collection Framework While inserting an object which sould be prefered- ArrayList or LinkedList and why? Inserting an object with ArrayListArrayListExample.javaimport java.util.*;import java.io.*;public class
Struts
Struts Tell me good struts manual
Struts - Java Interview Questions
Struts Interview Questions I need Java Struts Interview Questions and examples
Struts Tutorials
found out:
1. The entry point to the all Struts related configuration...
Struts Tutorials
Struts Tutorials - Jakarta Struts Tutorial
This complete reference of Jakarta Struts shows you how to develop Struts
Interview Questions - Struts Interview Questions
Interview Questions - Struts Interview Questions...?
Answer: Struts is very rich framework and it provides very good... is centralized point of control for the web application. In struts framework
Struts
Struts How will you retrieve a collection of records from business logic to presentation logic in framework
java core collection - Java Interview Questions
java core collection why program in collection package throw two warnings(notes
core java collection package - Java Interview Questions
core java collection package why collection package doesnot handle... the Collections Framework. In the Collection Framework,
a collection represents... store in Collection and after wrapper the primitive data types store
java related - Java Beginners
java related Hello sir,
I want to learn java. But I don't know where to start from. I have purchased one java related book. But I am... training ?or can
it be studied by myself? Please suggest the good book & help me
struts - IDE Questions
Struts global forward example I need the global forward example in Struts
Web Related - JSP-Servlet
// insertmid.jsp
Thanks for posting questions
Struts Books
these questions. It is not an exhaustive reference on Apache Struts. Far from.... The book starts with an explanation of why Struts is a "good thing" and shows... (not as good but bigger) struts book and the two complement quite well. Go
Struts - JSP-Interview Questions
Struts Tag bean:define What is Tag bean:define in struts? Hello,The Tag <bean:define> is from Struts 1. So, I think you must be working on the Struts 1 project.Well here is the description of <bean
interview question - Servlet Interview Questions
interview question What is Servlet? Need interview questions on Java... according to your experience.And for collection of Java Servlet Interview Question you can visit here at
Struts Book - Popular Struts Books
and related simply to the architectural issues.
Struts in Action
Struts... to the Jakarta Struts Cookbook an amazing collection of code solutions to common...
Struts Book - Popular Struts Books
Programming Jakarta
Array to Collection
Array to Collection
In this example we are converting values of an array into
collection.
List interface is a member of the Java Collection
Framework
Struts with Eclipse - IDE Questions
Struts with Eclipse How to develope struts application in Websphere Rational Application Developer 7.0? AT First Check Your Eclipse contain Plugins for Websphere 7.0 or not?
ifcontain go preference/eclipse
struts - Java Interview Questions
server side validation in Struts How can i create a Server Side Validation in Struts? Hello,You can user server side validation to validate your form.But these almost all the browser is supporting java script. Might
Servlet Interview Questions
Servlet Interview Questions
Collection of large number of Servlet Interview Questions. These questions
are frequently asked in the Java Interviews.
Question: What
Collection
Collection What is the exact difference between lagacy classes and collection classes?
and Enumeration is possible on Collection classes
Collection to Array
Collection to Array
...; a collection into a array. In this example we creating an object of ArrayList,
adding...; interface is a member of the Java Collection
Framework and extends Collection
Struts - Struts
Struts Is Action class is thread safe in struts? if yes, how it is thread safe? if no, how to make it thread safe? Please give me with good...://
Thanks
Collection
Collection actually why do we need collections? means we can also store group of objects in relational data base and dbms also provides all the operatoins insert,delete,update,sort,search etc. then why collection
java - Servlet Interview Questions
java servlet interview questions Hi friend,
For Servlet interview Questions visit to :
Thanks
collection
Collection
Ask SOA Questions Online
Ask SOA Questions Online
... is a collection of services used for making communication with each other... business tasks, or services.
Ask questions pertaining to SOA
java questions - Java Interview Questions
the paths of java core questions and answers pdfs or interview questions pdfs or ebooks :)
please favor me best books of interviews questions for craking...://
Thanks
struts ebook
struts ebook please suggest a good ebook for struts>
Library Management in Struts. - Struts
Library Management in Struts. Hi can you give me the application related to Library Management using Struts Or Jsp
Session Related Interview Questions
Session Related Interview Questions
Question: What is a Session?
Answer: A Session refers to all the request that a single client makes to
a server. A session
JAVA - Struts
:// the above link
Common Interview Questions
Common Interview Questions
Every organization or institution requires good professionals... to answer a number of questions
in order to demonstrate their practical knowledge
Core Java Interview Questions!
Core Java Interview Questions
... () {
// Appropriate method-related code.
}
E.g. Synchronizing...; }
}
Question: What is Collection API?
Answer
A few questions related to developing a blog....can anyone please help me out??
A few questions related to developing a blog....can anyone please help me out?? I am trying to develop a project which is almost like a blog using jsp.I have a few questions....
Can anyone tell me if we can insert images
Jakarta Struts Interview Questions
Jakarta Struts Interview Questions
Q: What is Jakarta Struts Framework?
A: Jakarta Struts is open source implementation of MVC
(Model-View-Controller
java - Java Interview Questions
released as compared to J2SE 1.4. Sun have made more additions to make the Collection... any many more. Generics made the collection framework to store the objects of the related type.
Difference between Servlet?s context and config object
Ask Programming Questions and Discuss your Problems
Ask Programming Questions and Discuss your Problems
... and your love for Java and Java and Java related fields, Roseindia Technologies... all sorts of Java related problems round the clock.
Believe it. Roseindia has
java - Java Server Faces Questions
java Java Server Faces Quedtions Hi friend,
Thanks
How singleton in struts - Java Interview Questions
How singleton in struts Hi, How to implement singleton and threadsafe in struts .
same in jsp and servlet. Thanks Prakash
Important Interview Questions in Core Java
Important Interview Questions in Core Java
Core Java refers..., interviewer can ask any questions in the stock pile of core java questions and answers.
It is not possible to anyone to cover all essential core java - Java Interview Questions
java i want to java&j2ee interview questions.
Regards
Akhilesh Kumar Hi friend,
I am sending you a link. This link will help you.
Read for more information.
hint - Java Interview Questions
the following link:
Here you will get lot of interview questions and their answers.
Thanks thanks for your
Java: Garbage Collection
Java: Garbage Collection
Garbage collection is the process... in
delivered, shrink-wrapped, software are related to memory allocation/deallocation... running out of memory.
Automatic garbage collection
When there are no longer
Struts-It
Action class
other Struts-related classes like configuration...)
when related Struts configuration was changed.
Adds Struts capabilitiy... Struts-It
JSF Interview Questions
JSF Interview Questions
Collection of JSF (Java Server Faces) Interview Questions.
JSF Interview Question
JavaServer Faces (JSF) is an application - Java Interview Questions
Legacy Class:
Legacy Class is related to the synchronization.You can also called it synchronization class. It is the concept of the collection framework
interview questions - EJB
interview questions in Java Need interview questions in Java ...:// Questions: more thing first of all you should sound in programming language
Struts - Framework
/struts/". Its a very good site to learn struts.
You dont need to be expert...Struts Good day to you Sir/madam,
How can i start struts application ?
Before that what kind of things necessary
Difficult Interview Questions Page -11
. Good questions to ask are follow up questions to those asked of you during...
Difficult Interview Questions Page -11
... are you considering?
Answer: Keep your answer related to this company's field
java - Struts
/interviewquestions/design-patterns/design-patterns-interview-questions1.shtml.0 - Struts
Struts 2.0 Hi ALL,
I am getting following error when I am trying to use tag.
tag 'select', field 'list': The requested list key 'day' could not be resolved as a collection/array/map/enumeration/iterator type. Example
MVC - Struts
MVC Can any one help me in good design of an struts MVC....tell me any e-book so that i can download from site
STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS
STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS... are a Struts developer then you might have experienced the pain of writing huge number of Action classes for your project. The latest version of struts provides classes
Java faqs
This section contains collection of frequently asked questions(faqs) in interview or viva of Java
Struts Interview Questions
Struts Interview Questions
Question: Can I setup Apache Struts to use
multiple configuration files?
Answer: Yes Struts can use multiple configuration files.
Ask PHP Questions
questions at
Ask Questions
section.
You can ask any questions related...Ask PHP Questions
PHP Questions and Answers
Ask PHP Questions and get answers from
StringBuffer related.
StringBuffer related. how to make StringBuffer as immutable
collection overview and collection interface
collection overview and collection interface write the program for collection interface?
Please visit the following links:
struts 1.3
struts 1.3 my requirement is i have two drop downs.second drop down... all the data related to that item in database will come in next drop down menu using struts 1.3 but without using ajax
java - JSP-Interview Questions
java hi..
snd some JSP interview Q&A
and i wnt the JNI(Java Native Interface) concepts matrial
thanks
krishna Hi friend,
Read more information. | http://roseindia.net/tutorialhelp/comment/12086 | CC-MAIN-2014-15 | refinedweb | 2,160 | 58.58 |
CodePlexProject Hosting for Open Source Software
An unexpected error has occured.
There is an unsaved comment in progress. You will lose your changes if you continue. Are you sure you want to reopen the work item?
Closed
public abstract class Entity { ... }
public class Cat : Entity { ... }
public class Dog : Entity { ... }
JsonSerializer serializer = new JsonSerializer();
//I would expect $type for the Cat to be written in this case:
serializer.Serialize{Entity}(new Cat());
//But not in this case:
serializer.Serialize{Cat}(new Cat());
jonstelly
wrote Feb 8, 2013 at 4:16 PM
wrote Feb 22, 2013 at 1:47 AM
wrote Feb 24, 2013 at 3:38 AM
wrote Mar 3, 2013 at 12:58 AM
jonstelly
wrote Mar 3, 2013 at 12:58 AM
JamesNK
wrote Mar 3, 2013 at 12:58 AM
wrote Mar 3, 2013 at 12:59 AM
wrote Mar 24, 2013 at 1:11 AM
itavantiq
wrote May 10, 2013 at 9:40 AM
JamesNK
wrote May 10, 2013 at 10:50 PM
wrote May 16, 2013 at 12:36 PM
Keyboard shortcuts are available for this page. | http://json.codeplex.com/workitem/23891 | CC-MAIN-2017-22 | refinedweb | 181 | 71.75 |
Batea is a context-driven network device ranking framework based on the anomaly detection family of machine learning algorithms. The goal of Batea is to allow security teams to automatically filter interesting network assets in large networks using nmap scan reports. We call those Gold Nuggets.
For more information about Gold Nuggeting and the science behind Batea, check out our whitepaper here
You can try Batea on your nmap scan data without downloading the software, using Batea Live:
How it works
Batea works by constructing a numerical representation (numpy) of all devices from your nmap reports (XML) and then applying anomaly detection methods to uncover the gold nuggets. It is easily extendable by adding specific features, or interesting characteristics, to the numerical representation of the network elements.
The numerical representation of the network is constructed using features, which are inspired by the expertise of the security community. The features act as elements of intuition, and the unsupervised anomaly detection methods allow the context of the network asset, or the total description of the network, to be used as the central building block of the ranking algorithm. The exact algorithm used is Isolation Forest ()
Machine learning models are the heart of Batea. Models are algorithms trained on the whole dataset and used to predict a score on the same (and other) data points (network devices). Batea also allows for model persistence. That is, you can re-use pretrained models and export models trained on large datasets for further use.
Usage
# Complete info$ sudo nmap -A 192.168.0.0/16 -oX output.xml# Partial info$ sudo nmap -O -sV 192.168.0.0/16 -oX output.xml$ batea -v output.xml
Installation
$ git clone [email protected]:delvelabs/batea.git$ cd batea$ python3 setup.py sdist$ pip3 install -r requirements.txt$ pip3 install -e .
Developers Installation
$ git clone [email protected]:delvelabs/batea.git$ cd batea$ python3 -m venv batea/$ source batea/bin/activate$ python3 setup.py sdist$ pip3 install -r requirements-dev.txt$ pip3 install -e .$ pytest
Example usage
# simple use (output top 5 gold nuggets with default format)$ batea nmap_report.xml# Output top 3$ batea -n 3 nmap_report.xml# Output all assets$ batea -A nmap_report.xml# Using multiple input files$ batea -A nmap_report1.xml nmap_report2.xml# Using wildcards (default xsl)$ batea ./nmap*.xml$ batea -f csv ./assets*.csv# You can use batea on pretrained models and export trained models.# Training, output and dumping model for persistence$ batea -D mymodel.batea nmap_report.xml# Using pretrained model$ batea -L mymodel.batea nmap_report.xml# Using preformatted csv along with xml files$ batea -x nmap_report.xml -c portscan_data.csv# Adjust verbosity$ batea -vv nmap_report.xml
How to add a feature
Batea works by assigning numerical features to every host in the report (or series of report). Hosts are python objects derived from the nmap report. They consist of the following list of attributes:
[ipv4, hostname, os_info, ports] where ports is a list of ports objects. Each port has the following list of attributes :
[port, protocol, state, service, software, version, cpe, scripts], all defaulting to
None.
Features are objects inherited from the
FeatureBase class that instantiate a specific
_transform method. This method always takes the list of all hosts as input and returns a lambda function that maps each host to a numpy column of numeric values (host order is conserved). The column is then appended to the matrix representation of the report. Features must output correct numerical values (floats or integers) and nothing else.
Most feature transformations are implemented using a simple lambda function. Just make sure to default a numeric value to every host for model compatibility.
Ex:
class CustomInterestingPorts(FeatureBase): def __init__(self): super().__init__(name="some_custom_interesting_ports") def _transform(self, hosts): """This method takes a list of hosts and returns a function that counts the number of host ports member from a predefined list of "interesting" ports, defaulting to 0. Parameters ---------- hosts : list The list of all hosts Returns ------- f : lambda function Counts the number of ports in the defined list. """ member_ports = [21, 22, 25, 8080, 8081, 1234] f = lambda host: len([port for port in host.ports if port.port in member_ports]) return f
You can then add the feature to the report by using the
NmapReport.add_feature method in
batea/__init__.py
from .features.basic_features import CustomInterestingPortsdef build_report(): report = NmapReport() #[...] report.add_feature(CustomInterestingPorts()) return report
Using precomputed tabular data (CSV)
It is possible to use preprocessed data to train the model or for prediction. The data has to be indexed by
(ipv4, port) with one unique combination per row. The type of data should be close to what you expect from the XML version of an nmap report. A column has to use one of the following names, but you don't have to use all of them. The parser defaults to null values if a column is absent.
'ipv4', 'hostname', 'os_name', 'port', 'state', 'protocol', 'service', 'software_banner', 'version', 'cpe', 'other_info'
Example:
ipv4,hostname,os_name,port,state,protocol,service,software_banner10.251.53.100,internal.delvesecurity.com,Linux,110,open,tcp,rpcbind,"program version port/proto service100000 2,3,4 111/tcp rpcbind100000 2,3,4 "10.251.53.100,internal.delvesecurity.com,Linux,111,open,tcp,rpcbind,10.251.53.188,serious.delvesecurity.com,Linux,6000,open,tcp,X11,"X11Probe: CentOS"
Outputing numerical representation
For the data scientist in you, or just for fun and profit, you can output the numerical matrix along with the score column instead of the regular output. This can be useful for further data analysis and debug purpose.
$ batea -oM network_matrix nmap_report.xml | https://amp.kitploit.com/2021/01/batea-ai-based-context-driven-network.html | CC-MAIN-2021-17 | refinedweb | 926 | 50.02 |
What are words with double b?
rubble rabble scrabble scribble hobble bubble ribbon babble bobble hebblewhite bobbin
rabble rubble wobble wibble pebble pobble (with no toes) nobble nibble gobble dabble yabby cabby cubby tubby hubby bubby stubby nubbly
rubber stubble Ebb chubby
How do you play the double b flat on flute?
A double b flat is also an A
What s words have a double b in them?
subbuteo sabbatical Sabbath sobbing
Are there any words using double b?
bubble In Italian - repubblica
Can any note in an octave have an enharmonic - such as G-sharp and A-flat B and C-flat and A and B-double-flat etc?
I am guessing so... I've seen something like a key signature having a B-flat, and somewhere in the piece there is a flat in front of a B, so it would be a B-double-flat. If double flats are allowed,then it would be C,B-sharp;C-sharp,D-flat;D, E-double-flat; D-sharp, E-flat; E, F-flat;F,G-double-flat;F-sharp,G-flat;G,A-double-flat;G-sharp,A-flat;A,B-double-flat;and B,C-double-flat.
How can you write an algorithm to read two numbers then display the smallest?
Algorithm smallest Is:- Input: two values, a and b Output: smallest value of a and b if a<b then return a else return b In C programming: long double smallest (long double a, long double b) { return a<b?a:b; }
How do you Calculate the average of two numbers then return the average in c plus plus?
double getAverage(const double a, const double b) { return (a + b)/2.0;}
What is the enharmonic of A double sharp?
A double sharp is the enharmonic of B nature
What is the value of a Fox Model B double barrel with double triggers?
i wood like to know the value of a Fox Model B
How do you write a program to find the area of triangle?
To find the area of a triangle you first need to know the base and height: double area_of_triangle (double base, double height) { return base * height / 2; } If we don't know the height, then we need to know the length of any two sides and the included angle. Using standard notation where the sides are labelled a, b and c and their opposing angles as A, B and C, given sides a…
How do you find the general equation of cone using C language?
If you mean the "general equation of a cone" to be the elliptical cone equation: z = √( (x/a)2 + (y/b)2 ) ... then the function in C to compute this given the proper variables is: double genEqCone(const double x, const double y, const double a, const double b) { const double X_A = (x/a); const double Y_B = (y/b); return sqrt((X_A * X_A) + (Y_B * Y_B)); }
What does double d mean?
Double d means twice b (2) d as in dodder.
Can you compare NaN values?
Yes using the equals method. Example: Double a = new Double(Double.NaN); Double b = new Double(Double.NaN); if( a.equals(b) ) System.out.println("True"); else System.out.println("False"); If you execute the above code snippet you will see "True" in the console. If you try the "==" operator to compare the 2 values a and b you will get only false
What actors and actresses appeared in Double B-side - 2013?
The cast of Double B-side - 2013 includes: Chelsea Schuchman as Frankie Simone
How to calculate sum of two complex number in c plus plus?
#include<iostream> #include<complex> int main() { std::complex<double> a(1,0); std::complex<double> b(3,1); std::complex<double> c = a + b; }
If two fair dice are rolled what is the probability of rolling a double given that the sum was 11?
Let A = rolling a double Let B = sum is 11 P(A)=6/36=1/6 P(B)=2/36=1/18 since (5,6) and (6,5) produce a sum of 11. We want to find P(A/B)= P(A & B) / P(B) = 0 / P(B)=0 P(A & B) represent the event getting a double and the sum being 11.
Can i get a Java program for quadratic formula?
import java.util.*; public class quadratic { public static void main(String[] args) { Scanner input = new Scanner(System.in); String equation = "( ax^2 + bx + c = 0 1 )"; System.out.println("The equation is " + equation); System.out.println("Please enter the values of coefficients a, b, c, separated by spaces"); System.out.println("a = "); double a = input.nextDouble(); System.out.println("b = "); double b = input.nextDouble(); System.out.println("c = "); double c = input.nextDouble(); System.out.println(); double discriminant = Math.pow(b,2)…
What interval is c double sharp to b?
diminished 7th
Write a java program to demonstrate the method overloading for sum function?
Below is an example of method overloading which returns the sum of two number types. Each method performs the calculation and returns a value in a different type. int sum(final int a, final int b) { return a + b; } long sum(final long a, final long b) { return a + b; } float sum(final float a, final float b) { return a + b; } double sum(final double a, final double b) {…
What is an example of a double displacement reaction?
The preparation of hydrogen peroxide is a double displacement reaction. ---- Ab+c->ac+b
Program in c to find the roots of a quadratic equation using switch statement?"); scanf("%d", &option); printf("************* *************************\n"); /* Get a, b, and c from user */ printf("\na = "); scanf("%lf", &a); printf("b = "); scanf("%lf", &b); printf("c…
What are All the enharmonics on the piano?
Enharmonics is the name for a pitch that is "spelled" three different ways. # C=B sharp, D double flat # D flat= C sharp, B double sharp....
What has the author John B Geijsbeek written?
John B. Geijsbeek has written: 'Ancient double-entry bookkeeping'
What nicknames does Blair Barnette go by?
Blair Barnette goes by B.B., Ave B. Blair, and Double B.
What is the enharmonic equivalent of b flat?
A-sharp, C-double-flat or in some northern European Countries, B.
Is Hepatitis B RNA or DNA?
Hepatitis B is an infectious condition of the liver. Hepatitis B has a double stranded DNA that belongs to the hepadnavirus family.
4 s on a d b?
4 Strings on a Double Bass.
How to write a c plus plus program to calculate the square of number using a function?
... double squareOf_Number(double Number) { return (Number*Number); } ... int main() { ... double Number = 0; ... printf("Enter a number: "); cin >> Number; ... printf("Square of %f is %f\n", Number, squareOf_Number(Number)); ... } Or you can include #include <math.h> and use the function pow(double a, double b) which returns a^b.
What two syllable words have double b in them?
Some choices: cabbage, rubble, bubble, babble, wobble, clobber, pebble, stubble, gibbon, fibber
Double coincidence of demand?
For example; the supplier of good A wants good B and the supplier of good B wants good A.
Program to find the roots of quadratic equation in c using switch case?
Pls try the following program. "); /* Get option from user */ scanf("%d", &option); printf("************* *************************\n"); /* Get a, b, and c from user */…
What are the Words to Doublemint Gum jingle?
Double your pleasure Double your fun With Double mint Double good Double Mint Gum
Two methods cannot have the same name in Java?
Multiple methods with the same name is called method overloading. The way to do this is to have the different methods accept different parameters. Examples: Adding two values and returning the result. Let's use different methods for adding various numeric primitives. public static int add(int a, int b) { return a + b; } public static short add(short a, short b) { return a + b; } public static long add(long a, long b) {…
Program to find the sum of harmonic series?
Let's assume that you want the sum of the general harmonic series: sum(n=0,inf): 1/(an+b) Since we know that the harmonic series will converge to infinity, we'll also assume that you want the sum from 0 to n. double genHarmonic(const double n, const double a, const double b) { double sum = 0.0; // perform calculations int k; for(k = 0; k <= n; ++k) { sum += 1.0 / (a * k + b); }…
What is 4 s 0 a d b?
4 Strings on a Double Bass
How do you forge on epic pet wars?
press a b x double que
Why do we need type casting in programming?
Becuase, sometimes data is in a form that is unrecognizable to the program. Example: int a = 2; int b = 3; double c = a / b; We cast c as a double. if it was not, then the data would not have a decimal value.
Why is there no B sharp or C flat in music?
B# and Cb are used in music, just not very much. Most keys do not use either notes, but some do, and they can be used as accidentals. In this way they are similar to double-sharps and double-flats.
How do we tuple initialize a class or structure?
Consider the following structure: struct X { int a; double b; // ... }; Here we could initialise with a std::tuple<int, double>. To achieve this we simply define a constructor that accepts the required tuple: #include<tuple> struct X { int a; double b; X::X (std::tuple<int, double>& t): a {std::get<0>(t)}, b {std::get<1>(t)} {} // ... }; Note that any constructor that has one argument is known as a conversion constructor, in this case converting from tuple…
Write a c plus plus program that prints all reals olutions to the quadratic equation?
#include <iostream> #include <math.h> using std::cin; using std::cout; int main() { cout << endl << "This program find real roots of a*x*x + b*x + c = 0"; double a = 0.0; cout << endl << "Enter a: "; cin >> a; double b = 0.0; cout << endl << "Enter b: "; cin >> b; double c = 0.0; cout << endl << "Enter c: "; cin >> c; double det = b*b…
What is the lowest string on a double bass?
The lowest string on a four string double bass is an E string. If you have a fairly rare five string double bass then the lowest fifth string is a B string.
Did the song Daytripper have a B side?
We Can Work It Out Technically, there is no 'B-side' this single by the Beatled was a 'Double A-side' (Ah those were the days)
What type of chemical reactions are double replacement reactions?
A double replacement reaction is a chemical reaction where two reactant ionic compounds exchange ions to form two new product compounds with the same ions. Double replacement reactions take the form: A+B- + C+D- → A+D- + C+B-
Double h words?
Withhold has a double h.
What does it mean when a sharp and a flat are in front of the same note?
Offhand, I would say that is a misprint. However, a natural and flat means to return to a normal flat note after a double-flat. For example, suppose you are in a key with B-flat in the key signature, but you have an E-flat diminished chord, which includes B-double-flat. After that you have a regular B-flat. The natural cancels the double-flat, and the single flat returns to the usual note. After a double-sharp, a natural and…
What has the author Rodney B Taylor written?
Rodney B. Taylor has written: 'Jamestown' -- subject(s): Biography, Buildings, structures, Historic buildings, History, Pictorial works 'Double taxation relief' -- subject(s): Double taxation
What words start with double letters?
Aardvark and eel are words. They begin with double letters.
What Words that have bee in them?
If you mean b double e then Been Beel (as in Louis Beel) Beem (acronym for Best Evidence in Emergency Medicine) Beehive Beegees and Bees
What is the enharmonic of c flat?
The enharmonic equivalent of C flat is B natural. N.B - B natural can also be called A double-sharp.
What brass instrument play the lowest note in the orchestra?
Double B-flat Tuba
What would your weight b if earths mass were to be doubled?
Your weight would be double what it is now. | https://www.answers.com/Q/What_are_words_with_double_b | CC-MAIN-2019-30 | refinedweb | 2,083 | 65.22 |
==============================================================
To stay up-to-date with our latest releases and news, follow us on Twitter: @outworkers.
Named after the Greek God of Dreams, morpheus is a reactive type-safe Scala DSL for MySQL, Postgres, MSSQL, MariaDB, Oracle and Sybase. "Morpheus" morphs into the SQL implementation of your desire, so instead of implementing a Slick like leaking abstraction, we have instead opted to implement an entire engine for each of the mainstream SQL databases and unify them to offer a consistent fluent DSL experience.
With the single switch of a dependency and an import, morpheus will perform a full feature swap from MySQL to OracleSQL for example. It doesn't have a query compiler, instead it entirely mimics the functionality the database has, so if a method exists in OracleSQL but not in MySQL, you will get a compile time error if you attempt to use it.
There are no renames, no new things to learn, no new features or abstractions like in Slick, just dear old SQL as you've grown to love i or hate it.
Using morpheusUsing morpheus
The current version is:
val morpheusVersion =
.
Morpheus is actively and avidly developed. It is not yet production ready, so trial at your own risk.
The stable release is always available on Maven Central and will be indicated by the badge at the top of this readme. The Maven Central badge is pointing at the latest version
Intermediary releases are available through our managed Bintray repository available at
Resolver.bintrayRepo("outworkers", "oss-releases"). The latest version available on our Bintray repository is indicated by the Bintray badge at the top of this readme.
Table of contents
- Design philosophy
- Integrating Morpheus
Supported databases and documentation
Design philosophy
You're probably wondering how Morpheus fairs compared to the more established players in the Scala SQL market and why we set out to do something new in the first place. To sum it up, we believe Slick is an excellent tool but we do not believe you should learn about our abstractions to get things done. A DSL should auto-magically encode the same syntax and the logic as the tool it's designed for.
Instead of learning about primitives and rules we thought of to abstract away discrepancies between the various SQL implementations, Morpheus features a unique approach, what we call the auto-magical flip. Although at this point in time only MySQL is supported, Morpheus is designed to give you an "all-you-can-eat" buffet through a single import.
As follows:
import com.outworkers.morpheus.mysql._.
And done, you can now define tables, query and so on. Say you have something like this:
Recipes.select.distinctRow.where(_.name eqs "test").
DISTINCTROW doesn't exist in the Postgres
SELECT statement syntax, but it's a standard thing as far as MySQL is concerned.
Here's how Morpheus operates:
If you change the top level import to:
com.outworkers.morpheus.postgres._ and you try to compile the same
distinctRow query. But there will be none. The method will simply not exist. Morpheus has now auto-magically performed a full feature swap, changed communication protocol and all underlying settings, and all you get now is Postgres features.
How? Quite a lot of fun magic under the hood, have a look throughout our decently documented codebase for more information. The beauty of it is that you don't have to care. Slick makes it easy to move from one SQL database to the other with less code changes, but if you're well set on a database you already know and love, it may be counter productive to have to learn about a framework when you could use Morpheus and all you need is IDE auto-completes to get lightning fast development productivity.
Oh, and did we mention it's entirely asynchronous and reactive? No JDBC.
Integrating Morpheus
Morpheus is designed to give you an all-you-can eat buffet through a single import, so all you really have to do is to pick the module corresponding to the database you want to use. At this point in time only MySQL is supported.
If you are using MySQL, you would simply use the following:
libraryDependencies ++= Seq( "com.outworkers" %% "morpheus-mysql" % morpheusVersion )
And then you can:
import com.outworkers.morpheus.mysql._, which will give you the full set of MySQL methods and features without any overlaps or unsupported operations. Morpheus guarantees you can almost never write an invalid SQL query unless you try really really hard.
Available modulesAvailable modules
The full list of available modules is:
libraryDependencies ++= Seq( "com.outworkers" %% "morpheus-dsl" % morpheusVersion, "com.outworkers" %% "morpheus-mysql" % morpheusVersion, "com.outworkers" %% "morpheus-postgres" % morpheusVersion )
Contributors
Morpheus was developed by us from scratch in an attempt to evolve the SQL tooling in the Scala ecosystem to the new level and bring in fully reactive database access while preserving the complete SQL syntax you are used to.
- Flavian Alexandru @alexflav23
- Benjamin Edwards @benjumanji
Commercial support
We, the people behind phantom run a software development house specialised in Scala and NoSQL. If you are after enterprise grade training or support for using phantom, Outworkers is here to help!
We offer a comprehensive range of elite Scala development services, including but not limited to:
- Software development
- Remote Scala contractors for hire
- Advanced Scala and Morpheus training
We are big fans of open source and we will open source every project we can! To read more about our OSS efforts, click here. | https://index.scala-lang.org/outworkers/morpheus/morpheus-dsl/0.4.1?target=_2.11 | CC-MAIN-2019-13 | refinedweb | 914 | 51.99 |
WTL contains many wrappers and utility classes that haven't gotten full coverage yet in this series, such as
CString and
CDC. WTL has a nice system for wrapping GDI objects, some useful functions
for loading resources, and classes that make it easier to use some of the Win32 common dialogs. Here in Part IX,
I'll cover some of the most commonly-used utility classes.
This article discusses four categories of features:
WTL takes a rather different approach to its GDI wrappers than MFC. WTL's approach is to have one template class
for each type of GDI object, each template having one
bool parameter called
t_bManaged.
This parameter controls whether an instance of that class "manages" (or owns) the wrapped GDI object.
If
t_bManaged is
false, the C++ object does not manage the lifetime of the GDI object;
the C++ object is a simple wrapper around the GDI object handle. If
t_bManaged is
true,
two things change:
DeleteObject()on the wrapped handle, if it is not NULL.
Attach()calls
DeleteObject()on the wrapped handle, if it is not NULL, before attaching the C++ object to the new handle.
This design is in line with the ATL window classes, where
CWindow is a plain wrapper around an
HWND, and
CWindowImpl manages the lifetime of a window.
The GDI wrapper classes are defined in atlgdi.h, with the exception of
CMenuT, which is
in atluser.h. You don't have to include these headers yourself, because atlapp.h always includes
them for you. Each class also has typedefs with easier-to-remember names:
I like this approach, compared to MFC which passes around pointers to objects. You never have to worry about
getting a NULL pointer (the wrapped handle might be NULL, but that's another matter), nor do you have any special
cases where you get a temporary object that you can't hang on to for more than one function call. It is also very
cheap to create an instance of any of these classes since they only have one member variable, the handle being
wrapped. As is the case with
CWindow, there is no problem passing a wrapper class object between threads,
since WTL keeps no thread-specific maps like MFC.
There are additional device context wrapper classes for use in special drawing scenarios:
CClientDC: Wraps calls to
GetDC()and
ReleaseDC(), used to draw in a window's client area
CWindowDC: Wraps calls to
GetWindowDC()and
ReleaseDC(), used to draw anywhere in a window.
CPaintDC: Wraps calls to
BeginPaint()and
EndPaint(), used in a
WM_PAINThandler.
Each of these classes takes a
HWND in the constructor, and behaves like the MFC classes of the
same name. All three are derived from
CDC, so these classes all manage their device contexts.
The GDI wrapper classes follow the same design. To be concise, I'll cover the methods in
CBitmapT
here, but the other classes work similarly.
CBitmapThas an
HBITMAPmember called
m_hBitmap.
HBITMAP, which defaults to NULL.
m_hBitmapis initialized to this value.
t_bManagedis true, and
m_hBitmapis not NULL, then the destructor calls
DeleteObject()to destroy the bitmap.
Attach()and
operator =
HBITMAPhandle. If
t_bManagedis
true, and
m_hBitmapis not NULL, these methods call
DeleteObject()to destroy the bitmap that the
CBitmapTobject is managing. Then they set
m_hBitmapto the
HBITMAPthat was passed in as the parameter.
Detach()
Detach()sets
m_hBitmapto NULL, then returns the value that was in
m_hBitmap. After
Detach()returns, the
CBitmapTobject is no longer associated with a GDI bitmap.
CBitmapThas wrappers for the Win32 APIs that create a bitmap:
LoadBitmap(),
LoadMappedBitmap(),
CreateBitmap(),
CreateBitmapIndirect(),
CreateCompatibleBitmap(),
CreateDiscardableBitmap(),
CreateDIBitmap(), and
CreateDIBSection(). These methods will assert if
m_hBitmapis not NULL; to reuse a
CBitmapTobject for a different GDI bitmap, call
DeleteObject()or
Detach()first.
DeleteObject()
DeleteObject()destroys the GDI bitmap object, then sets
m_hBitmapto NULL. This method should be called only if
m_hBitmapis not NULL; it will assert otherwise.
IsNull()
IsNull()returns
trueif
m_hBitmapis NULL, or
falseotherwise. Use this method to test whether the
CBitmapTobject is currently associated with a GDI bitmap.
operator HBITMAP
m_hBitmap, and lets you pass a
CBitmapTobject to a function or Win32 API that takes an
HBITMAPhandle. This converter is also called when a
CBitmapTis evaluated in a boolean context, and evaluates to the logical opposite of
IsNull(). Therefore, these two if statements are equivalent:
CBitmapHandle bmp = /* some HBITMAP value */; if ( !bmp.IsNull() ) { do something... } if ( bmp ) { do something more... }
GetObject()wrappers
CBitmapThas a type-safe wrapper for the Win32 API
GetObject():
GetBitmap(). There are two overloads: one that takes a
LOGBITMAP*and calls straight through to
GetObject(); and one that takes a
LOGBITMAP&and returns a
boolindicating success. The latter version is the easier one to use. For example:
CBitmapHandle bmp2 = /* some HBITMAP value */; LOGBITMAP logbmp = {0}; bool bSuccess; if ( bmp2 ) bSuccess = bmp2.GetLogBitmap ( logbmp );
CBitmapThas wrappers for Win32 APIs that take an
HBITMAPparameter:
GetBitmapBits(),
SetBitmapBits(),
GetBitmapDimension(),
SetBitmapDimension(),
GetDIBits(), and
SetDIBits(). These methods will assert if
m_hBitmapis NULL.
CBitmapThas two useful methods that operate on
m_hBitmap:
LoadOEMBitmap()and
GetSize().
CDCT is a bit different from the other classes, so I'll cover the differences separately.
The method to destroy a DC is called
DeleteDC() instead of
DeleteObject().
One aspect of MFC's
CDC that is prone to errors is selecting objects into a DC. MFC's
CDC
has several overloaded
SelectObject() functions that each take a pointer to a different kind of GDI
wrapper class (
CPen*,
CBitmap*, and so on). If you pass a C++ object to
SelectObject(),
instead of a pointer to a C++ object, the code ends up calling the undocumented overload that accepts an
HGDIOBJ
handle, and this is what causes the problems.
WTL's
CDCT takes a better approach, and has several select methods, each of which works with just
one type of GDI object:
HPEN SelectPen(HPEN hPen) HBRUSH SelectBrush(HBRUSH hBrush) HFONT SelectFont(HFONT hFont) HBITMAP SelectBitmap(HBITMAP hBitmap) int SelectRgn(HRGN hRgn) HPALETTE SelectPalette(HPALETTE hPalette, BOOL bForceBackground)
In debug builds, each method asserts that
m_hDC is not NULL, and that the parameter is a handle
to the correct type of GDI object. They then call the
SelectObject() API and cast the
SelectObject()
return value to the appropriate type.
There are also helper methods that call
GetStockObject() with a given constant, and then select
the object into the DC:
HPEN SelectStockPen(int nPen) HBRUSH SelectStockBrush(int nBrush) HFONT SelectStockFont(int nFont) HPALETTE SelectStockPalette(int nPalette, BOOL bForceBackground)
Fewer constructors: The wrappers classes lack constructors that create a new GDI object. For example,
MFC's
CBrush has constructors that create a solid or patterned brush. With the WTL classes, you must
use a method to create the GDI object.
Selecting objects into a DC is done better: See the Using CDCT section above.
No
m_hAttribDC: WTL's
CDCT does not have a
m_hAttribDC
member.
Minor parameter differences in some methods: For example,
CDC::GetWindowExt() returns a
CSize object in MFC; while in WTL the method returns a
bool, and the size is returned
via an output parameter.
WTL has several global functions that are helpful shortcuts for loading various types of resources. We'll need
to know about one utility class before getting on to the functions:
_U_STRINGorID.
In Win32, most types of resources can be identified by a string (
LPCTSTR) or an unsigned integer
(
UINT). APIs that take a resource identifier take an
LPCTSTR parameter, and if you want
to pass a
UINT, you need to use the
MAKEINTRESOURCE macro to convert it to an
LPCTSTR.
_U_STRINGorID, when used as the type of a resource identifier parameter, hides this distinction so
that the caller can pass either a
UINT or
LPCTSTR directly. The function can then use
a
CString to load the string if necessary:
void somefunc ( _U_STRINGorID id ) { CString str ( id.m_lpstr ); // use str... } void func2() { // Call 1 - using a string literal somefunc ( _T("Willow Rosenberg") ); // Call 2 - using a string resource ID somefunc ( IDS_BUFFY_SUMMERS ); }
This works because the
CString constructor that takes an
LPCTSTR checks whether the
parameter is actually a string ID. If so, the string is loaded from the string table and assigned to the
CString.
In VC 6,
_U_STRINGorID is provided by WTL in atlwinx.h. In VC 7,
_U_STRINGorID
is part of ATL. Either way, the class definition will always be included for you by other ATL/WTL headers.
The functions in this section load a resource from the resource instance handle kept in the
_Module
global variable (in VC 6) or the
_AtlBaseModule global (in VC 7). Using other modules for resources
is beyond the scope of this article, so I will not be covering it here. Just remember that by default, the functions
look in the EXE or DLL that the code is running in. The functions do nothing more than call through to APIs, their
utility is in the simplified resource identifier handling provided by
_U_STRINGorID.
HACCEL AtlLoadAccelerators(_U_STRINGorID table)
Calls through to
LoadAccelerators().HMENU AtlLoadMenu(_U_STRINGorID menu)
Calls through to
LoadMenu().HBITMAP AtlLoadBitmap(_U_STRINGorID bitmap)
Calls through to
LoadBitmap().HCURSOR AtlLoadCursor(_U_STRINGorID cursor)
Calls through to
LoadCursor().HICON AtlLoadIcon(_U_STRINGorID icon)
Calls through to
LoadIcon(). Note that this function - like
LoadIcon()- can only load 32x32 icons.int AtlLoadString(UINT uID, LPTSTR lpBuffer, int nBufferMax) bool AtlLoadString(UINT uID, BSTR& bstrText)
Call through to
LoadString(). The string can be returned in either a
TCHARbuffer, or assigned to a
BSTR, depending on which overload you use. Note that these functions only accept a
UINTas the resource ID, because string table entries cannot have string identifiers.
This group of functions wrap calls to
LoadImage(), and take additional parameters that are passed
on to
LoadImage().
HBITMAP AtlLoadBitmapImage( _U_STRINGorID bitmap, UINT fuLoad = LR_DEFAULTCOLOR)
Calls
LoadImage()with the
IMAGE_BITMAPtype, passing along the
fuLoadflags.HCURSOR AtlLoadCursorImage( _U_STRINGorID cursor, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0)
Calls
LoadImage()with the
IMAGE_CURSORtype, passing along the
fuLoadflags. Since one cursor resource can contain several different-sized cursors, you can pass dimensions for the
cxDesiredand
cyDesiredparameters to load a cursor with a particular size.HICON AtlLoadIconImage( _U_STRINGorID icon, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0)
Calls
LoadImage()with the
IMAGE_ICONtype, passing along the
fuLoadflags. The
cxDesiredand
cyDesiredparameters are used as in
AtlLoadCursorImage().
This group of functions wrap calls to load system-defined resources (for example, the standard hand cursor).
Some of these resource IDs (mostly the ones for bitmaps) are not included by default; you need to
#define
the
OEMRESOURCE symbol in your stdafx.h in order to reference them.
HBITMAP AtlLoadSysBitmap(LPCTSTR lpBitmapName)
Calls
LoadBitmap()with a NULL resource handle. Use this function to load any of the
OBM_*bitmaps listed in the
LoadBitmap()documentation.HCURSOR AtlLoadSysCursor(LPCTSTR lpCursorName)
Calls
LoadCursor()with a NULL resource handle. Use this function to load any of the
IDC_*cursors listed in the
LoadCursor()documentation.HICON AtlLoadSysIcon(LPCTSTR lpIconName)
Calls
LoadIcon()with a NULL resource handle. Use this function to load any of the
IDI_*icons listed in the
LoadIcon()documentation. Note that this function - like
LoadIcon()- can only load 32x32 icons.HBITMAP AtlLoadSysBitmapImage( WORD wBitmapID, UINT fuLoad = LR_DEFAULTCOLOR)
Calls
LoadImage()with a NULL resource handle and the
IMAGE_BITMAPtype. You can use this function to load the same bitmaps as
AtlLoadSysBitmap().HCURSOR AtlLoadSysCursorImage( _U_STRINGorID cursor, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0)
Calls
LoadImage()with a NULL resource handle and the
IMAGE_CURSORtype. You can use this function to load the same cursors as
AtlLoadSysCursor().HICON AtlLoadSysIconImage( _U_STRINGorID icon, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0)
Calls
LoadImage()with a NULL resource handle and the
IMAGE_ICONtype. You can use this function to load the same icons as
AtlLoadSysIcon(), but you can also specify a different size such as 16x16.
Finally, this group of functions are type-safe wrappers for the
GetStockObject() API.
HPEN AtlGetStockPen(int nPen) HBRUSH AtlGetStockBrush(int nBrush) HFONT AtlGetStockFont(int nFont) HPALETTE AtlGetStockPalette(int nPalette)
Each function checks that you're passing in a sensible value (e.g.,
AtlGetStockPen() only accepts
WHITE_PEN,
BLACK_PEN, and so on), then calls through to
GetStockObject().
WTL has classes that make using the Win32 common dialogs easier. Each class handles messages and callbacks that
the common dialog sends, and in turn calls overridable functions. This is the same design used in property sheets,
where you write handlers for individual property sheet notifications (e.g.,
OnWizardNext() for handling
PSN_WIZNEXT) that are called by
CPropertyPageImpl when necessary.
WTL contains two classes for each common dialog; for example, the Choose Folder dialog is wrapped by
CFolderDialogImpl
and
CFolderDialog. If you need to change any defaults or write handlers for any messages, you derive
a new class from
CFolderDialogImpl and make the changes in that class. If the default behavior of
CFolderDialogImpl is sufficient, you can use
CFolderDialog.
The common dialogs and their corresponding WTL classes are:
Since writing about all those classes would make this article far too long, I'll cover just the first two, which are the ones you'll likely use most often.
CFileDialog, and its base
CFileDialogImpl, are used to show File Open and File Save
dialogs. The two most important data members in
CFileDialogImpl are
m_ofn and
m_szFileName.
m_ofn is an
OPENFILENAME that
CFileDialogImpl sets up for you with some
meaningful default values; just as in MFC, you can change the data in this struct directly if necessary.
m_szFileName
is a
TCHAR array that holds the name of the selected file. (Since
CFileDialogImpl only
has this one string for holding a filename, you'll need to provide your own buffer when you use a multiple-select
open file dialog.)
The basic steps in using a
CFileDialog are:
CFileDialogobject, passing any initial data to the constructor.
DoModal().
DoModal()returns
IDOK, get the selected file from
m_szFileName.
Here is the
CFileDialog constructor:
CFileDialog:, HWND hWndParent = NULL )
bOpenFileDialog should be
true to create a File-Open dialog (
CFileDialog
will call
GetOpenFileName() to show the dialog), or
false to create a File-Save dialog
(
CFileDialog will call
GetSaveFileName()). The remaining parameters are stored directly
in the appropriate members of the
m_ofn struct, but they are optional since you can access
m_ofn
directly before calling
DoModal().
A significant difference between MFC's
CFileDialog is that the
lpszFilter parameter
must be a null-character-delimited string list (that is, the format documented in the
OPENFILENAME
docs), instead of a pipe-separated list.
Here is an example of using a
CFileDialog with a filter that selects Word 12 files (
*.docx):
CString sSelectedFile; CFileDialog fileDlg ( true, _T("docx"), NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, _T("Word 12 Files\0*.docx\0All Files\0*.*\0") ); if ( IDOK == fileDlg.DoModal() ) sSelectedFile = fileDlg.m_szFileName;
CFileDialog isn't very localization-friendly, since the constructor uses
LPCTSTR parameters.
That filter string is also a bit hard to read at first glance. There are two solutions, either set up
m_ofn
before calling
DoModal(), or derive a new class from
CFileDialogImpl that has the improvements
we want. We'll take the second approach here, and make a new class that has the following changes:
_U_STRINGorIDinstead of
LPCTSTR.
We'll start by writing a class whose constructor takes parameters similar to the
CFileDialogImpl
constructor:
class CMyFileDialog : public CFileDialogImpl<CMyFileDialog> { public: // Construction CMyFileDialog ( BOOL bOpenFileDialog, _U_STRINGorID szDefExt = 0U, _U_STRINGorID szFileName = 0U, DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _U_STRINGorID szFilter = 0U, HWND hwndParent = NULL ); protected: LPCTSTR PrepFilterString ( CString& sFilter ); CString m_sDefExt, m_sFileName, m_sFilter; };
The constructor initializes the three
CString members, loading strings if necessary:
CMyFileDialog::CMyFileDialog ( BOOL bOpenFileDialog, _U_STRINGorID szDefExt, _U_STRINGorID szFileName, DWORD dwFlags, _U_STRINGorID szFilter, HWND hwndParent ) : CFileDialogImpl<CMyFileDialog>(bOpenFileDialog, NULL, NULL, dwFlags, NULL, hwndParent), m_sDefExt(szDefExt.m_lpstr), m_sFileName(szFileName.m_lpstr), m_sFilter(szFilter.m_lpstr) { }
Note that the string parameters are all NULL in the call to the base class constructor. This is because the
base class constructor is always called before member initializers. To set up the string data in
m_ofn,
we add some code that duplicates the initialization steps that the
CFileDialogImpl constructor would
do:
CMyFileDialog::CMyFileDialog(...) { m_ofn.lpstrDefExt = m_sDefExt; m_ofn.lpstrFilter = PrepFilterString ( m_sFilter ); // setup initial file name if ( !m_sFileName.IsEmpty() ) lstrcpyn ( m_szFileName, m_sFileName, _MAX_PATH ); }
PrepFilterString() is a helper method that takes a pipe-delimited filter string, changes the pipes
to null characters, and returns a pointer to the beginning of the string. The result is a string list that's in
the proper format for use in an
OPENFILENAME.
LPCTSTR CMyFileDialog::PrepFilterString(CString& sFilter) { LPTSTR psz = sFilter.GetBuffer(0); LPCTSTR pszRet = psz; while ( '\0' != *psz ) { if ( '|' == *psz ) *psz++ = '\0'; else psz = CharNext ( psz ); } return pszRet; }
Those changes make the string-handling easier. To implement automatic centering, we'll override the
OnInitDone()
notification. This requires us to add a message map (so we can chain notification messages to the base class),
and our
OnInitDone() handler:
class CMyFileDialog : public CFileDialogImpl<CMyFileDialog> { public: // Construction CMyFileDialog(...); // Maps BEGIN_MSG_MAP(CMyFileDialog) CHAIN_MSG_MAP(CFileDialogImpl<CMyFileDialog>) END_MSG_MAP() // Overrides void OnInitDone ( LPOFNOTIFY lpon ) { GetFileDialogWindow().CenterWindow(lpon->lpOFN->hwndOwner); } protected: LPCTSTR PrepFilterString ( CString& sFilter ); CString m_sDefExt, m_sFileName, m_sFilter; };
The window attached to the
CMyFileDialog object is actually a child of the File Open dialog. Since
we need the top-most window in the stack, we call
GetFileDialogWindow() to get that window.
CFolderDialog, and its base
CFolderDialogImpl, are used to show a Browse For Folder
dialog. While the dialog supports browsing anywhere within the shell namespace,
CFolderDialog is only
capable of browsing within the file system. The two most important data members in
CFolderDialogImpl
are
m_bi and
m_szFolderPath.
m_bi is an
BROWSEINFO that
CFolderDialogImpl
manages and passes to the
SHBrowseForFolder() API; you can change the data in this struct directly
if necessary.
m_szFolderPath is a
TCHAR array that holds the name of the selected folder.
The basic steps in using a
CFolderDialog are:
CFolderDialogobject, passing any initial data to the constructor.
DoModal().
DoModal()returns
IDOK, get the path to the selected folder from
m_szFolderPath.
Here is the
CFolderDialog constructor:
CFolderDialog::CFolderDialog ( HWND hWndParent = NULL, LPCTSTR lpstrTitle = NULL, UINT uFlags = BIF_RETURNONLYFSDIRS )
hWndParent is the owner window for the browse dialog. You can either set it here in the constructor,
or in the
DoModal() call.
lpstrTitle is a string that will be shown above the tree control
in the dialog.
uFlags are flags that control the dialog's behavior, and should always include
BIF_RETURNONLYFSDIRS
so the tree only shows file system directories. Other values for
uFlags that you can use are listed
in the docs for
BROWSEINFO, but remember that some flags may not produce good results, such as
BIF_BROWSEFORPRINTER.
UI-related flags like
BIF_USENEWUI will work fine. Note that the
lpstrTitle parameter
has the same usability problems as the strings in the
CFileDialog constructor.
Here is an example of selecting a directory using
CFolderDialog:
CString sSelectedDir; CFolderDialog fldDlg ( NULL, _T("Select a dir"), BIF_RETURNONLYFSDIRS|BIF_NEWDIALOGSTYLE ); if ( IDOK == fldDlg.DoModal() ) sSelectedDir = fldDlg.m_szFolderPath;
To demonstrate customizing
CFolderDialog, we'll derive a class from
CFolderDialogImpl
and set the initial selection. This dialog's callbacks don't use window messages, so the class doesn't need a message
map. Instead, we override the
OnInitialized() method, which gets called when the base class receives
the
BFFM_INITIALIZED notification.
OnInitialized() calls
CFolderDialogImpl::SetSelection()
to change the selection in the dialog.
class CMyFolderDialog : public CFolderDialogImpl<CMyFolderDialog> { public: // Construction CMyFolderDialog ( HWND hWndParent = NULL, _U_STRINGorID szTitle = 0U, UINT uFlags = BIF_RETURNONLYFSDIRS ) : CFolderDialogImpl<CMyFolderDialog>(hWndParent, NULL, uFlags), m_sTitle(szTitle.m_lpstr) { m_bi.lpszTitle = m_sTitle; } // Overrides void OnInitialized() { // Set the initial selection to the Windows dir. TCHAR szWinDir[MAX_PATH]; GetWindowsDirectory ( szWinDir, MAX_PATH ); SetSelection ( szWinDir ); } protected: CString m_sTitle; };
WTL has the classes
CSize,
CPoint, and
CRect, that wrap the
SIZE,
POINT, and
RECT structs respectively. They work like their MFC counterparts.
As mentioned earlier, you can use the
_U_STRINGorID type for a function parameter that can be a
numeric or string resource ID. There are two other classes that work similarly:
_U_MENUorID: This type can be constructed from a
UINTor
HMENU, and is meant to be used in
CreateWindow()wrappers. The
hMenuparameter to
CreateWindow()is actually a window ID when the window being created is a child window, so
_U_MENUorIDhides the distinction between the two usages.
_U_MENUorIDhas one member
m_hMenu, which can be passed as the
hMenuparameter to
CreateWindow()or
CreateWindowEx().
_U_RECT: This type can be constructed from a
LPRECTor
RECT&, and lets the caller pass in a
RECTstruct, pointer to a
RECT, or a wrapper class like
CRectthat provides a converter to
RECT.
As with
_U_STRINGorID,
_U_MENUorID and
_U_RECT are always included for
you by other headers.
WTL's
CString works just like MFC's
CString, so I won't be covering it in detail here.
WTL's
CString has many extra methods that are used when you build with
_ATL_MIN_CRT defined.
These methods, like
_cstrchr(),
_cstrstr(), are replacements for the corresponding CRT
functions, which aren't available when
_ATL_MIN_CRT is defined.
CFindFile wraps the
FindFirstFile() and
FindNextFile() APIs, and is a
bit easier to use than MFC's
CFileFind. The general pattern of usage goes like this:
CFindFile finder; CString sPattern = _T("C:\\windows\\*.exe"); if ( finder.FindFirstFile ( sPattern ) ) { do { // act on the file that was found } while ( finder.FindNextFile() ); } finder.Close();
If
FindFirstFile() returns
true, at least one file matched the pattern. Inside the
do loop, you can access the public
CFindFile member
m_fd, which is a
WIN32_FIND_DATA
struct that holds the info about the file that was found. The loop continues until
FindNextFile()
returns
false, indicating that all files have been enumerated.
CFindFile has methods that return the data from
m_fd in easier-to-use forms. These
methods return meaningful values only after a successful call to
FindFirstFile() or
FindNextFile().
ULONGLONG GetFileSize()
Returns the file size as a 64-bit unsigned integer.
BOOL GetFileName(LPTSTR lpstrFileName, int cchLength) CString GetFileName()
Returns the filename and extension of the file that was found (copied from
m_fd.cFileName).
BOOL GetFilePath(LPTSTR lpstrFilePath, int cchLength) CString GetFilePath()
Returns the full path to the file that was found.
BOOL GetFileTitle(LPTSTR lpstrFileTitle, int cchLength) CString GetFileTitle()
Returns just the file title (that is, the filename with no extension) of the file that was found.
BOOL GetFileURL(LPTSTR lpstrFileURL, int cchLength) CString GetFileURL()
Creates a
file:// URL that contains the full path to the file.
BOOL GetRoot(LPTSTR lpstrRoot, int cchLength) CString GetRoot()
Returns the directory that contains the file.
BOOL GetLastWriteTime(FILETIME* pTimeStamp) BOOL GetLastAccessTime(FILETIME* pTimeStamp) BOOL GetCreationTime(FILETIME* pTimeStamp)
These methods return the
ftLastWriteTime,
ftLastAccessTime, and
ftCreationTime
members from
m_fd respectively.
CFindFile also has some helper methods for checking the attributes of the file that was found.
BOOL IsDots()
Returns
true if the found file is the "
." or "
.."
directory.
BOOL MatchesMask(DWORD dwMask)
Compares the bits in
dwMask (which should be the
FILE_ATTRIBUTE_* constants) with
the attributes of the file that was found. Returns
true if all the bits that are on in
dwMask
are also on in the file's attributes.
BOOL IsReadOnly() BOOL IsDirectory() BOOL IsCompressed() BOOL IsSystem() BOOL IsHidden() BOOL IsTemporary() BOOL IsNormal() BOOL IsArchived()
These methods are shortcuts that call
MatchesMask() with a particular
FILE_ATTRIBUTE_*
bit. For example,
IsReadOnly() calls
MatchesMask(FILE_ATTRIBUTE_READONLY).
WTL has several useful global functions that you can use to do things like DLL version checks and show message boxes.
bool AtlIsOldWindows()
Returns true if the operating system is Windows 95, 98, NT 3, or NT 4.
HFONT AtlGetDefaultGuiFont()
Returns the value of
GetStockObject(DEFAULT_GUI_FONT). In English Windows 2000 and later (and other
single-byte languages that use the Latin alphabet), this font's face name is "MS Shell Dlg". This is
usable as a dialog box font, but not the best choice if you are creating your own fonts for use in your UI. MS
Shell Dlg is an alias for MS Sans Serif, instead of the new UI font, Tahoma. To avoid getting MS Sans Serif, you
can get the font used for message boxes with this code:
NONCLIENTMETRICS ncm = { sizeof(NONCLIENTMETRICS) }; CFont font; if ( SystemParametersInfo ( SPI_GETNONCLIENTMETRICS, 0, &ncm, false ) ) font.CreateFontIndirect ( &ncm.lfMessageFont );
An alternative is to check the face name of the font returned by
AtlGetDefaultGuiFont(). If the
name is "MS Shell Dlg", you can change it to "MS Shell Dlg 2", an alias that resolves to Tahoma.
HFONT AtlCreateBoldFont(HFONT hFont = NULL)
Creates a bold version of a given font. If
hFont is NULL,
AtlCreateBoldFont() creates
a bold version of the font returned by
AtlGetDefaultGuiFont().
BOOL AtlInitCommonControls(DWORD dwFlags)
This is a wrapper for the
InitCommonControlsEx() API. It initializes an
INITCOMMONCONTROLSEX
struct with the given flags, then calls the API.
HRESULT AtlGetDllVersion(HINSTANCE hInstDLL, DLLVERSIONINFO* pDllVersionInfo) HRESULT AtlGetDllVersion(LPCTSTR lpstrDllName, DLLVERSIONINFO* pDllVersionInfo)
These functions look in a given module for an exported function called
DllGetVersion(). If the
function is found, it is called. If
DllGetVersion() is successful, it returns the version information
in a
DLLVERSIONINFO struct.
HRESULT AtlGetCommCtrlVersion(LPDWORD pdwMajor, LPDWORD pdwMinor)
Returns the major and minor versions of comctl32.dll.
HRESULT AtlGetShellVersion(LPDWORD pdwMajor, LPDWORD pdwMinor)
Returns the major and minor versions of shell32.dll.
bool AtlCompactPath(LPTSTR lpstrOut, LPCTSTR lpstrIn, int cchLen)
Truncates a file path so it is less than
cchLen characters in length, adding an ellipsis at the
end if the path is too long. This works similarly to the
PathCompactPath() and
PathSetDlgItemPath()
functions in shlwapi.dll.
int AtlMessageBox(HWND hWndOwner, _U_STRINGorID message, _U_STRINGorID title = NULL, UINT uType = MB_OK | MB_ICONINFORMATION)
Displays a message box, like
MessageBox(), but uses
_U_STRINGorID parameters so you
can pass string resource IDs.
AtlMessageBox() handles loading the strings if necessary.
There are various preprocessor macros that you'll see referenced in the WTL header files. Most of these macros can be set in the compiler settings to change behavior in the WTL code.
These macros are predefined or set by build settings, you'll see them referenced throughout the WTL code:
_WTL_VER
0x0710for WTL 7.1.
_ATL_MIN_CRT
CString) normally use CRT functions, special code is compiled that replaces the code that would normally be imported from the CRT.
_ATL_VER
0x0300for VC 6,
0x0700for VC 7, and
0x0800for VC 8.
_WIN32_WCE
The following macros are not defined by default. To use a macro,
#define it before all
#include
statements in stdafx.h.
_ATL_NO_OLD_NAMES
CUpdateUIObjectbecomes
CIdleHandler, and
DoUpdate()becomes
OnIdle().
_ATL_USE_CSTRING_FLOAT
CString;
_ATL_MIN_CRTmust not also be defined. You need to define this symbol if you plan to use the
%I64prefix in a format string that you pass to
CString::Format(). Defining
_ATL_USE_CSTRING_FLOATresults in
CString::Format()calling
_vstprintf(), which understands the
%I64prefix.
_ATL_USE_DDX_FLOAT
_ATL_MIN_CRTmust not also be defined.
_ATL_NO_MSIMG
#pragma comment(lib, "msimg32")line; also disables code in
CDCTthat uses msimg32 functions:
AlphaBlend(),
TransparentBlt(),
GradientFill().
_ATL_NO_OPENGL
#pragma comment(lib, "opengl32")line; also disables code in
CDCTthat uses OpenGL.
_WTL_FORWARD_DECLARE_CSTRING
_WTL_USE_CSTRINGinstead.
_WTL_USE_CSTRING
CString. This way, code in headers that are normally included before atlmisc.h will be able to use
CString.
_WTL_NO_CSTRING
WTL::CString.
_WTL_NO_AUTOMATIC_NAMESPACE
using namespace WTLdirective.
_WTL_NO_AUTO_THEME
CMDICommandBarCtrlImplfrom using XP themes.
_WTL_NEW_PAGE_NOTIFY_HANDLERS
PSN_*notification handlers in
CPropertyPage. Since the old WTL 3 handlers are obsolete, this symbol should always be defined unless you are maintaining WTL 3 code that can't be updated.
_WTL_NO_WTYPES
CSize,
CPoint, and
CRectfrom being defined.
_WTL_NO_THEME_DELAYLOAD
NOTE: If neither
_WTL_USE_CSTRING nor
_WTL_NO_CSTRING is defined, then
CString can
be used at any point after atlmisc.h is included.
The demo project for this article is a downloader application called Kibbles that demonstrates the various classes that have been covered in this article. It uses the BITS (background intelligent transfer service) component that you can get for Windows 2000 and later; since this app only runs on NT-based OSes, I also made it a Unicode project.
The app has a view window that shows the download progress, using various GDI calls including
Pie()
which draws the pie chart shapes. When the app is first run, you'll see the UI in its initial state:
You can drag a link from a browser into the window to create a new BITS job that will download the target of the link to your My Documents folder. You can also click the third toolbar button to add any URL that you want to the job. The fourth button lets you change the default download directory.
When a download job is in progress, Kibbles shows some details about the job, and shows the download progress like so:
The first two buttons in the toolbar let you change the colors used in the progress display. The first button opens an options dialog where you can set the colors used for various parts of the display:
The dialog uses the great button class from Tim Smith's article Color Picker
for WTL with XP themes; check out the
CChooseColorsDlg class in the Kibbles project to see it
in action. The Text color button is a regular button, and the
OnChooseTextColor() handler demonstrates
how to use the WTL class
CColorDialog. The second toolbar button changes all the colors to random
values.
The fifth button lets you set a background picture, which will be drawn in the part of the pie that shows how much has been downloaded. The default picture is included as a resource, but if you have any BMP files in your My Pictures directory, you can select one of those as well.
CMainFrame::OnToolbarDropdown() contains the code that handles the button press event and shows
a popup menu. That function also uses
CFindFile to enumerate the contents of the My Pictures directory.
You can check out
CKibblesView::OnPaint() to see the code that does the various GDI operations that
draw the UI.
An important note about the toolbar: The toolbar uses a 256-color bitmap, however the VC toolbar editor only
works with 16-color bitmaps. If you ever edit the toolbar using the editor, VC will reduce the bitmap to 16 colors.
What I suggest is keeping a high-color version of the bitmap in a separate directory, making changes to it directly
using a graphics program, then saving a 256-color version in the
res directory.
This article is copyrighted material, (c.
With the exception of ColorButton.cpp and ColorButton.h,.
The files ColorButton.cpp and ColorButton.h come from Color Picker for WTL with XP themes by Tim Smith. They are not covered by the above license statement; see the comments in those files for their license.
February 8, 2006: Article first published.
Series Navigation: « Part VIII (Property Sheets and Wizards)
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/wtl/wtl4mfc9.aspx | crawl-002 | refinedweb | 5,019 | 54.42 |
Implementing a plug-in
LLBLGen Pro comes with a plug-in system, exposing the project to the plug-in. Plug-ins can be made easily by the developer. The plug-ins can be handy when you have to add a feature especially for your project, like renaming a lot of fields according to an xml file.
The LLBLGen Pro install comes with a set of plug-ins, which sourcecode is bundled with the sourcecode archive available under the downloads section of 'My account' on the website. You can use the sourcecode of these plug-ins as an example how to write a plug-in yourself.
This section gives some guidelines how to write your own plug-in. It's highly recommended you both check out the plug-ins sourcecode shipped with this SDK and the ApplicationCore reference manual also shipped with this SDK for details about the properties and methods of various classes.
Writing your own plug-in, a guide.
This guide steps through the steps to get you up and running with your first plug-in for the LLBLGen Pro designer. First, familiar yourself with the details about the plug-in system, which are described in step 0 below. Then go through the various steps to create your own plug-in. Be sure to think through what you want to do in a plug-in before starting.
Step 0: familiar yourself with the plug-in system details
All plug-ins have to be implemented using .NET and have to derive from a plug-in baseclass. This base class implements the foundation for a plug-in and describes the plug-in, allows the designer to call a plug-in etc. This base class also offers functionality to accept delegates to various methods in the LLBLGen Pro designer, and for example access to a progress window.
A plug-in is developed in a library assembly, which results in a .dll. Each plug-in dll has to be placed in the Plugins folder of the LLBLGen Pro installation before LLBLGen Pro is started. All dlls are loaded into the designer and used if one of the components in the dlls derives from PluginBase which is the common base class for plug-ins. If a plug-in crashes during startup, it is mentioned and the plug-in is ignored. The user has to restart llblgen pro if a new version of a plug-in has to be loaded. PluginBase is located in the Extensibility namespace in ApplicationCore.
A plug-in can also create a dockable window. In the case you want this, which is for example done in the Project Inspector plug-in, shipped with LLBLGen Pro, it's best to make the plug-in a DirectRun plugin, which means that it won't cause a pop-up before it's run, but it's run immediately.
When a plug-in isn't a DirectRun plug-in, it will get a bag with elements which it should use as the elements to work on. It also receives the whole project object to work on if required. The bag is a hashtable with as key the type of element in the value and as value an arraylist with objects.
It furthermore gets the application settings and user preferences as input. A hashtable with delegates is provided for the plug-in to work with the progress window created for the plug-in. The base class PluginBase is implemented in ApplicationCore, as well as the describe info object, so you'll have to reference the ApplicationCore assembly in your plug-in project.
The base class requires the plug-in to override a couple of virtual methods. One of them is the Describe method which fills a PluginDescription object. This object is used by the plug-in execution system to handle the plug-in inside the designer. It furthermore should override a method which produces a control which can be used for settings for the plug-in.
This method is called
GetConfigurationControl. The control produced by this method is hosted
in the dialog which is popped up by LLBLGen Pro when the user decides to
run a plug-in. This control has to implement the interface
IPluginConfigurationControl which exposes 2 events:
DataIsValid and
DataIsInvalid, for the run button enable/disable handling.
If DataIsValid is never fired, the plug-in will never run because the user won't be able to click the run button, as it will stay disabled. The third important method to override is Execute which actually runs the plug-in. The base class has empty implementations of these methods so not overriding them will simply produce a plug-in which doesn't do anything.
Plugins are ran from the project explorer: by right-clicking on a root node (e.g. Entities) or a single object node (like an entity), the user can select to run a plug-in and select one from the cascading menu. Plug-ins can only be started when clicking Project elements, not by clicking fields or other tiny project elements.
When the plug-in's Execute method is called, a ProgressViewer instance is shown to show the progress of the plug-in. The plug-in can control that pogress viewer by calling base class methods, like ProgressTaskStart, ProgressTaskInit etc. Of course, if the plug-in is a DirectRun plug-in, no ProgressView is shown.
Plug-ins can be viewed from the main menu: Tools -> Plugins... which pops up the plug-in viewer, which displays per plug-in the information retrieved from the plug-in's Describe method, so it is key you supply enough information in that method. Each plug-in has to have a unique GUID to identify itself.
A plug-in can control if the project explorer has to be reset before execution, which can gain some performance on long running plug-ins. This is all done through the object returned from Describe. Please consult the LLBLGen Pro designer core assembly reference manual for more information about the various settings possible in the PluginDescription object.
Step 1: setting up VS.NET
Create a library project in your language of choice and add a reference to the SD.LLBLGen.Pro.ApplicationCore.dll assembly found in the LLBLGen Pro installation folder, as well as the SD.LLBLGen.Pro.Core.dll. Add a class which derives from PluginBase. This will be your plug-in class.
Use the designer core assemblies reference manual for the namespace names you have to specify to obtain access to public classes like the Entity Definition. All model classes are defined in the ApplicationCore assembly. All relational model data classes are defined in the DBDriverCore assembly.
Create three overrides in your plug-in class, one for Describe, one for Execute and one for GetConfigurationControl. There is no need to call base class' methods in these methods as they're empty.
Add a user control to your library project. This will be the control which will be returned from GetConfigurationControl. Open the code window of the control and make sure the control implements IPluginConfigurationControl and add the two event handlers.
Step 2: setting up Describe
Describe is an important method. In here you specify what your plug-in will do, who created it etc. etc. An example implementation is shown below.
public override PluginDescription Describe() { PluginDescription toReturn = base.Describe(); toReturn.Build = _build; toReturn.Description = "General plug-in to add custom properties to various elements of an LLBLGen Pro project." + " It allows you to add the same custom property to all selected project elements."; toReturn.Id = new Guid("{E63E0064-E1CD-4726-8340-57290A3E144E}"); toReturn.Name = "Add Custom Properties Plug-in"; toReturn.ShowProgressViewerDuringExecution=true; toReturn.TargetType = PluginTargetType.SPCall | PluginTargetType.Entity | PluginTargetType.Project | PluginTargetType.ValueType | PluginTargetType.TypedList | PluginTargetType.TypedView; toReturn.TypeOfPlugin = PluginType.SingleAndMultiElementPlugin; toReturn.Vendor = "Solutions Design"; toReturn.Version = _version; return toReturn; }
Not all properties are set, which means the defaults are used. Consult the designer core assemblies reference manual for details about these properties. As you can see, the target type is specified with OR operators, to concatenate the flag enum values. If you specify just one target type, the plugin won't show up in context menus on elements the plug-in can't be run on.
Step 3: setting up the configuration control
The control's layout is up to you, as long as you fire the DataIsValid event as soon as the data is valid so the LLBLGen Pro designer can enable the run button to run the plug-in. Even if your plug-in doesn't have any settings, you still have to produce and return a valid winforms control and raise DataIsValid.
Below is a name validation event handler which is the element on the control which has to be filled in to make the example plug-in work. If validation fails, the data is invalid and the proper event is raised, otherwise the DataIsValid event is raised.
private void _nameTextBox_TextChanged(object sender, System.EventArgs e) { if(_nameTextBox.Text.Trim().Length>0) { if(DataIsValid!=null) { DataIsValid(this, new EventArgs()); } } else { if(DataIsInvalid!=null) { DataIsInvalid(this, new EventArgs()); } } }
To set up
GetConfigurationControl in your plug-in class, simply add
similar code as the snippet below:
public override System.Windows.Forms.Control GetConfigurationControl() { _control = new AddCustomPropertiesConfigurationControl(); return _control; }
This method stores the instance of the control in a member variable, for later reference.
Step 4: implementing Execute
The heart of your plug-in is of course the Execute method. All data required to make the Execute method work and run your plug-in is provided by the base class through properties, like the ProjectToTarget property, the Entities property etc. etc. If your plug-in was described as a plug-in which should run on multiple entities, it is key you use the separate collections for the objects, like Entities, TypedLists, of the base class, as these will contain the selections the user made in the object selector.
Consult the LLBLGen Pro designer core assembly reference manual for detailed information about the various properties exposed to you through the base class PluginBase.
If you've described your plug-in as a plug-in which requires the progress window, you can interact with that window using the following methods. The progress window is divided into two areas: one for tasks and one for sub tasks.
Per task you should use the sub task oriented
methods to show the progress within the current task. For controlling
the task area, you have three methods, which are offered to you by the
base class
PluginBase:
ProgressTaskInit,
ProgressTaskStart and
ProgressTaskComplete. With ProgressTaskInit you specify the number of
tasks to perform, for example 5. This will make sure that the top
progress bar on the progress window will have 5 steps and will be full
when the ProgressTaskComplete method is called 5 times. It is essential
you specify the right number of tasks to perform.
ProgressTaskStart accepts a string which is displayed below the top progress bar on the progress window so the user can see which task is currently in progress. By calling ProgressTaskComplete, you signal the progress window that the task is done and it should increase the top progress bar.
The sub tasks have their own set of methods, but they work the same: ProgressSubtaskInit, ProgressSubtaskStart and ProgressSubtaskComplete.
Another way to give feedback to the user is through the ApplicationOutput window, docked at the bottom of the LLBLGen Pro designer. To write a line of text to that window, you use the base class method LogLineToApplicationOutput and specify the parameters it requires, like the source of the message, if it is a verbose message or not etc. Below is an example of how to use the discussed methods in action.
base.ProgressTaskStart("Processing SP Calls"); base.ProgressSubtaskInit(this.SPCalls.Count); foreach(SPCallDefinition spCall in this.SPCalls) { base.ProgressSubtaskStart("Processing sp call: " + spCall.Name); switch(workTarget) { case Target.Element: case Target.ElementAndField: CreateCustomProperty(spCall.CustomProperties, existsAction); base.LogLineToApplicationOutput( string.Format( "New custom property '{0}' added to retrieval sp call '{1}'", _control.CustomPropertyName, spCall.Name), "AddCustomPropertiesPlugin", true, true); break; } base.ProgressSubtaskComplete(); } base.ProgressTaskComplete();
workTarget is a setting selected in the plug-in control for the settings.
Step 5: compiling and debugging
After you've done all the previous steps, you have code which should work as a plug-in. Compile the assembly and place it in the Plugins folder of the LLBLGen Pro installation, or the Additional Plugins folder you've specified in the Preferences and start LLBLGen Pro and check if everything works as planned.
Now, it can happen that there is a bug in your plug-in. So first of all, be sure to set the LLBLGen Pro designer preference CreateBackupBeforeRunningPlugin to true, so you won't lose any precious work.
Then, if you want to debug your plug-in, take the following steps:
- Load the plug-in project in VS.NET
- Create a debug build and copy the .dll and the .pdb file into the Plugins folder (or additional plugins folder)
- Run the LLBLGen Pro designer
- In VS.NET, press cntrl-alt-p. This allows you to attach to a process, select LLBLGenPro.exe and just select the managed debugger.
- Set a breakpoint in the method you want to break and switch to LLBLGen Pro and start your plug-in. You should now break at the breakpoint you've set. | https://www.llblgen.com/documentation/5.0/SDK/gui_implementingplugin.htm | CC-MAIN-2019-51 | refinedweb | 2,220 | 55.13 |
When a bug isn't a bug, but still requires a workaround
I have been playing with Whidbey ASP.Net over the last week, developing some web custom controls that need to publish some resources along with the control.
I have previously written an article about how to publish resources from the controls assembly in 1.1. This works really well, but requires you to do the resource extraction and HTTP handling yourself. This isn’t a huge problem as most of the code can be reused and is compiled into the resource, therefore very portable. The big problem with it is that after the assembly is referenced by the web project, there is a little bit more work to do to get it working. The developer has to add the httpHandler to the web.config so that the site knows how to intepret the request for the resource.
Whidbey has some new tricks up its sleeve. On the surface, it looks like a great implementation, but I have found some problems with it. There is a good article on MSDN that gives a great overview of how it all works. It is a little out of date though as there have been some changes.
One of the great changes in the new version is that the httphandler is inbuilt (for the webresource.axd url) as it is defined in the machine.config instead of being required in each web sites web.config. The url to hit the resource is found by calling Page.ClientScript.GetWebResourceURL to which you pass a Type (from which the assembly is obtained) and the name of the resource you want.
Like I said, on the surface, this looks great, but there are a few things I don’t like about this implementation.
Firstly, this implementation requires that you register the resource with the assembly config as one that can be served by webresource.axd. This is for security. It isn’t as bad as registering httpHandlers in the sites web.config because this is in the controls assembly and only has to be done in one place. One problem with this is that it is a piece of the puzzle that could be easily over looked or incorrectly typed. It would be nice if this was a property of the resource rather than requiring the developer to enter
<Assembly: WebResource(\[Name\], \[ContentType\] /> into AssemblyInfo.vb (which is also hidden from the IDE by default).
Secondly, the compiler prefixes the name of the resource with the root namespace of the assembly. This means, for example, that test.gif now turns into MyRoot.Web.Controls.test.gif. This is the name of the resource that must be not only defined in AssemblyInfo.vb with
<Assembly: WebResource("MyRoot.Web.Controls.test.gif", "image/gif") />, but also when you call Page.ClientScript.GetWebResourceURL. Very intuitive right?
It is the second point that causes me the most grief. Most people will not know that the namespace has been compiled into the resources name and wonder why web resources don’t work in Whidbey. I always have a nice namespace hierarchy for my web controls. Each control is under that namespace. This means that when Page.ClientScript.GetWebResourceURL is called, it can be a little more dynamic by saying Page.ClientScript.GetWebResourceURL(Me.GetType(), Me.GetType.Namespace & “.test.gif”).
What happens when the class that calls this is wrapped in a Namespace statement. The resource won’t be found. To avoid that problem, the namespace has to be hardcoded to be Page.ClientScript.GetWebResourceURL(Me.GetType(), “MyRoot.Web.Controls.test.gif”). Similarly, the registration of the resource in AssemblyInfo.vb must be hardcoded with the namespace as a string as it is a compile time configuration.
So what happens when the namespace of the assembly is changed? Broken resources all over the shop.
Many people have tried to highlight this to Microsoft’s Product Feedback Center (read here, here and here). The first link is the most interesting one. The response from Microsoft is a workaround of removing the root namespace of the assembly, or hardcode the namespace in all of your resource references. This means that each of your classes must be wrapped in Namespace statements, or lose flexibility by hardcoding namespaces.
Why is the resource compiled with the namespace as the prefix to its name? No idea, but what benefit does it bring? I still have no idea. It does have these obvious down sides though. It is a shame that Microsoft have taken the stance on this that they have (read outcome of the first feedback link above). | https://www.neovolve.com/2005/08/14/when-a-bug-isn-t-a-bug-but-still-requires-a-workaround/ | CC-MAIN-2020-05 | refinedweb | 771 | 66.44 |
All Articles | Submit Article |
Title: Plug and play architecture using policy application blocks
Author: Shivprasad Koirala
Language: Architecture Interview Questions
Level: Beginner
Description: Plug and play architecture using policy application blocks
IntroductionProblemSolutionImplementation
In this section we will discuss how we can make plug & play architecture using policy application blocks. What we will do is we will take a practical scenario where we want to enable logging for an application depending on situations. For past some days I have been writing and recording videos for architecture and project managers. You watch the videos at
To understand the real use of policy application blocks we will take up a real time scenario. No application is perfect and it is very much possible that you can have defects in production. In production as a rule we have fully compiled DLL’s and it will be very difficult to track down the errors. We can definitely use TRACE to get to the bottom of the problem. One of the issues with TRACE is that we do not get verbose information. From trace we will just get which method has the issues.Below is a solution which I have thought I am sure there are better ways of doing it. The whole point of this article is to make understand how we can use the plug and play mechanism given by policy application blocks.We will try to implement a plug and play mechanism. The application interface of our project calls business classes. When we want to enable the debug mode we will just plug in the logging application block. The logging application block will start logging in method calls in event log which we can use to analyze what issue we have in the application. In the normal production mode we will remove the logging feature. The below figure visualizes the same as a switch Which can plug in the logging or plug it out.
To implement the above solution we will use policy application blocks. Policy application blocks helps us to plug in policies which can be added and remove on fly. Using the enterprise application UI you can add new policies or remove policies.
In order that the class methods can be monitored by the policy block we need inherit the class from an interface. For the current example we want to monitor any methods of class clsFireMethods. You can see we have inherited the same from a interface ‘IMethods’
Now open the web.config file of the project and add the policy injection block. When you add the policies you will see two important nodes one of the policy and the other is the handler. Currently we only want log the method calls in event viewer so we will add logging handler. In order that logging handler should function properly we also need to add the logging application block. Now we need to add when these handlers should be fired. For the current scenario we would like to see firemethod1 call logged when the method is called. So we have added the member name matching rule and added the member name in the matches collection.
No we are all set. In the code we just need to call the ‘PolicyInjection’ static class to create the object. This class ties up the handlers and the rules accordingly. Please note to add the policy injection namespace in the code.
Once you are all done test the project with logging handler enabled and without. Whenever firemethod1 is called you will see an entry on the event logger.You can add more handlers. Depending on how you add the handlers the sequence will fire. So it will fire from top to bottom.
Submit Article | http://www.dotnetfunda.com/articles/article165.aspx | crawl-002 | refinedweb | 619 | 64 |
Using Unicode characters in HTML
Fredrik Lundh | October 2003 | Originally posted to online.effbot.org
Jeremy Hylton writes: “I have been struggling with Unicode for my weblog aggregator. There are several feeds that include Unicode data in the title or description. I tried to generate HTML output with a UTF-8 encoding, but that didn’t seem to work.”
Later in that article, Jeremy asks “Isn’t there some way to specify that stdout should use iso-8859-1 to encode all Unicode strings?”
There is some stuff in the codecs module that you can tweak for this purpose, but it’s probably easier to write your own file wrapper. Here’s one way to do it:
class encoder: def __init__(self, file, encoding="iso-8859-1"): self.file = file self.encoding = encoding def write(self, text): self.file.write(text.encode(self.encoding, "replace")) sys.stdout = encoder(sys.stdout)
The “replace” argument tells the encoder to replace non-ISO characters with question marks, instead of raising an exception.
A better solution would be to encode non-ISO characters using HTML character references. It’s fairly easy to do this using e.g. a regular expression (use re.sub with a callback that maps runs of non-ISO characters to references), but Python 2.3 makes it even easier: simply change “replace” to “xmlcharrefreplace”, and the encoder replaces any character that it cannot encode with the corresponding character reference:
class encoder: def __init__(self, file, encoding="iso-8859-1"): self.file = file self.encoding = encoding def write(self, text): self.file.write(text.encode(self.encoding, "xmlcharrefreplace")) sys.stdout = encoder(sys.stdout)
To make things even more robust, consider writing the document as plain ASCII, and use character references for all non-ASCII characters. ISO-8859-1 is the default encoding for HTTP, but HTML character encodings is something of a mess, and it might be better to be safe than sorry:
class encoder: def __init__(self, file): self.file = file def write(self, text): self.file.write(text.encode("ascii", "xmlcharrefreplace")) sys.stdout = encoder(sys.stdout) print u"voffo gör di på detta viset?"
This example prints:
voffo gör di på detta viset?
Unfortunately, this isn’t enough to solve Jeremy’s problem; it handles non-ASCII characters in titles and descriptions, but what if the title or description contains a less-than character (<) or an ampersand (&)?
Maybe the explicit encoding idea wasn’t so bad, after all. Just make sure to encode the text strings, instead of the resulting HTML:
def encode(text): text = text.replace("&", "&") # must be first! text = text.replace("<", "<") text = text.replace(">", ">") text = text.replace("'", "'") text = text.replace('"', """) return text.encode("ascii", "xmlcharrefreplace") print "<a href='%s'>%s</a>" % (encode(guid), encode(title))
(if you want to speed things up, you can leave out the > line, and perhaps also the ' line; for the latter to work, make sure to only use single quotes around HTML attributes).
Alternatively, you can wrap all non-HTML strings in a special wrapper class, and do the encoding in the __str__ method:
class text: def __init__(self, text): self.text = text def __str__(self): return encode(self.text) print "<a href='%s'>%s</a>" % (text(guid), text(title))
If you plan to print the same string in multiple places, the wrapper approach allows you to wrap the strings early on, and forget about the encoding when you print the strings:
guid = text(article.getguid()) title = text(article.gettitle()) ... print "<a href='%s'>%s</a>" % (guid, title) titles.append(title) ... for title in titles: print "%s<br />" % title
(again, if you want to speed things up, you can encode the string in the constructor instead of doing over and over again in the __str__ method.) | http://www.effbot.org/zone/unicode-in-html.htm | CC-MAIN-2016-07 | refinedweb | 624 | 58.18 |
inputDate : adding custom convertorUser13331987-Oracle Jan 30, 2013 2:31 PM
Hi,
inputDate component is returning the date in "MM/dd/yyyy" format, if I don't attach any converter to it.
Ex:
Thanks in advance for your help
Edited by: user13331987 on Jan 30, 2013 6:31 AM
inputDate component is returning the date in "MM/dd/yyyy" format, if I don't attach any converter to it.
Ex:.
<af:inputDate
Why it is returning date in long format when I add a custom converter? How can I control the calender date format when a custom converter is added?Why it is returning date in long format when I add a custom converter? How can I control the calender date format when a custom converter is added?
<af:inputDate <f:converter </af:inputDate>
Thanks in advance for your help
Edited by: user13331987 on Jan 30, 2013 6:31 AM
This content has been marked as final. Show 5 replies
1. Re: inputDate : adding custom convertorDimitar Dimitrov Jan 30, 2013 3:20 PM (in response to User13331987-Oracle)It is not necessary to use a custom converter at all. You can use the built-in <af:convertDateTime> converter, for example:1 person found this helpful
Set the format mask you want in the converter tag's "pattern" attribute. Have in mind that if you use the "pattern" attribute, then the conversion is applied on the server (but not on the client), so you should submit the field to the server (e.g. by setting autoSubmit="true") if you want the new value to be formatted immediately upon user enters a new value and exits the field.
<af:inputDate <af:convertDateTime </af:inputDate>
Alternatively, you can skip converter's "pattern" attribute if you use "dateStyle" attribute, for example:
As far as "pattern" attribute is not used in this case, the framework performs conversion automatically both at server-side and at client-side, so it is not necessary to set autoSubmit="true" in order to format the new value immediately upon the user enters a new value and exits the field.
<af:inputDate <af:convertDateTime </af:inputDate>
Have a look at the documentation of <af:comvertDateTime> for more details.
Dimitar
2. Re: inputDate : adding custom convertorUser13331987-Oracle Jan 30, 2013 4:24 PM (in response to Dimitar Dimitrov)Thanks Dimitar , for quick response.
My requirement is date display format is different from storage format. EX: need to display date in "MM-dd-yyyy" format but while storing it need to convert to "yyyy-MM-dd" format.
I am adding custom converter to convert display format to storage format and vice versa with the help of getAsObject() and getAsString() methods.
Can we meet this requirement without custom converter?
Thanks,
Kiran
3. Re: inputDate : adding custom convertorDimitar Dimitrov Jan 30, 2013 4:56 PM (in response to User13331987-Oracle)What do you mean when you say "storage format"? Where do you store the date value which is entered in the input field?
<af:inputDate> components accept values of type java.util.Date (internal data values of these components are of this type), they do not accept String values.
java.util.Date objects do not have a format, they are just date/time values. String representations of date/time values (which are displayed on the screen) have got formats, however. If you persist the value in a database column of DATE type, then you do not have to do any character formatting on the value. But if you have to persist the value in a character format (e.g. in a text file or in a database column of some character type) then you should get the java.util.Date value from the <af:inputDate> component and convert it to the necessary character representation. A JSF converter would not help in this case because JSF converters have a different purpose (e.g. they are used to convert an internal value of a JSF component to a string that is displayed on the screen, and in the opposite direction - to parse the string value entered in the field to an internal value).
If you have to convert a java.util.Date object to a character string with a specific format mask, then you could use a standard Java data/time formatter - have a look at the class java.text.SimpleDateFormat.
Dimitar
4. Re: inputDate : adding custom convertorUser13331987-Oracle Jan 30, 2013 5:14 PM (in response to Dimitar Dimitrov)My requirement is, need to display the user selected calender date in "MM-dd-yyyy" format and when user saves the form I need to save the same date into a xml file in "yyyy-MM-dd" format.
If user reopens the record need to parse the date value needs to display it in "MM-dd-yyyy" format.
Thats why I am adding jsf converter to inputDate. But when I add converter calender control returning date in long format(not sure about the exact format).
5. Re: inputDate : adding custom convertorDimitar Dimitrov Jan 30, 2013 7:15 PM (in response to User13331987-Oracle)I will try to explain again. What is misunderstood is that you should have two separate conversions - a conversion between XML file's format "yyyy-MM-dd" and a java.util.Date object and a conversion between a java.util.Date object and a string in format "MM-dd-yyyy". The 1st one must be done when you read/write from/to the XML file and load/store the value into/from a some kind of a Model layer. The 2nd one happens between the server-side <af:inputDate> component's local value and the string displayed/entered in the HTML field on the screen during the JSF's APPLY_REQUEST_VALUES phase. The 2nd conversion is performed by a JSF converter, but the 1st one cannot be done using a JSF converter and it has to be done in other way. Please, look at the details below:
You must have some kind of a Model layer (for example, a backing bean) that supplies the <af:inputDate> component with a value of java.util.Date datatype.
import java.util.Date; public class MyBean { private Date myDateValue; public Date getMyDateValue() { return myDateValue; } public void setMyDateValue(Date value) { myDateValue = value; } ... }
The datatype of the value must be java.util.Date, it cannot be java.lang.String because the "value" attribute of <af:inputDate> does not accept String. It is your responsibility to read the necessary date literal (which is in format "yyyy-MM-dd") from the XML file, to convert the string to java.util.Date and to load the value into the corresponding bean property when you navigate to the necessary record. Also it is your responsibility to convert the bean property's java.util.Date value to a string representation in format "yyyy-MM-dd" when storing it back to the XML file. You can do that using a standard Java formatter class (e.g. java.text.SimpleDateFormat) if you read/write the XML file directly in code (e.g. when you do not use any framework for marshaling/unmarshaling XML files). You cannot use a JSF converter here because JSF converters are serve different purpose.
<af:inputDate value="#{MyBean.myDateValue}" ...>
Then you must define a JSF converter on the <af:inputDate> component in order to convert the internal value of the JSF component (which is of type java.util.Date) to a readable string representation displayed/entered in the input field on the screen in format "MM-dd-yyyy":
Dimitar
<af:inputDate </af:inputDate>
Edited by: Dimitar Dimitrov on Jan 30, 2013 9:06 PM
Edited by: Dimitar Dimitrov on Jan 30, 2013 9:12 PM | https://community.oracle.com/thread/2494768?tstart=120 | CC-MAIN-2017-09 | refinedweb | 1,281 | 51.99 |
This article tells you how to build a 3-tier application by using COM and XML. Here I'm going to show you how to build an ATL COM component that returns data in XML format, and use XSLT to transform it into a HTML page, and at last how to sort and split the data into pages locally.
You need a local data source to build this demo. In my case, I use the employee table of pub database in a local SQL server.
employee
pub
As the picture shown above, the whole system will split into four parts. User browses the ASP web page, then ASP will create the COM component on remote server, and issue the command to retrieve data from SQL database. The COM component then contacts SQL DB using ADO, after the record set returns, it wraps them into XML format, and passes back to ASP. ASP dynamically outputs the XML data from the return value of COM component, while adding some head information to notify IE using a specific XSL file to render it. At this time, the user can see a web page containing a table of data, he can sort the data by clicking on the table head, or navigate pages by clicking on the button above the table.
Although there are four parts in this application, I built it on my own PC, that means I installed Windows 2000 Advance Server with IIS, and a local SQL Server.
OK, lets talk about the code step by step. The first thing is to build a COM component, which uses ADO to retrieve data in SQL Server.
Launch VC, use ATL COM AppWizard to create a new project, name it as xmlrs. Press finish to accept all the default setting values. Insert a simple object by using ATL Object Wizard (Insert -> New ATL Object), name it as xmlrsobj, and accept all the default settings. Add the methods of this object by right clicking on the Ixmlrsobj icon on the class view. Select Add Method, and then enter ConnectDB in the method name field, and [in] BSTR bstrConn in the parameter field. Add the following two methods in the same way.
xmlrsobj
Ixmlrsobj
Add
ConnectDB
[in] BSTR bstrConn
GetXmlrs ([in] int intRow, [out, retval] BSTR *xmlrs)
CloseDB (void)
Fill in the code into these functions. The following code should be added to the CPP file, since the ADO is employed to retrieve data from SQL server.
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
named_guids no_namespace rename("EOF", "EndOfFile")
COM connects to SQL server using the connection string passed from ASP client, then the COM component gets the specific record set by a SELECT command. COM component wraps up the record set into XML format in turns.
Now it's time to build your COM object. VC would register the DLL file after a successful build, then you can use it locally. If you want to deploy it on another computer, you have to do extra administrator works according to the DCOM or COM+ you use here.
The ASP file is simple. Just create the COM object we built above, calling the GetXmlrs method of this object, and use response.write to output all the returned data. To make IE understand what information it gets from the ASP pages, we should set the content type to text/xml, XML version, and specify the XML style sheet.
GetXmlrs
response.write
text/xml
Response.ContentType = "text/xml"
response.write "<?xml version=""1.0""?>"
response.write "<?xml-stylesheet type=""text/xsl"" href=""xml.xsl""?>"
Don't forget to modify the connection string in the ASP file, so that it can work in your environment.
XSL is a kind of render mechanical for XML, it is something like CSS to HTML. By using XSL, we can separate the data rending from the data itself.
<HTML>
<BODY id="listing">
<TABLE width="60%" cellspacing="0">
<TR>
<TD> fName </TD>
<TD> lName </TD>
<TD> hire_date </TD>
</TR>
<TR>
<TD> fName </TD>
<TD> lName </TD>
<TD> hire_date </TD>
</TR>
</TABLE>
</BODY>
</HTML>
With these lines of HTML code, we build a web page with an empty table, where we will fill the XML data.
Now update the code, by using the XSL code, we filled the table with the data stored in XML.
...
<xsl:for-each
<xsl:if
<TR>
<TD><xsl:value-of</TD>
<TD><xsl:value-of</TD>
<TD><xsl:value-of</TD>
</TR>
</xsl:if>
</xsl:for-each>
...
Take a look on these codes. The code pair <xsl:for-each and </xsl:for-each> means repeat all the code between the pair with every Record node in the XML file, and all the data would be sort by fName field. Recordset/Record is following the XPath syntax, which means the Record of root Recordset.
<xsl:for-each
</xsl:for-each>
Record
fName
Recordset/Record
Recordset
Next code pair: <xsl:if</xsl:if>. This code pair is used to implement page split function, which will filter out the data not in current page. The default value will only show the first 10 records. When processing xsl:if command, computer will first calculate the value of test item, if it contains at least one node of data, the test item will be true. In this case context() and index() are XSL built-in functions, context() will return the current node, and index() returns the sequence number of current node according to the order. [...] means a filter, and $ge$ and stands for >= in a well formed HTML page, meanwhile $lt$ stands for <. So the code context()[index() $ge$ 0 and index() $lt$ 10] means for the current node, if its index value is >= 0 and < 10, then test item will return true, in turns the HTML code between xsl:if pair will be rendered.
<xsl:if
</xsl:if>
xsl:if
test
context()
index()
[...]
$ge$
>=
$lt$
<
context()[index() $ge$ 0 and index() $lt$ 10]
Last but not least, the code <xsl:value-of returns the current value of fName. With the above code, it will render the content of the table during the looping.
<xsl:value-of
XSL style sheet can be combined with CSS style sheet to make the page more beautiful. The following code defines the CSS styles used in this example. Update the XSL files according to the following lines.
...
<STYLE>
BODY {margin:0}
.row {font:8pt Verdana; border-bottom:1px solid #CC88CC}
.header {font:bold 9pt Verdana; cursor:hand;
padding:2px; border:2px outset gray}
.up {background-color:#DDFFDD; cursor:hand;}
.down {background-color:#FFDDDD;}
</STYLE>
...
<TD class="header"> fName </TD>
<TD class="header"> lName </TD>
<TD class="header"> hire_date </TD>
...
<TD class='row'> fName </TD>
<TD class='row'> lName </TD>
<TD class='row'> hire_date </TD>
...
<TD class='row'><xsl:value-of</TD>
<TD class='row'><xsl:value-of</TD>
<TD class='row'><xsl:value-of</TD>
...
By now, you've got a static page with a table of XML data. We make it interactive with user by adding the following JavaScripts. These scripts helps user navigate the data in pages, while there are too much data in the table.
There are four script functions:
init()
prevpg()
nextpg()
sort (key)
Then we will hook the functions with HTML items.
...
<BODY id="listing" onLoad="init()">
...
<p class="down">Click on the head to sort!</p>
<div class="up" onClick="prevpg()">prev page</div>
<div class="up" onClick="nextpg()">next page</div>
...
<TD class="header" onClick="sort('fName')">fName</TD>
<TD class="header" onClick="sort('lName')">lName</TD>
<TD class="header" onClick="sort('hire_date')">hire_date</TD>
...
Pay attention on the code pair ![CDATA[...]]. This is because the well formed HTML will encode <, thus we have to put our script into ![CDATA[...]] pair to avoid encoding.
![CDATA[...]]
Now you should have a 3 tier application powered by COM and XML. Enjoy it. You will find when you navigate through the pages, the order will not change until you set a new. | http://www.codeproject.com/Articles/1365/Using-XSLT-to-render-XML-data-returned-by-a-COM-ob?msg=56209 | CC-MAIN-2014-41 | refinedweb | 1,330 | 72.46 |
current position:Home>"I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
"I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
2022-01-31 21:00:23 【Dream eraser】
「 This is my participation 11 The fourth of the yuegengwen challenge 18 God , Check out the activity details :2021 One last more challenge 」
today , He crawled to get Thousands of them Blind date, plain face . Say with me ? Brush the dating platform , Collect plain photos , Training machine models . It can also be believed that ? They're wearing makeup .
Read this article and you'll get
- Nearly ten thousand faces ;
lxmlFirst knowledge of analytic library ;
XPathFirst knowledge of grammar ;
CooikeAnti creeping ;
- Girl friend ( Maybe it's a windfall )
Python collection 19 The portrait of a girl on a blind date
Start with this blog , You're going to enter the crawler 120 The second small stage of the example ,
requests +
lxml Implement reptiles .
requests Believe through the front 10 A case , You're already familiar with , And then we'll build on that , Add a new crawler parsing library
lxml. The library is mainly used for
XML,
HTML Parsing , And the parsing efficiency is very high , After using it , You can get rid of the trouble of writing regular expressions .
Target data source analysis
Crawl to the target website
The target of this capture is 19 The girls' blind date channel in Beijing , The classified channel is closed 7 month 1 It's still being updated .…
Here's a screenshot from the website , If there is any infringement , Contact the eraser in time ~
The target of this crawling is the head picture above , The file name is saved as the title content .
The use of Python modular
requestsmodular
lxmlmodular
fake_useragentmodular
Key learning content
lxml The module first .
List page analysis
This grab around the list page to complete the task , The order of the list page is as follows : Copy code
The label of the picture is as follows , The extraction work is handed over to
lxml Module to complete , Of course, in order to connect proficiency , You can still use
re The first version of the module is completed .
lxml Basic knowledge of
To pass ahead of time
pip install lxml Complete the installation of the library .
Import the library and the basic use of the library .
from lxml import etree html = " One o'clock HTML Code " # Generate a XPath object html=etree.HTML(text) # Extract the data html.xpath('//li/a') Copy code
As mentioned in the above code comments XPath object , About XPath, Is a door in XML/HTML The language in which information is found in a document , By means of specific grammar in HTML The language for extracting data from the database , The study of basic knowledge , You can refer to…, The best learning skill is to use it while checking .
The sorting requirements are as follows
- Batch generation of list pages to be crawled ;
requestsRequest target data ;
lxmlExtract target data ;
- Save the picture .
Code time
When coding , In order to prevent direct anti climbing identification , In the process of crawling , Add a waiting time , Limit crawling speed ( Of course, in the follow-up found no right IP The limitation of , Just remove it ).
In the process of coding , If the following error occurs , to update
fake_useragent that will do .
raise FakeUserAgentError('Maximum amount of retries reached') Copy code
The update script is as follows :
pip install -U fake-useragent Copy code
If it still fails , I suggest you write random generation UserAgent Function of .
A little bit of anti climbing
When crawling the target data , Directly through
requests Request target address , The following code will be returned , This code is not the page where the target data is located , That is, there is anti climbing technology in the website .
Request the target address directly , The response code is shown in the figure below , Pay attention to the position of the red box .
Yes
requests Analyze the requested data , Found in the returned code that
Cookie, After repeated testing of this value , Found to be a fixed value , Go straight through
requests Parameters
headers Can be set .
After getting the source code of the target page , You can go through
lxml Page extraction operation , In the previous article has been a simple description . The focus of study is divided into two parts :
- First, through
lxmlModule
etreeobject , take HTML Source code serialization , That is to translate it into Element object ;
- Then on
ElementObject parsing , The parsing syntax used here is XPath, This article uses path analysis , There are comments in the full code section .
Complete code
import requests from lxml import etree from fake_useragent import UserAgent import time def save(src, title): try: res = requests.get(src) with open(f"imgs/{title}.jpg", "wb+") as f: f.write(res.content) except Exception as e: print(e) def run(url): # ua = UserAgent(cache=False) ua = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36" headers = { "User-Agent": ua, "Host": "", "Referer": "", "Cookie": "_Z3nY0d4C_=37XgPK9h" # The value obtained from the anti crawl code } try: res = requests.get(url=url, headers=headers) text = res.text # take html convert to Element object html = etree.HTML(text) # xpath Path extraction @class To select class attribute divs = html.xpath("//div[@class='pics']") # print(len(divs)) # Traverse Elements node for div in divs: # Extract address , Note that the extracted attribute is data-src instead of src src = div.xpath("./img/@data-src")[0] # Extract the title title = div.xpath("./img/@alt")[0] save(src, title) except Exception as e: print(e) if __name__ == '__main__': urls = [""] for i in range(114, 243): urls.append(f"-{i}.html") for url in urls: print(f" Is fetching {url}") run(url) # time.sleep(5) print(" It's all crawled ") Copy code
In order to improve efficiency , You can cancel 5 Seconds to wait , You can also use multithreading , But just try for a few seconds , Don't over grab , After all, we just want to learn .
There is also an important knowledge point in the above code , In the obtained source code, the image
src The attribute is
dot.gif( Loading pictures ),
data-src Property has a value .
The specific comparison is shown in the figure below , The picture above shows the source code of the page , The following figure shows the source code returned directly by the server .
The crawling tips in this section are , Any parsing and extraction of data , According to the source code directly returned by the server .
Grab the result display time
Reptiles 120 example , The first 11 Example completed , I hope this blog can bring you different surprises and knowledge . Relevant information can be obtained directly below .
Full code download address :codechina.csdn.net/hihell/pyth…,NO11.
Here are the various learning data generated in the crawling process , If you only need data , You can go to the download channel to download ~.
Crawling resources are for learning purposes only , Infringement and deletion . | https://en.pythonmana.com/2022/01/202201312100211138.html | CC-MAIN-2022-27 | refinedweb | 1,194 | 58.92 |
23 February 2011 48 comments Django
There was a really interesting discussion on the django-users mailing list about how to best select random elements out of a SQL database the most efficient way. I knew using a regular
RANDOM() in SQL can be very slow on big tables but I didn't know by how much. Had to run a quick test!
Cal Leeming discussed a snippet of his to do with pagination huge tables which uses the
MAX(id) aggregate function.
So, I did a little experiment on a table with 84,000 rows in it. Realistic enough to matter even though it's less than millions. So, how long would it take to select 10 random items, 10 times? Benchmark code looks like this:
TIMES = 10 def using_normal_random(model): for i in range(TIMES): yield model.objects.all().order_by('?')[0].pk t0 = time() for i in range(TIMES): list(using_normal_random(SomeLargishModel)) t1 = time() print t1-t0, "seconds"
Result:
41.8955321312 seconds
Nasty!! Also running this you'll notice postgres spiking your CPU like crazy.
A much better approach is to use Python's
random.randint(1, <max ID>). Looks like this:
from django.db.models import Max from random import randint def using_max(model): max_ = model.objects.aggregate(Max('id'))['id__max'] i = 0 while i < TIMES: try: yield model.objects.get(pk=randint(1, max_)).pk i += 1 except model.DoesNotExist: pass t0 = time() for i in range(TIMES): list(using_max(SomeLargishModel)) t1 = time() print t1-t0, "seconds"
Result:
0.63835811615 seconds
Much more pleasant!
UPDATE
Commentator, Ken Swift, asked what if your requirement is to select 100 random items instead of just 10. Won't those 101 database queries be more costly than just 1 query with a
RANDOM(). Answer turns out to be no.
I changed the script to select 100 random items 1 time (instead of 10 items 10 times) and the times were the same:
using_normal_random() took 41.4467599392 seconds using_max() took 0.6027739048 seconds
And what about 1000 items 1 time:
using_normal_random() took 204.685141802 seconds using_max() took 2.49527382851 seconds
The algorithm for returning a generator has a couple of flaws:
Here's a much more complete function:
def random_queryset_elements(qs, number): assert number <= 10000, 'too large' max_pk = qs.aggregate(Max('pk'))['pk__max'] min_pk = qs.aggregate(Min('pk'))['pk__min'] ids = set() while len(ids) < number: next_pk = random.randint(min_pk, max_pk) while next_pk in ids: next_pk = random.randint(min_pk, max_pk) try: found = qs.get(pk=next_pk) ids.add(found.pk) yield found except qs.model.DoesNotExist: pass
Follow @peterbe on Twitter
I have used a similar approach but sometimes it can fail if rows have been deleted. Thus you should only use this method if you know that all of the ID's from 1 to 'max' still exist (as a side point - if you do know they all exist, a count may be faster than a Max aggregate).
Anyway, to get around this I used something like;
model.objects.filter(id__gte=randint(1, max_))[0]
if you get a random id that doesn't exist the loop will just try another number until it has rounded up as many as it needs.
A count is never faster than a MAX aggregate. Certainly not in Postgres
Well, your solution is bugged :) You cant use max(id) since some record could have been deleted, so your randinit(1, max_) would produce id that do not exists.
But ofcourse there is bulletproof solution. Just add column to the table say "number" write a triger wich will maintain asceding int values with no gap. finaly use radint(1, max(number_column)) to get random rows.
It's not bugged. See what I wrote to Dougal. It re-tries if it doesn't exist.
The assumption is that the count is quite similar to the max.
Aff, my mistake. But still let assume You want to get 100 rows in random order. With Your solution script would execute more then 100 queries to database. It would be slow. So why are so reluctant to use trigers wich guarantees you to get what You want with one query?
Offtopic: I am not big fan of orms, and I am surprise that python/django community tries to solve database problems with weird python/django orm solutions rather then use database itself, which results in greater performance and readability.
Check the update I just added to the blog post. Selecting 100 random items only once takes the same amount of time.
How would one use triggers to solve this in a better way?
CREATE OR REPLACE FUNCTION position_update() RETURNS TRIGGER AS $$
DECLARE
next_position INTEGER;
BEGIN
IF (TG_OP = 'INSERT') THEN
SELECT (COALESCE(MAX(position), 0) + 1) INTO next_position FROM table;
UPDATE table SET position = next_position WHERE id = NEW.id;
ELSEIF (TG_OP = 'DELETE') THEN
UPDATE table SET position = position - 1 WHERE position > OLD.position ;
END IF;
RETURN NULL;
END;
$$
LANGUAGE 'plpgsql' VOLATILE
COST 100;
DROP TRIGGER IF EXISTS position_trigger ON table;
CREATE TRIGGER position_trigger AFTER INSERT OR DELETE ON table FOR EACH ROW EXECUTE PROCEDURE position_update();
Now we can:
1. Select max(position) from table;
2. generate random numbers from 1 to max
3. fetch all rows in one query using where in
On my desktop time to fetch 100random rows from 100000row table is.... ~40ms
Its a difference? Isn't it ?
I have no idea what that does. How do you use it to select random elements?
1. Create triger I've posted
2. Select maximum value of "position" column
3. GEnerate your random numbers varying from 1 to value form point 2.
4. Select rows from table using where predicate:
"where position in (generated numbers from point 3)"
I dont know django ORM so well so I can't translate it to python code :) But i assume u can use "where in" predicate in it.
Again, I'm feeling really dim. What do you mean by "Select maximum value of "position" column"??
In python, to do `random.randint(1, SOME_BIG_NUMBER)` is very quick and that's not where the optimization win is.
I've meant: select max(position) from table;
But I see my solution is not clear so i will explain once more.
We have table with rows and id column as pk. If no rows were ever deleted then we would have id values varying from 1 to number of rows. So max(id) gives us number of rows. However if some rows were deleted then max(id) != rows number, hence we cant use random.randint(1, max_id_value_returned_from_database) because there are some gaps in id sequence. But if we add additional column say "position" like in my example and add trigger to that table we could maintain this column value in given fashion:
1. if row is added, select maximum existing value for column position. Then increment it by one and save it to the new record.
2. if row is deleted then update all rows that have "position" value bigger then deleted row. All updated rows will reduce "position" value by 1. That is how i enforce sequence with no gaps in it.
Now that we have sequence with no gaps we can get maximum value of this sequence, generate some random number in python, and retrieve all rows with one query. Also we could add index for that column, but since we are retrieving randoms rows random fetches for database are inevitable.
Some caps are OK. Read my code again. If COUNT(id) is 10,000 and MAX(id) is 11,000 that means that you have about 10% blanks in there so the loop that keeps going till it has fetched 'TIMES' random entries will have to loop for about 11 (10 + 10% of 10) times.
If is the kind of application where deletes are very common, look at Simon's solution.
Actually, your algorithm is broken. Suppose you add:
row1, row2, row3, row4.
The "position" value will be 4 (randint(1, 4))
Then you delete row3. The "position" value will be decrement to 3 (randint(1, 3)). How then will it ever randomly pick row4?
Read my post again. If you delete row3, value of "position" for row4 will be decremented by 1, so, after delete it will have value of 3. This leads us to place where everything is alright.
I see! So the position is kept with the table.
But now you need an index on the position field too otherwise you can't pick from it quickly. Seems tight but extremely convoluted.
"On my desktop time to fetch 100random rows from 100000row table is.... ~40ms"
This was done without index and worked perfectly fine. Also, I'am glad that I finally make myself clear about this solution :)
So if I understand, you're gaining some optimization for the random SELECT but you're causing an UPDATE on a possibly large number of rows for every DELETE? Example: if you DELETE the first row in the table, you now have to UPDATE every other row. Seems like this would be a high cost to pay, especially if your app does frequent deletes.
You are correct. There never is golden solution for each case. All tables have theirs specifics and where on solutions is great it is a failure in another one.
Rather than decrementing the position of every row above the deleted one, you should just give the highest one the position of the deleted one. So if you have rows 1, 2, 3, 4 and you delete 2, you have 1, 3, 2. That way you only have to make one update.
I dont think that would work, ie. we got 1,2,3,4. We delete 2
1,3,4 are left and we are missing 2. Flowing ur advice i can update last value (4) and get 1,3,2.
Now, I delete 1. 3,2 are left and updating last value wont give us a correct sequence
No, you would replace the 3 with 1. That is the highest position value in the sequence 1,3,2. Not the *last* value in position, the *highest*.
@offtopic the reason for using an ORM is not that we are afraid of raw SQL (though you should sometimes...), but the power of the models and queryset classes. We can manipulate models and querysets in a pythonic way, and reuse all kinds of stuff on different models and queries. A queryset can be used to just get a list of instances, filter the change list in the admin, provide choices for a dropdownbox, be used in all kinds of templatetags etc.
Raw SQL queries have a place in django applications, but there are very good reasons to stick with the ORM most of the time...
I totally agree. Not depending on SQL means I can run unit tests in SQLite3 in memory and then manually test and deploy on Postgres.
Staying within the ORM usually means you're not complicating things for yourself. Instead of solving problems by abandoning the ORM and digging deep into the SQL perhaps instead you should walk around the problem and look at it in a different way.
Well, I know what ORM is used for but I offten see that people use it to much. It all fine and dandy what You are saying when u got simple bussnes logic like get list of something, simple predicates and stuff. But when u need to join 10 tables in sophistacated manner orms are usless :)
I cant expect that some code will do everthing for You, and even if it does dont expect it will be the best available way to achive your goal.
Probably I am lucky that I never needed to join 10 tables in a single query. If these questions come up in IRC, most of the time, whoever asked it was thinking much much too complicated.
If however, I really had to join 10 tables, punching out a complex ORM queryset would be the least of my problems. But again, I still expect such cases to be a very small minority.
Most problems I ever encountered map nicely to the ORM if you put a little thought in it.
I guess my point was that, if you need to join 10 tables you probably have made the app too complex. To get out of it, an ORM certainly won't help.
By the way, a good ORM makes it possible to inject arbitrary raw SQL if there's a need for speed or a need for a hack.
Or I had to develop big app with weird client requests :)
For the second part about hacking orm I don't know why using some fancy database features like cte, window function, sql functions, views, database extensions is "hacking". Mixing raw sql with orm imho is out of taste also, once again whats the point? If I need data only for displaying (I do not want to change that data) why would I go through the pain in making complex orm query if I can write nice and easily readable sql query that uses 100% of database ? Again, If I want to make efficient application limiting myself only to features orm provides is wrong. Why would I forbid myself from using all goodies postgres have? Or if I was developing using mysql, orcale etc why should I limit myself only to standard sql queries ?
On the other hand I have no grudge against orms. I use them every day ,but for tasks they fit perfectly. I've seen many blog posts presenting pythonic solutions for some problems
taking tens of lines which could have been done in 10line trigger...
Why? Because it reduces complexity from a code-reading point of view.
Compare the readability of your trigger function with a snippet of plain python ORM code. A new developer joining would have to study the SQL functions, the triggers, the application code.
Large SQL statements are harder to read and harder to debug. You can't put in step-by-step debuggers, debugging print statements, monkeypatching or unit testing.
That's why.
By the way, I maintain a very large web app where the SQL is handcoded (started before ORMs became popular). Hundreds of .sql files. It's fast because the database gets to do so much of the processing. But for basic things (editing a user profile) it's tedious to have to type all the SQL and the app now only works in Postgres meaning I can't run my unit tests in a in-memory SQLite3 database.
Our discussion is going to nowhere. No offence but if sql statements are hard to read and hard to debug don't use sql at all if its to hard to learn it :) The only reason why people are so afraid of using sql is that they don't know it very well so using orm is very cosy.
I know SQL extremely well but I still believe ORMs are generally better than hand-coding SQL and using triggers, functions and views. Especially if it's an app.
I'm a big fan of Redis for solving this kind of problem: stick your database primary keys in a Redis set, then use the lightning fast SRANDMEMEBER command to grab a random ID. Keeping your Redis sets synchronized with your database IDs isn't a huge burden - I usually use a bit of custom code in the .save() and .delete() methods on the Django model, but you could also use Django's signals.
Wow! That's interesting. Considering how fast a primary key index table is, Redis goes to beat it. Thanks for the tip!
BTW. Check the update I added to the blog about selecting 100 random items instead of 10 ten times.
cant you just take the count of your query set, and then pick random rows via slicing?
Count is slower than Max. Also a count will yield a lower number than the MAX(id) meaning the random range in reduced. With slicing, how would you make it random?
example
count = Model.objects.all().count()
randomrow = Model.objects.all()[int(random.random() * count)]
the idea is that since query sets are lazy, only that one row will actually be retrieved.
the reason we want to use count() instead of max, is that the max pk may be significantly higher than the total number of rows available to slice out. i.e. rows have been deleted.
if you wanted 10 random rows, you could just generate 10 random numbers, making sure they're unique, and then iterate over the list of randoms taking that row number from the the query set and appending it to a list or something.
i actually think i first saw this technique in the docks, as a way to avoid mysql's slow randomizing.
a) count() is much slower than max() or using the sequence currval()
b) if you have the IDs 1,2,4 the count will be 3 so you'd have to run randint(1,3). That way you're never picking up ID=4.
c) what does that slice translate to in SQL? Is it "LIMIT 1 OFFSET <python random number>"? If so, don't you have to order?
i don't know about a at all, it's something to test, i'm just throwing out an alternate technique to try.
b) it's zero indexed and you should be adding in checks that int(random() * count) < count
c) you're right about offset and limit, but you don't need an order because you're pulling a random one anyway, so it's irrelevant.
a) trust me, it is. considerably
c) have you tried it? It's ultra-slow
on c, taking a slice rather than get(pk=X)
i just tried it (this is on sqlite though, which just occurred to me) could someone with a real db test this?
t0 = time()
blah = Model.objects.all()[3].pk
print '%f seconds' % (time() - t0)
t0 = time()
blah = model.objects.model.objects.get(pk=2).pk
print '%f seconds' % (time() - t0)
yielded these three trials
0.000898 seconds
0.001472 seconds
0.001804 seconds
0.001447 seconds
0.001948 seconds
0.001504 seconds
when i write out the function, similar to the using_max function, i get these results (first is using count and slices, second is the using_max function
0.007093 seconds
0.010980 seconds
0.006881 seconds
0.011418 seconds
0.006947 seconds
0.011399 seconds
count = model.objects.all().count()
i = 0
while i < TIMES:
try:
yield model.objects.all()[random.randint(0, count-1)].pk
i += 1
except model.DoesNotExist:
pass
like i said though, his is on sqlite, with probably not a representative dataset.
Do it on a proper database like postgres and copy and paste the SQL that Django generates then run it like this:
mydatabase# EXPLAIN ANALYZE <the big sql statement>;
no need, now that i've filled up the database with faked data, we get this:
0.862994 seconds
0.104061 seconds
0.894336 seconds
0.114008 seconds
0.809722 seconds
0.102276 seconds
Are you sure you're doing that right? I just tried it myself and got this:
COUNT 84482
using_max() took 0.613966941833 seconds
using_max2() took 2.08254098892 seconds
using_count_and_slice() took 14.112842083 seconds
Code here:
no, i think the numbers jive, and you're right.
it seems to be a 7x factor using the count/slice method i was talking about.
Don't think so, out of the 14 seconds about 0.4 seconds is spent getting the counts.
Really nice post, but what is the business value of this. It reminds me to the question "how can I count 8 million rows in a table". And the answer is not "Slow", it is "Why do you have to?".
Taking random entries from a million rows table will not only kill your server but it will be bad for your user`s experience. Do you like sites when the content changes on every refresh? Sound to me like "Hey, wait me to refresh this page 1000 times to show you something great"
E.g. you're building a customer database and you want cold callers to ring randomly selected telephone numbers.
I am not convinced it must be done by random, but maybe you`re right.
But my approach will be to take them in order and record who I called and does this lead to a purchase/contract. The chance to find returning customers is much bigger than convincing a new one if you have some reputation(lets say a 100 000 clients). In the other case when you have less customers and you are trying to find a new ones then calling them randomly has the same value as if it is done in order?
I was just thinking, why not to use "in_bulk" to get a random id's. This could reduce number of requests to the db significantly. | https://www.peterbe.com/plog/getting-random-rows-postgresql-django | CC-MAIN-2021-10 | refinedweb | 3,508 | 74.19 |
Introduction
Optimization is an important part of software development, especially if the software is a game or some kind of scientific software which performs thousand or millions of calculations each second. In such application some method which is called all the time (path finding in a game or some formula in calculations) has to be fast. It might take only 100 ticks when called once so the optimization wouldn't be noticed but if it's called all the time, just reducing the time taken by 20 ticks might make your whole software few percents faster.
The Challenge
In this challenge you have to optimize a very basic method which is called ten thousand times. The method counts how many times one character appears in a string.
The only method you have to edit to give right results is CountCharactersOptimized(string str, char c). You are NOT allowed to change the signature of this method in any way, for example to (string str, string c). But you can edit the inside of the method any way you want. Create a loop, use string class methods, whatever it is that you desire.
Here is the code you can copy-paste into your Console application:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Optimization_Challenge_1 { class Program { private static Random random = new Random(); static void Main(string[] args) { string str = GetRandomString(10000); char c = GetRandomChar(); System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); st.Start(); for (int i = 0; i < 10000; i++) { CountCharactersSlow(str, c); } st.Stop(); Console.WriteLine("CountSlow: " + CountCharactersSlow(str, c)); long elapsedSlow = st.ElapsedTicks; Console.WriteLine("TimeSlow: " + elapsedSlow); st.Restart(); for (int i = 0; i < 10000; i++) { CountCharactersOptimized(str, c); } st.Stop(); Console.WriteLine("CountOptimized: " + CountCharactersOptimized(str, c)); long elapsedOptimized = st.ElapsedTicks; Console.WriteLine("TimeOptimized: " + elapsedOptimized); decimal difference = ((decimal)elapsedOptimized / (decimal)elapsedSlow); if (difference > 1) Console.WriteLine("CountCharactersOptimized is slower by " + (difference - 1).ToString("P")); else Console.WriteLine("CountCharactersOptimized is faster by " + (1 - difference).ToString("P")); Console.ReadKey(); } static string GetRandomString(int length) { string str = ""; for (int i = 0; i < length; i++) str += (char)random.Next((int)'a', (int)'f'); return str; } static char GetRandomChar() { return (char)random.Next((int)'a', (int)'f'); } static int CountCharactersSlow(string str, char c) { return str.Count(c1 => c1 == c); } static int CountCharactersOptimized(string str, char c) { //return str.Count(c1 => c1 == c); } } }
Example run:
CountSlow: 2002 TimeSlow: 9091487 CountOptimized: 2002 TimeOptimized: 3893097 CountCharactersOptimized is faster by 57,18 %
As you can see in the Main method, the results will be in percentages. Milliseconds/Ticks wouldn't tell us enough because someone might have faster computer.
For testing you may reduce the number of calls or the length of the string because the Slow method takes about 9 seconds on my computer (which is slow like the method) when ran in debug mode.
Please don't use solution where you cache the answer and then just return the same answer
Rewards
The one who is able to reduce the time taken the most will be rewarded with the awesome "Optimization guru" title which you can include in your profile signature as text. However, no one will be telling you that you had the fastest time, you have to check it yourself in this thread.
Final words
Good luck and have fun optimizing. Creating 50% faster method might be easy. But don't stop there, try to be 80% or 90% faster!
Remember to use Spoiler and Code tags when posting code. But you can post the results outside of the code tags.
Feel free to post your unsuccessful solutions too. | http://www.dreamincode.net/forums/topic/262838-optimization-challenge-count-characters/page__pid__1530187__st__0 | CC-MAIN-2013-20 | refinedweb | 601 | 57.16 |
Hi. How to implement communication in a Xbee mesh network in API mode. I am trying to understand Arduino + Xbee communication in a mesh network.
I am starting to learn arduino + Xbee and this time and I just want to know how to establish communication between units in a mesh network. The data is not relevant. I just want to know how to send and receive data from coordinator to router or from router to coordinator. Is the the following exmaple OK? If not, where am I wrong. Similar code is on both units.
#include <SoftwareSerial.h> SoftwareSerial Xbee( 1, 0 ); void setup( ) { Serial.begin( 9600 ); Xbee.begin( 9600 ); Serial.println( "Ready!" ); delay( 500 ); Xbee.write( "XBee 2 says it's ready!" ); } void loop( ) { // if( Serial.available( ) ) { // /* If data comes in from serial monitor, send it out to XBee */ // xbee1.write( Serial.read( ) ); // } Xbee.write("0x02", HEX); if( Xbee.available( ) ) { /* If data comes in from XBee, send it out to serial monitor */ Serial.println("unit2"); Serial.println(Xbee.read(), HEX); Xbee.write(Xbee.read()); } delay( 2000 ); } | https://forum.arduino.cc/t/communication-in-xbee-mesh-in-api-mode/461418 | CC-MAIN-2022-21 | refinedweb | 176 | 63.15 |
table of contents
- buster 4.16-2
- buster-backports 5.04-1~bpo10+1
- testing 5.10-1
- unstable 5.10-1
NAME¶epoll_wait, epoll_pwait - wait for an I/O event on an epoll file descriptor
SYNOPSIS¶
#include <sys/epoll.h>
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout); int epoll_pwait(int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t *sigmask);
DESCRIPTION¶The()¶The¶When successful, epoll_wait() returns the number of file descriptors ready for the requested I/O, or zero if no file descriptor became ready during the requested timeout milliseconds. When an error occurs, epoll_wait() returns -1 and errno is set appropriately.
ERRORS¶
-¶ep¶epoll_wait() is Linux-specific.
NOTES¶While). | https://manpages.debian.org/buster/manpages-dev/epoll_wait.2.en.html | CC-MAIN-2021-04 | refinedweb | 117 | 51.24 |
This is my code so far
#include<fstream> #include<iostream> #include<cstdlib> #include<stdlib.h> using namespace std; const int MAX_GENERATED = 100; void fillArray(int a[], int size, int& numberUsed); //prototype int main () { int array[MAX_GENERATED], numberUsed; fillArray (array, MAX_GENERATED, numberUsed); getchar (); getchar (); return 0; } void fillArray( int array[], int size, int& numberUsed) { ifstream inStream; string fileName; cout << "What file would you like to work with?" << endl; cout << "Remember to include the file extension." << endl; cin >> fileName; inStream.open(fileName.c_str()); //to connect with file int next, index = 0; inStream >> next; while (index < size) //loop fills array { array[index] = next; cout << array[index] << endl; index++; inStream >> next; } //end while loop numberUsed = index;//maybe can do something with this //might need 2d array?? }
It reads the input from a text file with one number per line with a maximum of 100 numbers in the file. These were numbers from -20 to 20 and were randomly generated.
I now have to display each number and the number of times it appears in the input file
It has to look something like this:
--------------
N COUNT
--------------
-12 4
3 3
4 2
1 4
-1 1
2 2
--------------
Total = 16
--------------
The problem with the code as it is, is that there are 20 numbers in the file, the last one being a randomly generated 15. When the program displays the numbers it does fine, but displays the number "15" eighty times. I want to know how to fix this, if possible.
Also, how may I go about counting the number of times each number appears?
I know I can do an if statement that if the number is -20, increment a counter and do that for up to 20. However, this method is tedious and I don't think it is desired for this.
I appreciate any help at all on this, I hope I've given enough information. | https://www.daniweb.com/programming/software-development/threads/153877/how-to-display-numbers-from-an-input-file-and-count-each-one-s-occurence | CC-MAIN-2018-30 | refinedweb | 315 | 66.67 |
MathematicsAlgebraGraphs and Functions23479 Nodes Add Remove If all the nodes of a simple, connected, planar graph have degree 4 and the number of arcs is 12, into how many regions does it divide the plane? Solution Summary This shows how to work with nodes of a simple connected graph. $2.19 Add Solution to Cart Remove from Cart Related Solutions Live Nodes, Garbage Collection in Java ... As inverse list is being built by adding a new node to list p in each iteration, it adds to the count of live nodes by 1 in each iteration. ... C++ ordered binary tree: inorder, preorder, postorder ... int countNodes(struct node* node) { if (node == NULL) return 0; else // Total nodes = 1 (accounting for current node) + nodes in its subtrees return (1 ... Actives nodes, adapter, ethernet 1. Suppose four active nodes-nodes A, B, C and D-are competing for access to a channel using slotted ALOHA. Assume each node has an infinite number of packets ... Java Nearest Neighbor Algorithm ... String[] result = new String[n]; for (int i=0; i< n; i++) { String[] node = nodes[i].split(":") node[0] = ID, node[1] = xpos, node[2] = ypos int xpos ... Linked List that Counts Unique Entries ... If we do not find the number in the linked list, then we will add a new node to the linked list with the new number and set the count to one. ... Binary Tree Delete Java ... largest value node of the left subtree of theNode TreeNode parentNode2=theNode; TreeNode theNode2=theNode.leftNode; // Only go throught the right nodes while ... Transportation and Transshipment Nodes ... Then we have node balancing equations for transshipment nodes ie for each transshipment nodes input is equal to output x14+ x24+x34=x46+x47+x48+x49 for ... Use a stack to reverse the contents of a file ... integers. This primarily requires changing the type of the data field in the Node class. We ... Node::Node() { data = 0; next = 0; }. Node::Node ... Adapter and Node - Link Layer & LAN ... from one node to the other on a network. A network adapter is a device (hardware or software-controlled) that allows communication of data between nodes (eg ... Network Models: Quantitative approaches ... 10. We have to identify the shortest path to traverse from source to destination node. Nodes 2-9 are called as intermediate nodes. ... View More | https://brainmass.com/math/graphs-and-functions/23479 | CC-MAIN-2016-44 | refinedweb | 385 | 75.3 |
when I ran this code I got an error says "parameter name omitted", I doubt it's because I'm using printf which returns int type inside a void return function.
*NOTE: I was writing this code to examine will the pointer change the value of a global variable successfully or not ?
#include <stdio.h>
int a = 5 ;
void call(int)
{
printf("%d\n",a);
}
int main()
{
int* p = &a;
call(a);
*p = 6 ;
printf("%d\n",a);
printf("%d\n",*p);
call(a);
}
It seems that the compiler considers warnings like errors. In fact this function definition
void call(int) { printf("%d\n",a); }
is valid. However the compiler warns you that the parameter name is omitted though the function is called with an argument.
Indeed the function does not use its parameter. So you can define it either like this (a preferable definition in C)
void call( void ) { printf("%d\n",a); }
or like this
void call() { printf("%d\n",a); }
In this case you have to call the function like
call();
and the function will rely on the global variable
a.
Take into account that if you exchange the function definitiom and the definition of the global variable like this
void call( void ) { printf("%d\n",a); } int a = 5 ;
then the code will not compile.
Thus it would be better if the function did not deal with global variables. SO it is better to define the function like
void call( int a ) { printf("%d\n",a); }
and call it like
call(a); | https://codedump.io/share/XZdXNuzHAC7f/1/using-printf-in-a-function-returns-void | CC-MAIN-2018-13 | refinedweb | 256 | 65.66 |
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode.
Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript).
Hello,
How to do that the genertaed object fill the viewport and be centered, because the object is too large.
I tried to use the c4d.CallCommand(12148) inside the GetVirtualObjects() function but this doesn't work. its work only if I use it inside Message() function.
is there a possibility to do that using python
Thank you.
Hi,
at least for me it is really hard to answer your question in the current form.
Modifying the active camera (letting an object fill the view) is quite an unusual thing for both a Python Generator Object and a ObjectData plugin to do. You might want to reconsider your approach. Also worth mentioning is that ObjectData.GetVirtualObjects() is executed in a threaded context, in which it is forbidden or disencouraged to modify the scene or add events. Invoking the 'center in view'-command does both (it modifies the editor camera object), so unexpected behavior is in this case actually to be expected
ObjectData
ObjectData.GetVirtualObjects()
To get better help you should post your code and describe your problems more in detail.
Cheers
zipit
@zipit
Hi,
I created the following example just to demonstrate my issue:
Code:
class MyCube(plugins.ObjectData):
def Init(self, op):
self.SetOptimizeCache(True)
self.InitAttr(op, float, [c4d.MYCUBE_OBJECT_WIDTH])
self.InitAttr(op, float, [c4d.MYCUBE_OBJECT_HEIGHT])
self.InitAttr(op, float, [c4d.MYCUBE_OBJECT_DEPTH])
data = op.GetDataInstance()
data.SetFloat(c4d.MYCUBE_OBJECT_WIDTH, 1600.0)
data.SetFloat(c4d.MYCUBE_OBJECT_HEIGHT, 1000.0)
data.SetFloat(c4d.MYCUBE_OBJECT_DEPTH, 1500.0)
return True
def GetVirtualObjects(self, op, hierarchyhelp):
width = op[c4d.MYCUBE_OBJECT_WIDTH]
height = op[c4d.MYCUBE_OBJECT_HEIGHT]
depth = op[c4d.MYCUBE_OBJECT_DEPTH]
cube = c4d.BaseObject(c4d.Ocube)
cube[c4d.PRIM_CUBE_LEN, c4d.VECTOR_X] = width
cube[c4d.PRIM_CUBE_LEN, c4d.VECTOR_Y] = height
cube[c4d.PRIM_CUBE_LEN, c4d.VECTOR_Z] = depth
return cube
And here is an screenshot for the given result :
The object is too large and it cut off in the viewport, and my object must be with the given dimensions above
while what you are doing is much clearer now, I still do not really get your problem An ObjectData plugin that implements GetVirtualObjects is not really supposed to modify the scene camera. Therefor I am a bit hesitant to tell you ways how you could circumvent the threaded context of GVO.
GetVirtualObjects
GVO
Just consider an user has three of your MyCube objects in his/her scene and has animated a parameter in each of these objects. When he/she starts the scene playback GVO will be invoked for each object at least once per frame. If you had some sort of camera logic attached to the execution of your GVO, the scene camera would wildly jump from object to object for each frame and the user would not be able to interact with the scene anymore.
If you really want to have some sort of "frame this object"-logic attached to your object, I would propose adding a button to your description resource and then frame the object when the user presses that button.
@zipit
My object is limited to only one Object instance by document, (is not possible to open more than one object in current document). It is a studio light kit that will contain a lot of objects. I had thought about adding button to do that.
Anyway, thank you very much for your help. I will probably adding button to do that.
As Zipit said, this is not the right place to trigger event or change the scene.
What I would like to know is if it's a "once shot" or "always".
If it's one shot, you could Create a script or a commandData that will add your generator to the scene and take care of changing the camera to Frame it. This is allowed.
If it's "always"
As I understand, you are going to create a Cube (we know the size) and put object Inside it ?
So you can move your cube backward (in camera space). You just have to check if your 8 points are in the frame.
That remember a bit this post. You will find code and information to check if your object is framed..
Once again, don't update the scene or move the camera in a generator.
hope that helped.
Cheers,
Manuel
@m_magalhaes
Hello,
it's a "once shot" I would like to execute this command only on the first object open. in the case if the object is saved and reopened the command should not be re-executed. And also I don't want to move the object out of the world center.
No problem, I will just add a button to my description resource and run the command c4d.CallCommand(12151) # Frame Selected Objects
if you only want to frame the object on instantiation and also want to restrict the user to only being able to create one of your objects (which you cannot really do either in a safe way from within an ObjectData plugin), then the solution proposed by @m_magalhaes - writing a CommandData wrapper - is probably the best solution, as it can do both easily.
CommandData
hi,
We already talked on this thread about how to limit the number of object in a scene.
(it's cool to see tools coming to life)
So if you just want to frame the object from time to time, and still want to have that in your interface, i think the button is probably the best solution.
hello,
without any news, i'll pass this thread to solved.
@m_magalhaes
Hello Manuel,
ok Thank you. I have used the solution that I have mentioned above. | https://plugincafe.maxon.net/topic/11767/how-to-do-that-the-generated-object-fill-the-viewport-and-be-centered/? | CC-MAIN-2021-43 | refinedweb | 972 | 64.41 |
Hi guys! Does anybody know fast SerialUSB library for Arduino DUE? Current SerialUSB read data at 1Mbit/s but can be at 10Mbit/s easily.
I DO get about 10mbit.... over 1MB per second......
It is down to what payload you transfer.
Regards,
Graham
Hi Graham! I used in PC the following python script:
import serial import sys
ser =)
for i in range(100000) : ser.write('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
In Arduino Due:
char buffer[48];
void setup() { SerialUSB.begin(115200); }
void loop() { if (SerialUSB.available() > 0) { SerialUSB.readBytes(buffer, 48); } }
Speed of read is around 1Mbit/s
How to make 10Mbit/s ? What's wrong may be in my scripts?
Try lifting your read buffer to 256…
Regards,
Graham
I did test. This is my results:
buffer 48: 121kByte/s=0,95Mbit/s buffer 256: 129kByte/s=1Mbit/s
So, reading speed of SerialUSB is not very good.
You can look at comparing test results from the Internet:
It's very terrible that Arduino Due has so powerful hardware and so not optimal libraries. Guys, let's fix it pls.
I found one solution here But I haven't so deeply knowledge to change libraries and provide it for all. Can anybody from Arduino's experts optimize SerialUSB for fast reading? Thanks in advance!
The data rate is determined FAR more by the HOST device than the target device....
Regards, Ray L.
it's 100% arduino's problem. I connected USB-RS485 adapter to PC and used the same python script. Speed was 2,5Mbit/s (and can be higher I think). With arduino - max 1Mbit/s.
Can anybody pls help to optimize SerialUSB.read?
Sorry sined23 for misleading you, my write speed is >10mb, my read speed is comparable with yours (133174 bytes/second). :(
I will see if I can make sense of the link you gave.
Regards,
Graham
Graham, thank you! I will wait :)
Actually I also got write speed >10Mbit, even 40Mbit. But read speed is low :(
I connected USB-RS485 adapter to PC and used the same python script. Speed was 2,5Mbit/s (and can be higher I think).
Same Driver? I believe the Due uses Windows built-in CDC driver, which is reported to be "not that great." If your USB/RS485 driver has an FTDI or other chip that has its own driver, direct comparisons could be invalid.
Could be fun to poke at the Due code and see what changes have any effects...
@westfw,
You have previously mentioned the thesycon driver, have you personally tried it?
@sined123,
The link you sent with those changes to USBcore etc, I tried what he suggested, and the difference is amazing, BUT it makes the received data unreliable.... Not suitable if your data is critical.
Regards,
Graham
Graham, but is it possible to increase read speed without bit error? I think it must be some way.
Hi sined,
Yes it should be, but I am thinking this is over my head too..... Take a look at this document from Atmel, I think the problem is a poorly implemented USB/CDC core by the Arduino gang.... I am just reading it now to see if I can make head or tail of it... :o
Regards,
Graham
Graham, oh, it would very cool if you can deal with it
BTW: I found author of the usb libraries. It’s Peter Barrett.
Also there are contributors:
Do you know somebody from them? May be they can join us?
Perhaps my knowledge was enough
I increased USB read speed up to 8Mbit/s.
Speed can be increased more, but need optimize libraries more.
Pls, help to test it.
unzip fast_usbread.zip into hardware/sam/1.6.7/cores/arduino
after that you can use SerialUSB.readBlock(buffer, length) with high read speed
P.S. fast_usbread.zip is updated again
fast_usbread.zip (20.7 KB)
Read speed is increased up to 12Mbit/s !!! (using buffer 500 Bytes in SerialUSB.readBlock)
Use updated fast_usbread.zip
fast_usbread.zip (20.7 KB)
Hi Sined,
I have been quite busy with my own stuff(UTFT_GHL) but I am very interested to test your improvements to DUE read speed, however, what changes have you made to stream and uartclass? I understand the need for changes to usbcore, usbapi and cdc… A little more info would be good.
Also I am using 1.6.5 as I had issues with both 1.6.7 and 1.6.8, so unsure if I can just overwrite these files…
Regards,
Graham
Hi Graham! Arduino Due has CDC buffer 512 bytes (it’s configurable).
When data comes from PC, Arduino Due runs accept function from CDC.cpp.
Accept get only one byte and write it into the buffer.
You can see CDC.cpp (Serial_::accept):
c = USBD_Recv(CDC_RX); buffer->buffer[buffer->head] = c;
And when you run USBSerial.readBytes(array, len), Arduino Due fill in array from CDC buffer only one by one byte.
You can see Streem.cpp (Stream::readBytes):
int c = timedRead(); if (c < 0) break; *buffer++ = (char)c;
timedRead runs read() function, only it uses timeout feature.
Becouse of it read speed is slow.
I decided to write bytes into CDC buffer as many as possible () and get from CDC buffer full length of array.
I wanted to change readBytes function but decided to create new one and called readBlock.
Actually it’s possible to modify only readBytes and don’t create readBlock.
So, I added new function readBlock in Stream.cpp and Stream.h
readBlock can’t use read() from Streem.cpp becouse read() get only one byte.
So, I created readb in CDC. int Serial_::readb(char *c, size_t length)
readb should be declared in several places.
In UARTClass as well. But it will not work in UART
Becouse it’s specially for USB.
In UARTClass.cpp I just added
int UARTClass::readb(char *c, size_t length) { return 0; }
Now about readb in CDC.cpp:
unsigned int d = min((buffer->head - buffer->tail) % CDC_SERIAL_BUFFER_SIZE, length); // know how many bytes we can get from CDC buffer unsigned int i; for (i = 0; i < d; i++) *c++ = buffer->buffer[(buffer->tail + i) % CDC_SERIAL_BUFFER_SIZE]; // get bytes buffer->tail = (unsigned int)(buffer->tail + d) % CDC_SERIAL_BUFFER_SIZE; // change tail as tail+d
About accept in CDC.cpp:
uint8_t c[CDC_SERIAL_BUFFER_SIZE]; // create temp array uint32_t k = USBD_Recv(CDC_RX, &c, (buffer->tail - i) % CDC_SERIAL_BUFFER_SIZE); // recieve bytes as many as possible into temp array c. k - count of recorded bytes uint32_t j; for (j=0;j<k;j++) buffer->buffer[(buffer->head + j) % CDC_SERIAL_BUFFER_SIZE] = c[j]; // write k bytes into CDC buffer buffer->head = (buffer->head + k) % CDC_SERIAL_BUFFER_SIZE; // change head as head+k
Actually it’s hard to explain all. I spend 2,5 days to get it
If you have some questions pls ask.
One more thing. I changed USBD_Recv in USBCore.cpp
before it used:
while (n--) *dst++ = UDD_Recv8(ep & 0xF);
to get data from USB.
But now it uses:
UDD_Recv(ep & 0xF, dst, len);
It really increases read speed as well.
You can backup your files and copy mine. About changes you can use compare tools to find exact changes.
When you finish your tests pls tell me results. It's interesting for me :)
Total Time taken to transfer 20971520 bytes =15335852(us)
Bytes per second =1367483.2 MB per second =1.3041337
:) 8)
Well done!!
Regards,
Graham | https://forum.arduino.cc/t/fast-serialusb-for-arduino-due/377551 | CC-MAIN-2021-31 | refinedweb | 1,225 | 77.03 |
Introduction
Ok, the title is a bit sensationalist. I don't think dynamic typing is really dead. Different tasks call for different language characterstics, and there will always be a place for dynamically typed languages. However, I believe the decades-long debate about whether dynamic typing or static typing is the better choice for general-purpose computing is pretty much over, and dynamic typing lost.
The arguments
The core argument for static typing is that the compiler will catch a lot of errors for you, which saves you time. While a proper test suite will catch all or most of them in any case, and using static typing doesn't eliminate the need for such a suite, taking the test step out of the edit-load-test cycle is as much a win as taking the compile step out of the edit-compile-load-test cycle.
The core argument for dynamic typing is that providing the compiler with type information is a waste of time. Having to type in the type name as many as three times in some cases interrupts and slows development.
Both of these statements are prima facei true, and the question is which provides the larger savings. I personally spent two decades using dynamically typed languages because - well I hate typing.
The fallacy
The problem is that you only have to provide the compiler with lots of type information for languages using primitive type systems. Since most of the popular statically typed languages do that, people don't realize that this is a fallacy.
If you instead use a language with a modern type system - or even a more conventional one and a modern type engine - you can avoid providing type information most of the time. Instead, the compiler can derive the type of variables based on the operations they participate in and the constants also used in those operations, allowing for variable use that is similar to dynamically typed languages.
It's not perfect, because some operations can work on multiple types, and the compiler may not have enough information to pick an ambiguous type. But those cases are the exception, not the rule.
The irony
What's ironic here is that a statically typed language can use the type information to cut down on the typing needed in some cases. All languages provide default behaviors for types composed from more primitive types. Dynamically typed languages do this when comparing container types, since the comparison of those is done by comparing the contained elements in an order determined by the container. Statically typed languages can also do this for creation and for union types, because they have the information required to do so where dynamically typed languages don't.
So, while the argument against static typing is that the developer has to write more code, the reality is that a language with a modern type system can derive the type information, and use it to cut down on the amount of code the developer has to write!
An example
I realized this interesting facet of static typing while working on project euler problem #54
Given that Python values cutting out boilerplate, I wonder if there's some way to leverage this as completely as Haskell does. The enum types aren't a problem, and a tuple for a card should also work mostly the same. The real trick is the union type used to represent a hand. In Python I'd create another enum for the types of the hands, which would be about the same length as the union type declaration in Haskell. However, where in Haskell I'm now done, Python would seem to require creating a wrapper type to provide the comparison function.
A comparison
So, let's go through the types involved in both languages.
Note that I'm using the Enum class from as-yet-unreleased Python 3.4. There is no Enum class in earlier versions of Python, though there are a number of third party modules available that are similar to this. Since this was chosen for Python 3.4, it's presumably the best of breed and will become the defacto standard.
The python types haven't been put into a program, and have only been tested informally.
Suit
Haskell provides a simple declaration for the suit of a card:
data Suit = Spades | Hearts | Diamonds | Clubs deriving (Show, Eq)
A suit is either
Spades,
Hearts,
Diamonds or
Clubs. The last bit -
deriving Eq - tells the compiler to automatically create the code so that instances of a Suit can be compared for equality. It doesn't provide an ordering (that would be
Ord as well as
Eq), because most poker games - and the problem statement - don't rank suits. This type - and all the rest - derive from
Show so we can just
Python is equally succinct:
Suit = Enum('Suit', 'Spades Hearts Diamonds Clubs')
This creates the class
Suit as a subclass of
Enum with the four suits as members. The comparison behaviors come from the
Enum class, not the
Suit type, so there's no need to specify something like a
deriving clause.
The oddity of using strings and having to specify the name twice (once to name the created class, and once as a variable to bind it to) comes from using the functional shorthand for
Enum. While the bound variable and the class name don't have to be the same, it's idiomatic to do so, and doing otherwise could result in some confusion in tracebacks and other error messages. A
class statement could be used, but that would require binding the members to values by hand.
Rank
The Haskell for the rank of a card is only slightly longer:
data Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Show, Eq, Ord, Enum)
For rank, we want ordered comparison, and a sequence to the entries in the list, so we add
Ord and
Enum to the deriving clause to get those respective behaviors.
Python is also slightly longer:
Rank = IntEnum('Rank', 'Two Three Four Five Six Seven Eight Nine Ten ' 'Jack Queen King Ace')
While the
Enum class is already iterable, it doesn't have an ordering, so we use the subclass
IntEnum which adds that.
Card
The representation for a card in Haskell is as obvious as the
Suit and
Rank types:
data Card = Card Rank Suit deriving Show instance Eq Card where Card r1 _ == Card r2 _ = r1 == r2 instance Ord Card where Card r1 _ <= Card r2 _ = r1 <= r2
Here Haskell gets the duplicate name. The first
Card is the name of the type, the second the name of a constructor for instances of that type. Again, idiomatic usage is that they be the same if there's only one constructor, but it's not required.
This is the first type where we can't automatically derive the behavior we want. That's because the default would include the
suit component in the comparison, whereas we want to ignore it. So we need to provide two instance definitions - one for
Eq and one for
Ord - that provide the desired behavior.
Python has a similar problem:
@functools.total_ordering class Card(object): def __init__(self, rank, suit): self.rank = rank self.suit = suit def __eq__(self, other): return self.rank == other.rank def __lt__(self, other): return self.rank < other.rank
Haskell's default for comparisons uses the features of a
Card. In a dynamic language, what features do an don't exist can change during execution. This makes them a poor choice for use in default behaviors. So the default behavior for comparison of objects in Python is to compare their identity. That is an implementation-defined value that is only guaranteed to be unique to this object during it's existence, and not change during the life of the object.
This means that by default, an object is only equal to itself. Still not what we want, so we provide an
__eq__ method to get the proper value.
The default for ordering, on the other hand, is useless. You can't depend on two objects having the same order relationship between runs. So any time we want to have an ordering on instances of a class, we have to write at least one method, in this case
__lt__. The
@functools.total_ordering decorator then takes care of providing the rest of the comparison methods for a total ordering, which is what we want.
Knowing the features also means that a
Card constructor must always accept a
Rank and a
Suit and return a
Card so a default constructor can be created by the language. Being able to attach features dynamically is normally leveraged in a creation method in dynamic languages, so we have to write the
__init__ method to do that. To be fair, at least one dynamic language allows the creation of instances of such types which bind the values automatically, but that does seem to be the exception rather than the rule for dynamically typed languages.
Hand
So, we're ready for the actual hand type. In Haskell, that's only a little bit more complicated than the preceding:
Here, we can see why Haskell has both constructors and type names. The type is
Hand, but the constructors are the types of poker hands:
FullHouse,
Flush, etc.
Hand, like most of the previous Haskell types, derives the
Eq and
Ord functions for the type, just like it does for any other container type. This does what we want -
Hand types listed first will be less than hand types listed later, so a
Flush is greater than a
Straight. Two
Hands of the same type will be compared by the provided
Ranks, if any, and then the lists of
Cards in the hand will be compared if the
Ranks are equal. The only requirement for correct behavior is that the
Hands be created correctly.
In Python, this is a bit harder - there is no union type for Python. So we're going to have to provide our own discriminator. That's:
Hand = IntEnum('Hand', 'HighCard PairOf TwoPair ThreeOf Straight Flush FullHouse FourOf StraightFlush')
And now there's lots of choices, but no obviously good ones. Writing a single class similar to
Card, except you then have to decide how to handle the differences between initializing the different
Hand types. You could default the two
Rank elements so you can leave them off when not needed, but this exposes the internal implementation in the API. One way to deal with different initializations would be a subclass for each hand type, which might be idiomatic, but would be a bit long.
You can avoid having to write custom comparisons by using a tuple that starts with a
Hand entry and comparing those. In that case, a function for each hand type that returns the appropriate tuple does the job, and provides a clean API, but it's a bit repetitive:
def HighCard(cards): return Hand.HighCard, cards def PairOf(rank, cards): return Hand.PairOf, rank, cards def TwoPair(hiRank, loRank, cards): return Hand.TwoPair, hiRank, loRank, cards def ThreeOf(rank, cards): return Hand.ThreeOf, rank, cards def Straight(cards): return Hand.Straight, cards def Flush(cards): return Hand.Flush, cards def FullHouse(overRank, pairRank, cards): return Hand.FullHouse, overRank, pairRank, cards def FourOf(rank, cards): return Hand.FourOf, rank, cards def StraightFlush(cards): return Hand.StraightFlush, cards
You could drop the
Hand enum and manage the values yourself, but that still leaves this version twice as long as the Haskell version.
Conclusion
As I stated at the outset, the statically typed code has less boilerplate. But it's really a minimal difference. Even in the worst case, with no actual code beyond the type declaration and creation, the dynamically typed code is only about twice as long as the statically typed code. In this case, exposing some of the implementation details to the user could make them shorter in both languages, and much closer to the same length. Adding real code - for instance, to categorize a hand as the proper type then invoke the appropriate constructor - will make that less significant.
The real difference was that - when I got the union type - the statically typed language still had an one obvious way to do things, that was succinct and provided an API I was happy with. With a dynamically typed language, there is no union type, since they don't make sense. After all, your variable can hold all the types, you just have to write the code that deals with the differences between them. But - well, you have to write that code. Which means figuring out the best way to deal with it. You also have to decide what the API is going to look like, and the examine the tradeoffs in it from using a simpler implementation. That took longer than writing all the rest of the code put together.
So, given that my statically typed language has slightly less typing and provides - in this case - an obvious way to do something that presents a problem in the dynamic language, it would seem that dynamic languages no longer have an advantage to offset having to wait for tests to run before you catch type errors. So they will eventually - and given the speed at which this industry adopts new languages, I probably won't live to see the day - dissappear. Or maybe both will disappear before then.
Working example
This is the code I used for the solution to the project euler problem, modified to allow for interactive comparisons. A card is a single digit through 9, then the first letter of the rank (
23456789TJQKA) followed by the first letter of the suit ('SDHC'). A hand is five cards. You enter two hands on a line and hit enter, then the code will figure out the hand types and print them back labelling the winner and loser.
-- show -- /show import Data.Char (isSpace) import Data.List (sortBy, group, delete) import Control.Monad (forever) -- show data Suit = Spades | Hearts | Diamonds | Clubs deriving (Show, Eq) -- /show instance Read Suit where readsPrec _ [] = [] readsPrec p (c:cs) | isSpace c = readsPrec p cs | c == 'S' = [(Spades, cs)] | c == 'H' = [(Hearts, cs)] | c == 'D' = [(Diamonds, cs)] | c == 'C' = [(Clubs, cs)] | otherwise = [] -- show data Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Show, Eq, Ord, Enum) -- /show instance Read Rank where readsPrec _ [] = [] readsPrec p (c:cs) | isSpace c = readsPrec p cs | c == 'A' = [(Ace, cs)] | c == '2' = [(Two, cs)] | c == '3' = [(Three, cs)] | c == '4' = [(Four, cs)] | c == '5' = [(Five, cs)] | c == '6' = [(Six, cs)] | c == '7' = [(Seven, cs)] | c == '8' = [(Eight, cs)] | c == '9' = [(Nine, cs)] | c == 'T' = [(Ten, cs)] | c == 'J' = [(Jack, cs)] | c == 'Q' = [(Queen, cs)] | c == 'K' = [(King, cs)] | otherwise = [] -- show data Card = Card Rank Suit deriving Show -- Eq & Ord can't be derived, since poker ignores suits in hand rankings. instance Eq Card where Card r1 _ == Card r2 _ = r1 == r2 instance Ord Card where Card r1 _ <= Card r2 _ = r1 <= r2 -- /show instance Read Card where readsPrec p cs = do (r, cs1) <- readsPrec p cs (s, cs2) <- readsPrec p cs1 return (Card r s, cs2) -- show -- /show instance Read Hand where readsPrec p cs = do (c1, cs1) <- readsPrec p cs (c2, cs2) <- readsPrec p cs1 (c3, cs3) <- readsPrec p cs2 (c4, cs4) <- readsPrec p cs3 (c5, cs5) <- readsPrec p cs4 return (makeHand [c1, c2, c3, c4, c5], cs5) makeHand :: [Card] -> Hand makeHand cards = let sorted = sortBy (flip compare) cards grouped = sortBy (\a b -> compare (length b) (length a)) $ group sorted Card highOf _ = head . head $ grouped Card nextOf _ = head . head . tail $ grouped isStraight cards = all (\ (a, b) -> a `follows` b) (zip cards (tail cards)) where Card r1 _ `follows` Card r2 _ = r2 == if r1 > Two then pred r1 else Ace in (case length grouped of 5 | all (\ (Card _ a, Card _ b) -> a == b) (zip cards (tail cards)) -> if isStraight sorted then StraightFlush else Flush | isStraight sorted -> Straight | otherwise -> HighCard 4 -> PairOf highOf 3 -> if (length . head) grouped == 3 then ThreeOf highOf else TwoPair highOf nextOf 2 -> if (length . head) grouped == 4 then FourOf highOf else FullHouse highOf nextOf) sorted -- These should be generalized to deal with more than two hands per line. data Deal = Deal {h1, h2 :: Hand} instance Read Deal where readsPrec p s = do (h1, s1) <- readsPrec p s (h2, s2) <- readsPrec p s1 return (Deal h1 h2, s2) main = forever $ do line <- getLine let d = read line :: Deal let (w, l) = if h1 d > h2 d then (h1 d, h2 d) else (h2 d, h1 d) putStrLn $ "Winner: " ++ (show w) putStrLn $ "Loser: " ++ (show l)
The input code isn't very good - I used this as an excuse to learn how to write
Read instances - and it does no error checking, so if you screw up you get a
no parse error and it exits. It was sufficient for the problem, though.
There is a bug that isn't exercised by the project problem. I've left it in for the reader to find as an exercise. | https://www.schoolofhaskell.com/user/mwm/cards | CC-MAIN-2017-26 | refinedweb | 2,870 | 65.46 |
How to round to 2 decimals with Python?
I am getting a lot of decimals in the output of this code (Fahrenheit to Celsius converter).
My code currently looks like this:
def main(): printC(formeln(typeHere())) def typeHere(): global Fahrenheit try: Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n")) except ValueError: print "\nYour insertion was not a digit!" print "We've put your Fahrenheit value to 50!" Fahrenheit = 50 return Fahrenheit def formeln(c): Celsius = (Fahrenheit - 32.00) * 5.00/9.00 return Celsius def printC(answer): answer = str(answer) print "\nYour Celsius value is " + answer + " C.\n" main()
So my question is, how do I make the program round every answer to the 2nd decimal place?
You can use the round function, which takes as first argument the number and the second argument is the precision.
In your case, it would be:
answer = str(round(answer, 2))
From: stackoverflow.com/q/20457038 | https://python-decompiler.com/article/2013-12/how-to-round-to-2-decimals-with-python | CC-MAIN-2020-10 | refinedweb | 158 | 67.15 |
question how to properly implement Telerik OpenAccess in mojoportal. It seems that the best scenario is to place it in OnInit of the MasterPage and dispose it while disposing this page. (As explained HERE)
If the layout.Master.cs would be a partial class I could expand it (but it is not). Is there a simple way of achieving this goal?
Thank you in advance for any suggestions,
Tomasz
for that kind of situation what I would do is copy the code from our App_MasterPages/layout.master.cs into your own project with a new namespace, modify as needed and compile it into your own dll in the bin folder then make the layout.master file inherit from your own instead of ours
That is exactly what I did :) But the problem is that when I synchronize changes from the server I have to remember to copy it again and again - every synchronization. If the class would be partial (why it can not be?) - I could just expand it.
It is not intended for you to compile your own code together with mojoportal code, your code should be in separate projects and compiled into separate dlls of your own.
unless your code changes you don't have to redeploy your dll after it is first deployed so I don't know what you mean about every synchronization, but in any case that is going to have to be a good enough solution.
I mean pulling mojoportal changes from codeplex. In such case that file layout.master.cs may change so I would have to copy this every synchronization.
that file has not changed very often and is not expected to change so I would not worry too much about that
I understand Joe.
Of course your suggestion is good enough and works. I just thought that access to master page by possibility of expanding this class could be very usefull in some cases (like this one for example) and actually it doesn't fork the code.
But in this case I will just monitor potential changes in layout.master.cs and it will also work of course.
Thank you very much for the advice. Mojoportal in general works great :) | https://www.mojoportal.com/Forums/Thread.aspx?pageid=5&t=12834~1 | CC-MAIN-2018-26 | refinedweb | 369 | 71.95 |
Bakaláři
Bakaláři is Dart library that can be used for accessing Bakaweb API. Bakaláři (Bakaweb) is Czech school system. This library allows gathering information like grades, timetable, PMs, or homework.
This library is directly based on vakabus/pybakalib.
If you are at GitHub, the package can be found at pub.dartlang.org.
Install
Open
pubspec.yaml of your project and insert following line into dependencies section:
bakalari: ^0.3.3
Run
pub get and it should install automatically.
Use
Into
main.dart, insert this line:
import 'package:bakalari/bakalari.dart';
Create some async method. Instantiate
Bakalari class and don't forget to log in (
Now, you can call methods like
.getGrades() on the instance.
There are two static methods that can be called without instantiating the library:
getListOfCitites which returns list of cities in which is at least one school using the Bakaláři system, and
getListOfSchools, which returns list of schools using the Bakáláři system in a city.
See example/main.dart for example code.
If you run into problems, create GitHub issue and I'll get into it as soon as possible.
Other community projects
- pybakalib is python library that powers the alternative Bakaweb website, Bakaweb.tk.
- bakalari-api is unofficial documentation of Bakaweb API. Apart from documentation, this organization provides some unofficial apps that use the Bakaweb API.
Libraries
- bakalari
- Package that allows reading data from Czech school system Bakaláři. This unofficial library grants access to data that may be locked in the official app - for example all grades weights.
- bakalari.definitions
- This library contains class definitions for
bakalarilibrary. You need this to be able to use classes used by
bakalarilibrary whitout too much hassle. Just import it and let autocomplete do it's magic. | https://pub.dev/documentation/bakalari/latest/ | CC-MAIN-2020-45 | refinedweb | 287 | 60.11 |
"Printable PDF" Download Fails after Navigating to Dashboard from Actions Menu
Last updated on MAY 03, 2018
Applies to:Oracle Fusion Sales Cloud Service - Version 11.1.11.1.0 and later
Information in this document applies to any platform.
Symptoms
On : 11.1.11.1.0 version, Analytics
Unable to save a PDF locally within Sales Cloud from an embedded report using Google Chrome.
Google Chrome being used: version 53.0.2785.143 m
Up until recently, you were able to save PDFs locally from Google Chrome.
Now, you receive error "Failed - Network Error". This works fine in Internet Explorer and in Mozilla Firefox browsers.
The flow is as follows: Customers Object --> Actions (menu) --> Click menu link to Dashboard --> (Dashboard page opens) --> click Print at bottom of Dashboard page --> click "Printable PDF" --> Chrome prompts you to save file --> Choose file location --> Save.
ERROR
-----------------------
"Network Error" appears in Chrome Download notification in Downloads bar at the bottom of the Chrome window.
STEPS
=======================================
The issue can be reproduced at will with the following steps:
1. In Application Composer, under Account > Actions and Links, create a new Action.
2. On the "Edit Action or Link" page, configure the Action as follows:
----------------------------------------------------
Display Label: (Action display label)
Name: (Action name)
Type: Action
Description: [blank]
Source: URL (greyed out)
Display Mode: New Window (greyed out)
Context Object: Organization
SCRIPT:
=======================================
def JWTtoken = (new oracle.apps.fnd.applcore.common.SecuredTokenBean().getTrustToken())
def url = '../BIProxy'
url += '?cid=BIPresentationServer&RedirectURL=saw.dll?Dashboard'
url += '&PortalPath=/shared/Custom/.../DashboardName
url += '&Page=PageName'
url += '&Action=Navigate'
url += '&var1=dashboard.variables[%27JWT%27]'
url += '&val1="' + JWTtoken + '"'
println("URL is: ${url}")
return url;
=======================================
3. In Application Composer, navigate to the target Standard object's Pages area. (E.g. Account > Pages).
4. Click "Edit Summary Table"
5. Under Actions, move "Action Name" into the Selected Actions.
6. Save and Close.
7. In SUI, navigate to the Summary table of Account.
8. Under Actions > click 'Action Name'
9. Scroll to the bottom of the report, where the Print/Export buttons appear.
10. Click Print > Printable PDF.
11. Note the "Network Error" when trying to download the PDF.
12. Note that the Printable PDF can be downloaded without issue when accessed directly from within OBIEE.
BUSINESS IMPACT
----------------------------
Users cannot download the Dashboard page as PDF for offline use.
Changes
Chrome update
Cause
My Oracle Support provides customers with access to over a
Million Knowledge Articles and hundreds of Community platforms | https://support.oracle.com/knowledge/Oracle%20Cloud/2189349_1.html | CC-MAIN-2018-22 | refinedweb | 405 | 58.58 |
There is a connected graph G(V, E) and the weight or cost for every edge is given. Prim’s Algorithm will find the minimum spanning tree from the graph G.
It is a growing tree approach. This algorithm needs a seed value to start the tree. The seed vertex is grown to form the whole tree.
The problem will be solved using two sets. One set holds the nodes that are already selected, and another set holds the item those are not considered yet. From the seed vertex, it takes adjacent vertices, based on minimum edge cost, thus it grows the tree by taking nodes one by one.
The time complexity of this problem is O(V^2). Here V is the number of vertices.
Input: The adjacency list:
Output: (0)---(1|1) (0)---(2|3) (0)---(3|4) (1)---(0|1) (1)---(4|2) (2)---(0|3) (3)---(0|4) (4)---(1|2) (4)---(5|2) (5)---(4|2) (5)---(6|3) (6)---(5|3)Output: (0)---(1|1) (0)---(2|3) (0)---(3|4) (1)---(0|1) (1)---(4|2) (2)---(0|3) (3)---(0|4) (4)---(1|2) (4)---(5|2) (5)---(4|2) (5)---(6|3) (6)---(5|3)
prims(g: Graph, t: tree, start)
Input − The graph g, A blank tree and the seed vertex named ‘start’
Output − The Tree after adding edges.
Begin define two sets as usedVert, unusedVert usedVert[0] := start and unusedVert[0] := φ for all vertices except start do usedVert[i] := φ unusedVert[i] := i //add all vertices in unused list done while number of vertices in usedVert ≠ V do //V is number of total nodes min := ∞ for all vertices of usedVert array do for all vertices of the graph do if min > cost[i,j] AND i ≠ j then min := cost[i,j] ed := edge between i and j, and cost of ed := min done done unusedVert[destination of ed] := φ add edge ed into the tree t add source of ed into usedVert done End
#include<iostream> #define V 7 #define INF 999 using namespace std; //Cost matrix of the graph int costMat[V][V] = { {0, 1, 3, 4, INF, 5, INF}, {1, 0, INF, 7, 2, INF, INF}, {3, INF, 0, INF, 8, INF, INF}, {4, 7, INF, 0, INF, INF, INF}, {INF, 2, 8, INF, 0, 2, 4}, {5, INF, INF, INF, 2, 0, 3}, {INF, INF, INF, INF, 4, 3, 0} }; typedef struct { int u, v, cost; }edge; class Tree { int n; edge edges[V-1]; //as a tree has vertex-1 edges public: Tree() { n = 0; } void addEdge(edge e) { edges[n] = e; //add edge e into the tree n++; } void printEdges() { //print edge, cost and total cost int tCost = 0; for(int i = 0; i<n; i++) { cout << "Edge: " << char(edges[i].u+'A') << "--" << char(edges[i].v+'A'); cout << " And Cost: " << edges[i].cost << endl; tCost += edges[i].cost; } cout << "Total Cost: " << tCost << endl; } friend void prims(Tree &tre, int start); }; void prims(Tree &tr, int start) { int usedVert[V], unusedVert[V]; int i, j, min, p; edge ed; //initialize usedVert[0] = start; p = 1; unusedVert[0] = -1; //-1 indicates the place is empty for(i = 1; i<V; i++) { usedVert[i] = -1; //all places except first is empty unusedVert[i] = i; //fill with vertices } tr.n = 0; //get edges and add to tree while(p != V) { //p is number of vertices in usedVert array min = INF; for(i = 0; i<p; i++) { for(j = 0; j<V; j++) { if(unusedVert[j] != -1) { if(min > costMat[i][j] && costMat[i][j] != 0) { //find the edge with minimum cost //such that u is considered and v is not considered yet min = costMat[i][j]; ed.u = i; ed.v = j; ed.cost = min; } } } } unusedVert[ed.v] = -1; //delete v from unusedVertex tr.addEdge(ed); usedVert[p] = ed.u; p++; //add u to usedVertex } } main() { Tree tr; prims(tr, 0); //starting node 0 tr.printEdges(); }
(0)---(1|1) (0)---(2|3) (0)---(3|4) (1)---(0|1) (1)---(4|2) (2)---(0|3) (3)---(0|4) (4)---(1|2) (4)---(5|2) (5)---(4|2) (5)---(6|3) (6)---(5|3) | https://www.tutorialspoint.com/Prim-s-Minimum-Spanning-Tree-Algorithm | CC-MAIN-2021-21 | refinedweb | 697 | 75.34 |
Hi,On Wed, Jul 6, 2016 at 10:55 AM, Kees Cook <keescook@chromium.org> wrote:> On Wed, Jul 6, 2016 at 2:53 AM, Olof Johansson <olof@lixom.net> wrote:>> Add a separate Kconfig option for SAMPLES_SECCOMP.>>>> Main reason for this is that, just like other samples, it's forced to be a module.>>>> Without this, since the sample is a target only controlled by>> CONFIG_SECCOMP_FILTER, the samples will be built before include files are>> put in place properly. For example, from an arm64 allmodconfig built with>> "make -sk -j 32" (without specific target), the following happens:>>>> samples/seccomp/bpf-fancy.c:13:27: fatal error: linux/seccomp.h: No such file or directory>> samples/seccomp/bpf-helper.h:20:50: fatal error: linux/seccomp.h: No such file or directory>> samples/seccomp/dropper.c:20:27: fatal error: linux/seccomp.h: No such file or directory>> samples/seccomp/bpf-direct.c:21:27: fatal error: linux/seccomp.h: No such file or directory>> Ah-ha! Yes, that's ugly.>>> So, just stick to the same format as other samples.>> Agreed, that makes sense to me.>>>>> Signed-off-by: Olof Johansson <olof@lixom.net>>> --->> samples/Kconfig | 7 +++++++>> samples/seccomp/Makefile | 2 +->> 2 files changed, 8 insertions(+), 1 deletion(-)>>>>>> Hi Kees,>>>> This has been showing up for a while on my builder, and I finally had>> a bit of time to sit down and look at it.>>>> It'd be nice to see this in 4.7, but please consider for 4.8 at the least.>>>>>> Thanks!>>>> -Olof>>>> diff --git a/samples/Kconfig b/samples/Kconfig>> index 559a58b..ccc50be 100644>> --- a/samples/Kconfig>> +++ b/samples/Kconfig>> @@ -85,4 +85,11 @@ config SAMPLE_CONNECTOR>> with it.>> See also Documentation/connector/connector.txt>>>> +config SAMPLE_SECCOMP>> + tristate "Build seccomp sample code -- loadable modules only">> + depends on SECCOMP_FILTER && m>> + help>> + Build samples of seccomp filters using various methods of>> + BPF filter construction.>> +>> endif # SAMPLES>> diff --git a/samples/seccomp/Makefile b/samples/seccomp/Makefile>> index 1b4e4b8..ae7ff6f 100644>> --- a/samples/seccomp/Makefile>> +++ b/samples/seccomp/Makefile>> @@ -1,7 +1,7 @@>> # kbuild trick to avoid linker error. Can be omitted if a module is built.>> obj- := dummy.o>> Can the above two lines be dropped now since it'll always be a module?Actually, they can't, since the only other target is a hostprogs one.Still needs a dummy module object file.-Olof | https://lkml.org/lkml/2016/7/7/609 | CC-MAIN-2021-04 | refinedweb | 398 | 53.07 |
Introduction - location.
Here we will see some basics of what are pointer variable, reference variable, and a normal variable.
A simple pointer and reference to a variable
A variable is declared as follows:
int x;
Here,
X is the variable name
int specified the type of data that can be stored in x.
Let us assume that the variable shown above is declared in the void main of the program. The variable scope is inside the main and we know that the variable occupies some memory in the call stack of main. Now the x is a naming given to the location in the stack that is allocated by the void main function. Using the assignment operator and the variable x the location is accessed. So the address involved is hidden behind the scene and all you know is variable name x and internally is has an association to a location in the stack memory of the main function.
Now have a look at the variable declaration below:
int& refto_x = x;
Here,
refto_x is reference variable and that references the variable x. Int& specifies the reference notation and reference to what data type.
The reference variable should be initialized when it is declared. See… in our example statement we declared a reference variable refto_x and initialized it with the assignment = x. What does that say? Well. X is a naming notation used internally to read or write from a specific memory location in a stack (When x is not a global variable and declared inside some function) and simply it is a variable declared already. And refto_x is a naming notation for the naming x. That means refto_x is simply one more naming given to the location represented by the variable x.
Now look at the statement below:
int * pointerto_x = &x;
Here,
int * - Represents pointer to an integer
pointerto_x – A variable name given to the pointer variable
&x – Address of the variable x.
In the above declaration, a pointer variable pointerto_x is declared and at the same time initialized to have the address of the variable x. Note that in the above statement unlike reference it is not just one more name to the location represented by x. It has it own location represented by a variable pointerto_x and that location can store address location and when it access that location it treats that address location to read or write integer sized data.
Basic explanation for reference and pointers
Let us explore the pointer, reference and a normal variable with an example. Consider the below four statements:
int _tmain(int argc, _TCHAR* argv[])
{
//Declare an integer variable, then have a pointer and reference to it
int x;
int& refto_x = x;
int * pointerto_x = &x;
x = 10;
}
First, we declared an integer variable x and then had a reference to it in the variable refto_x. Then the pointer variable pointerto_x is declared and initialized to hold the address of the variable x. Finally, we assigned value 10 to the variable x. Have a look at the below picture:
The above three variable creation and assignment of value 10 is depicted as above. First, to store the value 10 we need some bits in memory. Second as the variable x is declared inside the _tmain () function and value 10 is assigned to the variable x, memory in the stack holds the value 10. To read or write from this memory location we use the variable x.
Read:
p = x + 15;
In the above statement, the value in the stack memory identified by the variable x is read then assigned to variable p after summing it with a value 15.
Write:
x = p - 10;
In the above statement the value in p is decremented by 10 then written to the memory location identified by the variable x.
So, according to x, the read or write operation defined by the variable x and it position in relation to the assignment operator =. C++ developers call the variable name and its corresponding memory location as naming association.
Now explaining the reference is easy. In our example statements above, refto_x is just one more naming association to the same stack memory. That means x and refto_x both corresponds to the same memory in the stack. What about pointerto_x? It stores the address of the memory location for x or refto_x.
The above four statements can further explained in detail by using the below depiction:
1. FE100B12: Memory address of stack that holds value 10
2. FF820CD7: Again, memory address of stack that holds address of some other memory in stack (32 bit address or 64 bit address)
3. Variable x is associated to the memory location FE100B12
4. Variable refto_x is also associated to the memory location FE100B12
5. Variable pointerto_x is associated to the memory location FF820CD7
Note that x, refto_x and pointerto_x all declared inside the main () and have an association to the stack memory. I will talk about heap later and that is different.
The value in the location is shown above. If you just read the content of the pointer variable pointerto_x, then you will get memory location of the variable. To read the content, you should de-reference the pointer.
int m = * pointerto_x;
In the above statement we specifed that we do not want the content of pointerto_x (Which is an address), But we want the actual value in the address which stored in the pointerto_x.
Code and Example
Below is the complete example and output:
#include "stdafx.h"
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
//Declare an integer variable, then have a pointer and reference to it
int x;
int& refto_x = x;
int * pointerto_x = &x;
//Assing a value to x and print the value in it using value, refernce and pointer
x = 10;
printf("X=%d\n", x);
printf("Value in x through refto_x=%d\n", refto_x);
printf("Value in x tnrough pointerto_x=%d\n", *pointerto_x );
//Now check the address of all the three variables
printf("********* Adress of Value, reference, pointer variables *********\n");
printf("Address of x=%d\n", &x);
printf("Address of refto_x=%d\n", &refto_x);
printf("Address of pointerto_x=%d\n", &pointerto_x );
//Special case
printf("Then what is stored in pointerto_x? It is %d, address of x", pointerto_x);
getch();
return 0;
}
Output
Leave your comment(s) here. | http://www.mstecharticles.com/2011/10/c-reference-vs-pointers.html | CC-MAIN-2017-17 | refinedweb | 1,049 | 59.53 |
DEM Examples
Collision of 2 particlesThis tutorial aims to build the simulation for 2 bodies colliding in an elastic way. The user declares a sphero-cube and a sphero-tetrahedron in a collision course. The energy, liner and angular momenta can be measured to check these conservation laws. The whole simulation is described in the following code which will be explained in detail:
// MechSys #include <mechsys/dem/domain.h> int main(int argc, char **argv) try { DEM::Domain dom; // add cube Vec3_t x(-10,0,0); Vec3_t v(1.,0,0); Vec3_t w(0,M_PI/5,0); dom.AddCube (/*Tag*/-1, /*Position*/x,/*SpheroRadius*/0.3,/*Length*/3.,/*Density*/1.); dom.Particles[0]->v = v; dom.Particles[0]->w = w; // add tetrahedron x = 10.0, 0 , 0; w = 0.0, 0 , M_PI/10.; v = -1.0, 0 , 0; dom.AddTetra (/*Tag*/-1, /*Position*/x,/*SpheroRadius*/0.5,/*Length*/5.,/*Density*/1.); dom.Particles[1]->v = v; dom.Particles[1]->w = w; // particle parameters Dict D; D.Set(-1,"Gn Gt Mu",0.0,0.0,0.0); dom.SetProps(D); // initial constants Vec3_t l0; Vec3_t p0; double Ek0,Ep0,E0; dom.LinearMomentum (p0); dom.AngularMomentum (l0); E0 = d.CalcEnergy (Ek0,Ep0); // solve dom.CamPos = 0.0,30.0,0.0; dom.Solve(/*tf*/30.0, /*dt*/1.0e-4, /*dtOut*/0.3, NULL, NULL, /*filekey*/"test_dynamics"); // final constants Vec3_t l1; // initial linear momentum Vec3_t p1; // initial angular momentum double Ek1,Ep1,E1; // initial energy dom.LinearMomentum (p1); dom.AngularMomentum (l1); E1 = dom.CalcEnergy (Ek1,Ep1); // check; // results if (error > tol) return 1; else return 0; } MECHSYS_CATCH
Initialization
MechSys/DEM simulations are prepared with a C++ source code. The first step is to include the required MechSys libraries. In this case the file domain.h contains the DEM domain definitions:
#include <mechsys/dem/domain.h>
Simulation script structure
The simulation script structure is:
#include ... int main(int argc, char **argv) try { ... } MECHSYS_CATCH
After including the required MechSys' libraries (and C++ standard libraries, if necessary), the
main
function is declared.
For MechSys, it is important to add the
try keyword just after
the
int main() and before the first opening brace
{. Then, after the last closing
brace the
MECHSYS_CATCH is added.
Declaring the DEM Domain and Particles
The line,
DEM::Domain d;
declares the container
dom of the class
DEM::Domain. This class defines the DEM universe and also has many functions
to include particles, some of which will be used in this tutorial.
To declare the cube, some 3D vectors are needed. The
Vec3_t data type is used
for fast vectorial operations:
Vec3_t x(-10,0,0); Vec3_t v(1.,0,0); Vec3_t w(0,M_PI/5,0);
The vectors
x
v
w
define respectively the cube center position, its linear velocity and its angular velocity. The declared angular velocity ensures that the cube will
spin around the y-axis counter clockwise. Once these three vectors are declared, the cube is introduced into the domain:
dom.AddCube (/*Tag*/-1, /*Position*/x,/*SpheroRadius*/0.3,/*Length*/3.,/*Density*/1.);
This function creates a cube into the memory. The first argument is a Tag which will be useful later on. The second is the position vector declared above. Next is the Sphero-Radius which is the radius of the rounded corners, and is required for the collision law. Ideally this spheroradius should be large enough so the overlapping between the colliding particles is small compared to the particles dimensions. The 4th argument is the length of the cube's edges and finally the density of the cube is also declared.
The method, however, initializes the particle at rest and without rotation. Therefore, to add the vector velocities, internal variables must be accessed:
dom.Particles[0]->v = v; dom.Particles[0]->w = w;
The object
dom.Particles is an array that contains the memory pointers to all the particles created in the domain
dom. To access
the first particle, which is the cube, the index
0 must be introduced. Therefore
dom.Particles[0] is a pointer to the cube. The internal vector variables
v and
w are the cube's linear and angular velocity vectors.
In a similar way the tetrahedron is included at the right side of the cube moving towards it:
x = 10.0, 0 , 0; w = 0.0, 0 , M_PI/10.; v = -1.0, 0 , 0; dom.AddTetra (/*Tag*/-1, /*Position*/x,/*SpheroRadius*/0.5,/*Length*/5.,/*Density*/1.); dom.Particles[1]->v = v; dom.Particles[1]->w = w;
With both particles properly defined, some collision parameters must be set. MechSys uses the spheropolyhedra method to model the collision of
solid objects. The collision law is defined by two spring constants
Kn and
Kt; two dissipative constants
Gn and
Gt; and a friction coefficient μ. Since this simulation deals with an elastic collision, the
two dissipative constants and the friction coefficient must be set to zero. In MechSys this is achieved by the use of dictionaries as follows:
Dict D; D.Set(-1,"Gn Gt Mu",0.0,0.0,0.0); dom.SetProps(D);
Where the dictionary
D contains the user information on the new parameters. The first argument of the
function
D.Set is the particle's tag. Hence different groups of particles can be associated with different
collision parameters. The elastic parameters
Kn and
Kt (as
Kn and
Kt in the dictionary string) can also be included into the dictionary, however for this example we will work
with their default values.
Starting the simulation
To check the conservation laws some values must be calculated before the simulation starts:
Vec3_t l0; Vec3_t p0; double Ek0,Ep0,E0; dom.LinearMomentum (p0); dom.AngularMomentum (l0); E0 = d.CalcEnergy (Ek0,Ep0);
The vectors
l0 and
p0 will store the linear and angular momenta given by the functions
dom.LinearMomentum and
dom.AngularMomentum. The three numbers
Ek0,
Ep0 and
E0 will be respectively the total kinetic energy, the
total potential energy and the total energy as given by the function
dom.CalcEnergy. This variable will be kept in memory to be compared with the situation after the simulation.
With the DEM universe defined, the simulation will begin. First, for future visualization, is useful to define the position of a camera:
dom.CamPos = 0.0,30.0,0.0;
Then the system evolves for as long as defined by the user by means of the
dom.Solve:
dom.Solve(/*tf*/30.0, /*dt*/1.0e-4, /*dtOut*/0.3, NULL, NULL, /*filekey*/"test_dynamics");
The system will evolve in this case up to
tf = 30.0 seconds of simulation time. The next
argument is the integration time step
dt, the smaller the more accurate the simulation is but also the more
time consuming. The 3rd argument is the report time step, in other words, the time span between movie frames. The next two arguments are
pointers to functions which are not explained in this simple example. This functions may be called from inside the Solve function, and hence offer
some control over the evolution of the system from outside. Finally, the last argument is a file key which is used to identify the report and
animation files form this simulation.
At the end of the simulation, the same variables that were measured before it are measured again:
Vec3_t l1; Vec3_t p1; double Ek1,Ep1,E1; dom.LinearMomentum (p1); dom.AngularMomentum (l1); E1 = d.CalcEnergy (Ek1,Ep1);
And compared with their initial values:;
After compiling and running, the simulation should give this results
Error in energy = 0.128839 Error in angular momentum = 0.000122599 Error in linear momentum = 8.30147e-10
Unfortunately the conservation laws are not exactly met in the DEM and therefore there is a difference between the initial and final values. As mentioned before this error can be tuned down with the integration time step
Simulation visualization
MechSys uses VisIt to visualize simulation results. A full tutorial can be found here. After following the instructions the dynamics of the system should resemble the following video: | https://mechsys.nongnu.org/DEMexample01.html | CC-MAIN-2022-05 | refinedweb | 1,332 | 51.34 |
Getting Started With Styletron
Styletron is a toolkit for component-oriented styling comprising of
CSS in
JavaScript flavouring. It’s great for
React apps but you can use it elsewhere too!
What’s CSS in JS? permalink
It’s exactly that. Defining your styling within
JavaScript. The major benefit being that we can abstract styling to the component level.
javascript
const Button = styled('button', { background: '#276EF1', color: '#FFFFFF', cursor: 'pointer' })
You also get the full power of
JavaScript within your styling. Global class name pollution or creating bloated style sheets are no longer a concern 🙌
There are some great resources about
CSS in
JS. Here’s a great speaker deck about
CSS in
JS. It’s almost 5 years old but the concepts still hold true 👍
There are many
CSS in
JS libraries available. Each have their own take on how
CSS in
JS should be.
Styletron is one of those libraries. Valerii Sorokobatko has curated some of the popular options.
Styletron permalink! 🚀
The above graphic is from Ryan Tsao's “Virtual CSS with Styletron”
With
Styletron, you gain the benefit of atomic
CSS without the overhead. You write your styles, it does the utility class part for you! It’s atomic
CSS from
JS.
Example permalink
Let’s go through some features with an example. The “Hello World” of components tends to be the button. Let’s create a
Button component with
Styletron.
The Basic Button permalink
javascript
const Button = styled('button', { background: '#276EF1', color: '#FFFFFF', cursor: 'pointer' })
That’s our basic
Button.
It is not very special. Let’s make something different for this demo 🤓
How about something like this.
Creating a fancier Button permalink
Let’s start by styling the foundation for our
Button. Nothing special happening here.
javascript
const Button = styled('button', { background: 'transparent', border: '4px solid #276EF1', borderRadius: '4px', color: '#276EF1', cursor: 'pointer', fontWeight: 'bold', padding: '8px 16px', position: 'relative' }) though.
javascript
const Button = styled('button', { background: 'transparent', border: '4px solid #276EF1', borderRadius: '4px', color: '#276EF1', cursor: 'pointer', fontWeight: 'bold', padding: '8px 16px', position: 'relative', '.
javascript
const Button = styled('button', props => ({ ':after': { content: `"${props.children}"`, } }))
As we are copying styles to the pseudo element, we can extract these into a variable and spread them.
javascript
const buttonStyles = {...} const Button = styled('button', props => ({ ...buttonStyles, ':after': { ...buttonStyles, background: '#276EF1', border: 0, bottom: 0, borderRadius: 0, color: '#FFFFFF', content: `"${props.children}"`, left: 0, position: 'absolute', right: 0, top: 0, } }))
Let’s create that
clip-path for our fancy effect.
javascript
const Button = styled('button', props => ({ ...buttonStyles, ':after': { ...buttonStyles,! 🙌
Theming permalink
Most buttons come in a variety of colors, think
Bootstrap etc. We can do this with theming. To use themes with
Styletron, we create a new
styled function using
React Context ⚛️
javascript
import React, { createContext } from 'react' import { createStyled } from 'styletron-react' import { driver, getInitialStyle } from 'styletron-standard' const { Consumer, Provider } = createContext() const THEME = { colors: { PRIMARY: '#276EF1', SECONDARY: '#95A5A6' } }.
javascript
const getButtonColor = props => { const { colors } = props.$theme; let color = colors.PRIMARY; if (props.$primary) color = colors.PRIMARY; if (props.$secondary) color = colors.SECONDARY; return color; };
Integrating the functions like so.
javascript
const Button = styled('button', props => { const color = getButtonColor(props) const styles = getButtonStyles(color) return { ...styles, ':after': { ...styles, ...otherStyles }, ':hover:after': { ...hoverStyles } } })
Will give us themed buttons!
Special props permalink
Styletron also exposes two special props you can use on your components.
$as will render the underlying component as a different HTML element.
javascript
<Button $ Check out Styletron! </Button>
It’s common to see developers want to render an anchor that looks like a button. We could create a
Styletron anchor using our
Button component.
The other prop is
$ref. This works the same as the
ref you will be familiar with. All you need do, is replace instances of
ref with
$ref where you are using a
Styletron component.
Pitfalls and Drawbacks permalink
Although there are some, none of these should deter you from using
Styletron. There’s no way to select descendants or use combinators such as
>,
~,
+ etc. This is not a draw back though. Component design should mitigate this.
There’s no value fallback for properties (Yet 🙂*)*.
Don’t mix shorthand and longhand properties. You can use both but don’t combine them. There’s no guarantee what will take precedence.
javascript
// DON'T DO THIS border: '4px solid blue', borderWidth: '10px' // DO EITHER THIS border: '10px solid blue' // OR THIS borderColor: 'blue', borderStyle: 'solid', borderWidth: '10px'
It’s also worth noting that any media queries will reorder in a mobile first fashion.
javascript
// THIS screen and (min-width: 1200px) screen and (min-width: 768px) // BECOMES THIS screen 💪 (These are currently at the PR stage)
Conclusion permalink.
Be sure to check out the concepts.
And have a play with the demo code | https://jhey.dev/writing/getting-started-with-styletron/ | CC-MAIN-2021-31 | refinedweb | 787 | 59.9 |
On a simliar note, I was just about to post an XML problem I had using
regular Python XML (minidom).
<myconfig>
mod_python version = 3.1.3
Apache version = 2.0.52
python version = 2.4
</myconfig>
...
from xml.dom import minidom
xmldoc = minidom.parse(myFile.xml)
...
After analyzing the logs files, I find segmentation faults occurring causing
the page to hand and never get displayed. I have tested this on two
separate systems and the results are the same.
I will try the methods described above and see what happens.
~= Chris =~
On Wed, 26 Jan 2005 18:36:40 -0500, Graham Dumpleton
<grahamd at dscpl.com.au> wrote:
>?
>
> The xmlrpclib module uses a Python XML module which looks like it tries
> to use expat.
>
> >>> import xmlrpclib
> >>> import sys
> >>> sys.modules.keys()
> ['cStringIO', 'copy_reg', 'sre_compile', '_sre', 'site', '__builtin__', 'xml.parsers.expat', 'xml._xmlplus', 'xml.parsers', 'xml.sys', '__main__', 'operator', 'xml.parsers.pyexpat', 'xml', 'posixpath', 'base64', 'binascii', 'pyexpat.errors', 'sre_constants', 're', 'os.path', 'stat', 'zipimport', 'string', 'warnings', 'UserDict', '_xmlplus', 'sys', 'readline', 'types', 'strop', 'sre', 'signal', 'xmlrpclib', 'linecache', 'posix', 'pyexpat.model', 'time', 'exceptions', 'sre_parse', 'os']
>
> It is a frequent problem that the version of the expat shared library which
> is used by the Python modules differs to that which Apache or PHP may
> already be using. This difference can result in a server crash.
>
> You should thus try to determine if you have multiple versions of expat
> present and whether these different packages are using different versions.
>
> On Linux, you might be able to use "ldd" to work this out by running it
> on the " binary, as well as the appropriate .so Python module.
>
> ldd /somepath-to-apache-bin-dir/
> ldd /somepath-to-python-module-dir/lib-dynload/pyexpat.so
> ldd /somepath-to-apache-module-dir/*php*.so
>
> The paths will need to be adjusted obviously.
>
> Please post the results of ldd if you can as am curious to see if this
> does help, I have never suggested trying it before.
>
> Graham
> _______________________________________________
> Mod_python mailing list
> Mod_python at modpython.org
>
> | https://modpython.org/pipermail/mod_python/2005-January/017252.html | CC-MAIN-2022-21 | refinedweb | 337 | 60.01 |
I have some cpp code that is looping through an array of char looking for a delimiter. The code saves the chars in a string until it finds the delimiter, then it adds the string to a vector of string and continues processing.
The input char array is,
Cl.N1C=CC=N1.HCl
the delimiter is '.', so the parsed strings should be,
Cl
N1C=CC=N1
HCl
The code seems to work find for the first two strings, but then it seems to stop and not find the third string.
This is the code,
The output from he above is,The output from he above is,Code:
#include <iostream>
#include <vector>
#include <string>
extern "C" { int parse_string_test_( char *INP_PASS, int *LENGTH); }
int parse_string_test_( char *INP_PASS, int *LENGTH ) {
vector<string> found_fragments;
string temp_read;
int i, passed_length;
// number of occupied positions in passed char array
passed_length = *LENGTH;
// print initial values
cout << "char array" << endl;
cout << "LENGTH " << passed_length << endl;
for(i=0; i<passed_length; i++) { cout << INP_PASS[i]; }
cout << endl;
cout << endl;
// parse char array into strings using . as delimiter
for(i=0; i<passed_length; i++) {
// add characters to temp_read until delimiter is found
if(INP_PASS[i] != '.') {
temp_read.push_back(INP_PASS[i]);
}
// when delimiter is found
else if(INP_PASS[i] == '.') {
// add temp read string to vector of string
found_fragments.push_back(temp_read);
cout << "temp_read " << found_fragments.size() << endl;
cout << temp_read << endl;
// clear temp read structure to continue looking for next string
temp_read.clear();
}
}
return 0;
}
char array
LENGTH 16
Cl.N1C=CC=N1.HCl
temp_read 1
Cl
temp_read 2
N1C=CC=N1
...then nothing. The function returns to the calling code, but may not have returned normally, it is hard to tell.
This appears to work up to a point, but does not find the last string HCl. The size of the char array that is passed to the functions prints as correct (16), so the for loop should process all 16 characters in the array. I don't see here why it stops.
This was compiled using g++-3. Some of the unusual syntax results from this being a cpp function that is called from fortran. The char array that is passed to the cpp prints as correct and has the correct size, so I don't think that is part of the problem.
Any suggestions,
Thanks,
LMHmedchem | http://forums.codeguru.com/printthread.php?t=536793&pp=15&page=1 | CC-MAIN-2018-09 | refinedweb | 383 | 71.65 |
In addition to the common operators for addition, subtraction, multiplication, and division, the Python standard library includes some arithmetic operators you may be less familiar with. In this post I'm going to talk about the modulo (
%) and floor division (
//) operators, and some common pitfalls associated with them.
What do modulo and floor division do?
Modulo
The modulo operator is used to carry out Euclidean division. You almost certainly learnt about Euclidean division in school, even if you didn't know what it was called.
When performing Euclidean division, you start with a dividend (a number you want to divide), and a divisor (the number you want to divide the dividend by). Let's say
10 and
3.
In what we might think of as "standard division" the result of
10 / 3 is
3.333 recurring, or
3 and a third. In Euclidean division, we don't care about numbers after the decimal point. We care about the whole number result of the division (in this case
3), which is called the quotient. The amount left over after the division is called the remainder, which in this case is
1.
To give you another example,
11 / 3 gives us a quotient of
3 and a remainder of
2.
In Python, the modulo operator simply yields the remainder:
>>> 10 % 3 1 >>> 11 % 3 2
Floor division
Floor division is also used to carry out Euclidean division, but unlike the modulo operator, floor division yields the quotient, not the remainder.
Let's look at a couple of examples:
>>> 10 // 3 3 >>> 9 // 2 4
We can create a small function to print out the full result of Euclidean division like so:
def euclidean_division(x, y): quotient = x // y remainder = x % y print(f"{quotient} remainder {remainder}") euclidean_division(10, 3) # 3 remainder 1 euclidean_division(11, 3) # 3 remainder 2
There is a problem, however. What happens when we call our function with negative numbers?
>>> euclidean_divison(10, -3) -4 remainder -2
That doesn't look right.
-3 multiplied by
-4 equals
12, which is higher than
10. The result we should have gotten was
-3 remainder
1. So what's going on?
It's floor division's fault
The picture I painted for you earlier about Euclidean division is not entirely accurate. For positive integers, floor division and modulo work exactly like Euclidean division, but things get more complicated when it comes to negative numbers.
The reason for this is to do with rounding. If we look at the Python documentation for arithmetic operators we find a clue about what is going on:
[T]he result [of floor division] is that of mathematical division with the ‘floor’ function applied to the result.
Okay, so let's look at the documentation for the
floor function.
Return the floor of x, the largest integer less than or equal to x.
And there's the problem.
-4 is considered less than
-3.333 recurring. It's further left on the number line. This means that floor division will always round away from zero for negative numbers, but towards zero for positive numbers.
>>> 10 // 3 3 # 3.333 rounds towards zero >>> 10 // -3 -4 # -3.333 rounds away from zero >>> 9 // 2 4 # 4.5 rounds towards zero >>> 9 // -2 -5 # -4.5 rounds away from zero
So what's the problem with modulo?
We've figured out why we're getting unexpected results from floor division and negative numbers, but our remainder was also not what we expected. So why is that?
It turns out that modulo and floor division are closely connected operators, which you may have read if you looked a little further in the documentation. Modulo and floor division are connected by the following identity:
x = (x // y) * y + (x % y).
This means that the result of floor division has a direct impact on the result of a modulo operation. We can rearrange the above like so:
(x % y) = x - (x // y) * y.
Let's try one of our earlier examples,
10 % -3:
10 % 3 = 10 - (-3) * (10 // -3) 10 % 3 = 10 - (-3) * (-4) # Remember, here floor division rounds away from zero 10 % 3 = 10 - 12 10 % 3 = -2
And we get the exact same result we got before:
10 % 3 = -2.
A few final notes
In this final section, I just want to mention a few other interesting things about modulo and floor division. Before I go into that, however, I think it's important to note that the implementation of floor division and modulo in Python isn't a bug. However, I do think it's important to understand when and how implementations like this differ from our intuitive understanding, because then we can use this implementation as a tool, and it stops being a source of perhaps frustrating bugs.
Type conversion
One of the interesting things about floor division in Python is that it doesn't necessarily produce a floating point number. In fact, in all of our examples, the result was an integer. This is completely different to standard division in Python, which always yields a float.
The modulo operator works the same way, yielding an integer if both operands were integers.
If either operand is a float, both modulo and floor division will yield a floating point number.
Using floats
While the examples in this post have all been integers, it's perfectly possible to use floating point numbers for either operand, and they work exactly the same, they simply yield a floating point number.
An example from the documentation is
3.14 % 0.7, which will yield
0.34.
Complex numbers
Complex numbers are numbers with a real and imaginary part. They're only worth noting here because neither modulo nor floor division can accept a complex number as an operand. Trying to use a complex number for floor division or modulo operations will raise a
TypeError.
Recap
- For positive numbers floor division and modulo work like Euclidean division, yielding the quotient and remainder respectively.
- For negative numbers, both operations will yield slightly unexpected results.
- Floor division always rounds away from zero for negative numbers, so
-3.5will round to
-4, but towards zero for positive numbers, so
3.5will round to
3.
- Floor division and modulo are linked by the following identity,
x = (x // y) * y + (x % y), which is why modulo also yields unexpected results for negative numbers, not just floor division. | https://blog.tecladocode.com/pythons-modulo-operator-and-floor-division/ | CC-MAIN-2019-26 | refinedweb | 1,066 | 54.73 |
SYNOPSIS
#include "write_log.h"
int wlog_open(struct wlog_file *wfile, int trunc, int mode);
int wlog_close(struct wlog_file *wfile);
int wlog_record_write(struct wlog_file *wfile, struct wlog_rec *wrec, long offset);
int wlog_scan_backward(struct wlog_file *wfile, int nrecs, int (*func)(struct wlog_rec *rec), long data);
char *Wlog_Error_String;
DESCRIPTION
The write_log package is a set of routines for creating a history file of write operations done to a set of files.
It is assumed that the actual pattern written to the file will be repeated occurrences of a string whose length is no greater than WLOG_MAX_PATTERN. See the pattern(3) man page for routines to conveniently generate buffers of this kind.
wlog_open() initializes the history file contained in wfile->w_file, and fills in the wfile structure. If trunc is non-zero, and existing history file by the same name will be truncated. If no history file exists, it will be created with the specified mode.
wlog_close() releases any resources associated with the given wfile. Use of wfile after this point is undefined until it is initialized again with wlog_open().
wlog_record_write() is the main routine for putting a wlog_rec into the history file. The caller is responsible for supplying a fully initialized wlog_rec structure. If offset is < 0, the record will be appended to the end of the history file. If offset is >= 0, the record will be written at the indicated offset. This, along with the w_done field in the wlog_rec structure, provide a mechanism for 'pre-logging' a write, doing the write operation, and then overlaying the original record with the w_done flag set to 1. This is useful for async writes which may not complete in a timely manner. It is also useful for seeing which write operations were pending at the time of a system crash - the ones whose w_done flag is 0 have not yet been verified as complete. The return value from wlog_record_write() is the offset in the history file at which the record was written.
wlog_scan_backward() can be used to conveniently scan a write history file. The routine scans the file in reverse order (ie. first record written is scanned last). For every record found, the user supplied function is called with 2 parameters: the read record, and an arbitrary word passed in by the user. This word may be interpreted however the user desires. If nrecs is greater than 0, up to nrecs will be scanned. The user supplied function should return 1 of the following: WLOG_STOP_SCAN, or WLOG_CONTINUE_SCAN. WLOG_STOP_SCAN provides a way for the user supplied function to prematurely abort the scanning process. WLOG_CONTINUE_SCAN instructs wlog_scan_backward() to continue scanning the next record.
In order for the history file to be effective, some basic rules must be followed by the programs using the history mechanism:
The area of the data file being written must be locked from before the write operation, until after the wlog_record_write() is complete. This is necessary to 'synchronize' simultaneous writes to the same area of a file. Note that the entire file does not need to be locked, only the portion being written to. If the calling program can guarantee that there will never be more than 1 process writing to the same area of a file at the same time, locking is not necessary. (Note: UNICOS Shared File Systems do not support record locking. The whole file is silently locked.)
Pathnames in the history file (w_path field) should be full pathnames if possible. This allows validation tools to be able to find the test files without having to take working directory considerations into account.
/* * write log file data type. wlog_open() initializes this structure * which is then passed around to the various wlog_xxx routines. */ struct wlog_file { int w_afd; /* append fd */ int w_rfd; /* random-access fd */ char w_file[1024];/* name of the write_log */ };
/* * User view of a history file record. Note that this is not * necessarily how the data is formatted on disk (significant * compression occurs), so don't expect to od(1) the history file and * see things formatted this way. See the file write_log.h for comments * on how the data is actually written to disk. */ struct wlog_rec { int w_pid; /* pid doing the write */ int w_offset; /* file offset */ int w_nbytes; /* # bytes written */ int w_oflags; /* low-order open() flags */ int w_done; /* 1 if io confirmed done */ int w_async; /* 1 if async write (writea) */ char w_host[WLOG_MAX_HOST+1];/* host doing write */ int w_hostlen; /* host name length */ char w_path[WLOG_MAX_PATH+1];/* file written to */ int w_pathlen; /* file name length */ char w_pattern[WLOG_MAX_PATTERN+1];/* pattern written */ int w_patternlen; /* pattern length */ };
Note: The history files can become very large very quickly if a lot of processes are logging writes. This is especially apt to happen if long pathnames or patterns are used. This is because the w_host, w_path, and w_pattern fields are variable length fields when stored on disk. Thus, use short pathnames and patterns to minimize the size of the history file. If any of the w_path, w_pattern, or w_host fields are not important to you, set the respective length field to 0 in the wlog_rec structure.
EXAMPLESThis is a simple example of how to initialize a history file, and record a write to it.
#include "write_log.h" main() { struct wlog_rec wrec; struct wlog_file wfile; ... strcpy(wfile.w_file, hisfile); if (wlog_open(&wfile, 1, 0666) < 0) { fprintf("wlog_open failed); exit(2); } ... wrec.w_pid = getpid(); wrec.w_offset = write_offset; wrec.w_nbytes = nbytes; wrec.w_oflags = open_flags; wrec.w_done = 0; wrec.w_async = 0; wrec.w_host = 0; /* don't care about host */ wrec.w_pathlen = sprintf(wrec.w_path, "%s", path); wrec.w_patternlen = sprintf(wrec.w_pattern, "%s", pattern); pattern_fill(buf, nbytes, pattern, strlen(pattern), 0); ... lock fd here ... log_offset = wlog_record_write(&wfile, &wrec, -1); write(fd, buf, nbytes); wrec.w_done = 1; wlog_record_write(&wfile, &wrec, log_offset); ... unlock fd here ... ... /* * Scan the logfile printing records for the file in 'path'. */ wlog_scan_backward(&wfile, 0, print_log_record, (long)path); } int print_log_record(record, data) struct wlog_rec *record; long data; { char *path; path = (char *)data; if (strcmp(record->w_path, path) == 0) { printf("write() of %d bytes to %s at offset %d by pid %d, record->w_nbytes, record->path, record->w_offset, record->w_pid); } return WLOG_CONTINUE_SCAN; }
DIAGNOSTICSAll routines return a value < 0 on failure, and >= 0 on success. Error messages can be accessed through Wlog_Error_String.
BUGSNone known. | http://manpages.org/write_log/3 | CC-MAIN-2018-09 | refinedweb | 1,033 | 64.51 |
Map in Java is an interface available in java.util package and it stores the data in key and value pairs. It does not allow duplicate keys. The map interface in Java is often misunderstood as being a subtype of the Collections interface. But that is not true, and hence, the Java map functions differently from the Collection interface.
Since it associates unique keys with values, you can access the latter using a map interface. The Java Map interface maintains three sets: keys, values, and key/values maps (mapping). It is possible to access all these sets individually.
What Is the Hierarchy of the Map Interface in Java?
You can implement maps in Java from two interfaces: Map and SortedMap. The SortedMap interface extends the Map interface. There are three classes to implement maps. These three classes are HashMap, LinkedHashMap, and TreeMap.
The LinkedHashMap class extends HashMap that implements the Map interface. TreeMap class implements the SortedMap interface that extends the Map interface. The flowchart diagram depicted below represents the hierarchy of Map interface in Java.
Different Operations That Are Performed With Maps in Java
The Map interface in Java can be used with the classes that implement it, to perform various operations. Some of the primary operations you can perform on the maps in Java are:
- Adding elements
- Removing elements
- Changing elements
- Iterating through the map
Let’s see an example for each operation. You will use the most commonly used HashMap to perform these operations.
Example: Adding Elements to a Map in Java
In the example below, you will use the put() method to add elements to a map. You will be using the HashMap class here to implement Java maps.
import java.util.*;
public class example{
public static void main(String args[]){
// Default initialization for map
Map<Integer, String> m1 = new HashMap<>();
Map<Integer, String> m2 = new HashMap<Integer, String>();
// Inserting the Elements
m1.put(1, "Welcome");
m1.put(2, "to");
m1.put(3, "Simplilearn");
m2.put(new Integer(1), "Welcome");
m2.put(new Integer(2), "to");
m2.put(new Integer(3), "Simplilearn");
System.out.println(m1);
System.out.println(m2);
}
}
Output:
Example: Removing Elements of a Map in Java
This time you will use the HashMap class and the remove() method to remove elements from a map in Java. You will pass the key value in the remove() method, eliminating the associated value.
import java.util.*;
public class example{
public static void main(String args[]){
Map<Integer, String> m1 = new HashMap<Integer, String>();
// Adding Elements
m1.put(new Integer(1), "Welcome");
m1.put(new Integer(2), "to");
m1.put(new Integer(3), "Simplilearn");
m1.put(new Integer(4), "additional");
m1.put(new Integer(5), "data");
// Map before remove operations
System.out.println(m1);
m1.remove(new Integer(4));
m1.remove(new Integer(5));
// Map after remove operations
System.out.println(m1);
}
}
Output:
Example: Changing Elements of a Map in Java
You can also change the elements already added to a Java map using the same put() method to add elements. The only change is that you will have to pass the key of the value you wish to change, this time.
import java.util.*;
public class example{
public static void main(String args[]){
Map<Integer, String> m1 = new HashMap<Integer, String>();
// Adding elements
m1.put(new Integer(1), "Hi");
m1.put(new Integer(2), "to");
m1.put(new Integer(3), "Simplilearn");
System.out.println("Map before change " + m1);
m1.put(new Integer(1), "Welcome");
System.out.println("Map after change " + m1);
}
}
Output:
Example: Iterating Through a Map in Java
In this example, you will traverse through a map in Java using the for-each loop and retrieve the values by the getValue() method. You can also use other ways to iterate through a map.
import java.util.*;
public class example{
public static void main(String args[]){
Map<Integer, String> m1 = new HashMap<Integer, String>();
// Adding elements
m1.put(new Integer(1), "Welcome");
m1.put(new Integer(2), "to");
m1.put(new Integer(3), "Simplilearn");
for (Map.Entry mapElement : m1.entrySet()){
int key = (int)mapElement.getKey();
// Finding value
String val = (String)mapElement.getValue();
System.out.println(key + " : " + val);
}
}
}
Output:
When to Use the Map Interface in Java?
Since the Map interface creates a mapping between key: value pairs, it is best to use it with Java objects such as dictionaries that store data in a key: value pair. Maps are also the best option when you have to retrieve or alter the elements or extract values through keys. Standard examples of using a map in Java include:
- Map of cities and their zip codes
- Map of classes and students
- Map of managers and employees
- Map of errors and descriptions
How to Create Map Objects?
Java does not allow creating objects using an interface, and the same is true for maps too. Hence, you need classes that implement the map interface to create objects of this type. You can use any of the three classes that implement the map interface and use them for creating map objects. An example of creating a map object using the HashMap class is:
Map obj = new HashMap();
What Are the Classes That Implement Map Interface in Java?
The three primary classes that implement map in Java are:
- HashMap
- LinkedHashMap
- TreeMap
Of these three, HashMap and LinkedHashMap classes allow null keys and values, but the TreeMap doesn’t. You will see examples of how to use all these classes to implement the map interface in Java in the latter section.
What Are the Methods of Map Interface in Java?
The map interface in Java provides various methods that help perform various operations on the map. The table depicted below describes some of the standard methods of the Java Map interface.
How to Implement Map Interface in Java?
As mentioned earlier, three primary classes implement the Map interface in Java. Let’s look at examples of implementing maps in Java using these three classes.
Example: Implementing Map in Java Using the HashMap Class
The HashMap class provides basic map implementation. It stores the elements in a key: value pair and uses a hashing technique to access the values through keys. Let’s create a map object with the help of the HashMap class and use various methods, in the following example:
import java.util.Map;
import java.util.HashMap;
public class example{
public static void main(String[] args) {
// Using HashMap to create a map
Map<String, Integer> num = new HashMap<>();
// Adding elements
num.put("One", 1);
num.put("Two", 2);
num.put("Three", 3);
num.put("Four", 4);
System.out.println("The Complete Map: " + num);
// Accessing keys
System.out.println("The Keys are: " + num.keySet());
// Accessing values
System.out.println("The Values are: " + num.values());
// Accessing entries
System.out.println("The Entries are: " + num.entrySet());
// Removing elements
int value = num.remove("Three");
System.out.println("Value Removed: " + value);
}
}
Output:
Example: Implementing Map in Java Using the LinkedHashMap Class
LinkedHashMap is similar to the HashMap class, only with an added functionality of maintaining order. The LinkedHashMap class can keep the order in which the elements were added, something that was missing in the HashMap class. Let’s look at the below example, where you can implement the map interface in Java using the LinkedHashMap class.
import java.util.*;
public class example{
public static void main(String[] args){
Map<String, Integer> mp1 = new LinkedHashMap<>();
mp1.put("One", 1);
mp1.put("Two", 2);
mp1.put("Three", 3);
mp1.put("Four", 4);
for (Map.Entry<String, Integer> m : mp1.entrySet())
System.out.println(m.getKey() + " " + m.getValue());
}
}
Output:
Example: Implementing Map Interface in Java Using the TreeMap Class
The Java TreeMap class implements Map Interface, NavigableMap, and Abstract Class. It differs from HashMap and LinkedHashMap because it provides an efficient way for sorting the map. You can sort the map either based on the keys or the constructor used. The code mentioned below uses the TreeMap class to implement a map in Java.
import java.util.Map;
import java.util.TreeMap;
public class example{
public static void main(String[] args){
// Using TreeMap class
Map<String, Integer> val = new TreeMap<>();
// Adding elements
val.put("Second", 2);
val.put("First", 1);
val.put("Fourth", 4);
val.put("Third", 3);
System.out.println("Map using TreeMap: " + val);
// Replacing elements
val.replace("First", 11);
val.replace("Third", 33);
System.out.println("New Map: " + val);
// Removing elements
int remVal = val.remove("First");
System.out.println("The Removed Value is: " + remVal);
}
}
Output:
Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.
Summing It Up
In this article, you learned everything about the Map interface in Java. You can use maps in Java whenever you want key-value mapping for accessing, changing and removing elements. Some everyday use cases include zip codes and cities mapping, error codes and descriptions mapping, and manager and employees mapping.
Since you now have a clear understanding of the Map interface in Java, you need to practice it to get a firm grip on the interface’s practical usage. If you want to learn more about such interesting Java programming concepts, you can opt for Simplilearn’s Online Java Certification Course. The course covers all the basic and advanced concepts in Java, along with several hours of applied learning. This makes the course well-adept at helping you excel in Java development.
Do you have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on the same, ASAP! | https://www.simplilearn.com/tutorials/java-tutorial/map-in-java | CC-MAIN-2022-27 | refinedweb | 1,592 | 51.24 |
KDECore
#include <KTemporaryFile>
Detailed Description
A QTemporaryFile that will save in the KDE temp directory.
This class derives from QTemporaryFile and makes sure that your temporary files go in the temporary directory defined by KDE. (This is retrieved by using KStandardDirs to locate the "tmp" resource.) In general, whenever you would use a QTemporaryFile() use a KTemporaryFile() instead.
By default the filename will start with your application's instance name, followed by six random characters and an extension of ".tmp". You can use setPrefix() and setSuffix() to change the beginning and ending of the random name, as well as change the directory if you wish (read the descriptions of these functions for more information). For complex specifications, you may be better off calling QTemporaryFile::setFileTemplate() directly.
For example, let's make a new temporary file:
This temporary file will currently be stored in the default KDE temporary directory and have an extension of ".tmp". Now, let's change the directory:
Now the temporary file will be stored in "/var/lib/foodata" instead of the default KDE temporary directory, with an extension of ".tmp". It's important to remember the leading and trailing slashes to properly define the path! Next, let's change the suffix to a particular extension:
Now the temporary file will be stored in "/var/lib/foodata" and have an extension of ".pdf" instead of ".tmp".
Once you are done determining the name of the file, call open() to create the file.
If open() is unable to create the file it will return false. If the call to open() returns true you are ready to use your temporary file. If you don't want the file removed automatically when the KTemporaryFile object is destroyed, you need to call setAutoRemove(false), but make sure you have a good reason for leaving your temp files around.
- See also
- QTemporaryFile
Definition at line 92 43 of file ktemporaryfile.cpp.
Destructor.
Definition at line 50 55 of file ktemporaryfile.cpp.
Sets a suffix to use when creating the file.
Sets a suffix to use when creating the file. The random part of the filename will come before this suffix.
- Parameters
-
Definition at line 72 of file ktemporaryfile.cpp.
The documentation for this class was generated from the following files:
Documentation copyright © 1996-2014 The KDE developers.
Generated on Tue Oct 14 2014 22:47:11 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online. | https://api.kde.org/4.12-api/kdelibs-apidocs/kdecore/html/classKTemporaryFile.html | CC-MAIN-2019-47 | refinedweb | 412 | 55.64 |
Want to know how easy it is to create a 3D pie chart with the new JavaFX 1.2 chart API? All the code you need to create this is:
import javafx.stage.Stage; import javafx.stage.Alert; import javafx.scene.Scene; import javafx.scene.chart.PieChart; import javafx.scene.chart.PieChart3D; Stage { scene: Scene { height: 400 width: 500 content: PieChart3D { title: "Sample Pie" startAngle: 0 data: [ PieChart.Data { label: "Apples" value: 34 }, PieChart.Data { label: "Oranges" value: 27 }, PieChart.Data { label: "Bananas" value: 16 }, PieChart.Data { label: "Grapes" value: 50 }, PieChart.Data { label: "Cherries" value: 6 }, PieChart.Data { label: "Strawberries" value: 5 }, PieChart.Data { label: "Raspberries" value: 7 } ] } } }
The JavaFX charts API is based on the idea of a “Visual Model” so each PieChart.Data represents a single slice of the pie so if you would like to add an action to one of the pie slices this can be done like this:
PieChart.Data { label: "Apples" value: 34 action:function(){Alert.inform("Clicked on Apples")} }
Here is a web start link to try it out for your self
Is there an example of such a chart backed by a real data source (like a web service, or text file?
cool, is it in 1.2 possible to implement a horizontally scrolling linechart? I tried to adjust the min/max boundaries of the xaxis at runtime but it didn’t work (it even caused a mem leak).
@Steven I will be doing one soon plotting stock data from Yahoo
Thanks for sharing this great information. I’ve been searching the internet for posts on how to build dashboards that present charts showing application activities. I have considered using JavaFX to accomplish the task and am pleased to see now learn that there is a chart api. I will definitely be consider using this to build the dashboards
Did you have any idea how to do something on mouse over ? | http://fxexperience.com/2009/06/example-3d-pie/?replytocom=4 | CC-MAIN-2022-33 | refinedweb | 320 | 76.62 |
Hello. I ran into an issue (which I fixed) during the creation of a lab program and was wondering if you all could clarify why it happened. I'd also appreciate it if you could make suggestions as to alternative ways of completing the assignment, since I am not sure if I am making this more convoluted than it needs to be.
The assignment is to create a program that calculates change. The user provides the amount due and the amount received, and the program calculates how many dollars, quarters, dimes, etc, the customer should receive.
Here is what I wrote:
I know it's probably a mess to you guys.I know it's probably a mess to you guys.Code:
#include <iostream>
#include <cmath>
using namespace std;
void main() {
int dollars = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
double due;
double received;
cout << "Please enter the amount due:\n";
cin >> due;
cout << "Please enter the amount received:\n";
cin >> received;
due = received - due;
if ( due >= 1 ) {
dollars = static_cast<int>( due );
due -= dollars;
}
if ( due >= .25 ) {
quarters = static_cast<int>( due / .25 );
due -= quarters * .25;
}
if ( due >= .10 ) {
dimes = static_cast<int>( due / .10 );
due -= dimes * .10;
}
if ( due >= .05 ) {
nickels = static_cast<int>( due / .05 );
due -= nickels * .05;
}
if ( due > 0 ) {
pennies = static_cast<int>( due / .01 );
}
cout << "Supply the customer with:\n"
<< dollars << " dollar(s)\n"
<< quarters << " quarter(s)\n"
<< dimes << " dime(s)\n"
<< nickels << " nickel(s)\n"
<< pennies << " pennies";
cin.get();
cin.get();
}
Anyway, if you change the dollars, quarters, etc, variables to doubles, the program works flawlessly. However, if you retain them as ints and attempt to use a difference of say, .72 between the two values, it indicates that you should use only one penny instead of two. The same is true for a difference of .73, where it suggests 2 pennies instead of 3.
Why does this happen?
Besides the aforementioned curiosity, I would also like to know if there is any way to get rid of all of the if statements, and just in general how I could optimize things.
Thanks guys. | http://cboard.cprogramming.com/cplusplus-programming/124141-little-homework-help-printable-thread.html | CC-MAIN-2016-18 | refinedweb | 352 | 74.49 |
Join devRant
Search - "file not found"
-
-
-
- A quite severe vulnerability was found in Skype (at least for windows, not sure about other systems) allowing anyone with system access (remote or local) to replace the update files skype downloads before updating itself with malicious versions because skype doesn't check the integrity of local files. This could allow an attacker to, once gaining access to the system, 'inject' any malicious DLL into skype by placing it in the right directory with the right file name and waiting for the user to update (except with auto updates of course).
From a company like Microsoft, taking in mind that skype has hundreds of millions of users worldwide, I'd expect them to take a very serious stance on this and work on a patch as soon as possible.
What they said about this: they won't be fixing it anytime soon as it would require a quite big rewrite of skype.
This kinda shit makes me so fucking angry, especially when it comes from big ass companies 😡. Take your fucking responsibility, Microsoft.22
-
- Found this gem on GitHub:
//.
Ref :
- alias gcc='echo "gcc: fatal error: Input file not found: "
Now have fun watching your victim struggle.7
-
-.48
-.9
-
-11
-
-
-
- For the privacy freaks of devRant, have a host file that blocks all Facebook owned domains:
Blocklist Facebook domains (2016) -...
(not mine, found on HN
-.6
-
-
- really enjoy my old Kindle Touch rather than reading long pdf's on a tablet or desktop. The Kindle is much easier on my eyes plus some of my pdf's are critical documents needed to recover business processes and systems. During a power outage a tablet might only last a couple of days even with backup power supplies, whereas my Kindle is good for at least 2 weeks of strong use.
Ok, to get a pdf on a Kindle is simple - just email the document to your Kindle email address listed in your Amazon –Settings – Digital Content – Devices - Email. It will be <<something>>@kindle.com.
But there is a major usability problem reading pdf's on a Kindle. The font size is super tiny and you do not have font control as you do with a .MOBI (Kindle) file. You can enlarge the document but the formatting will be off the small Kindle screen. Many people just advise to not read pdf's on a Kindle. devRanters never give up and fortunately there are some really cool solutions to make pdf's verrrrry readable and enjoyable on a Kindle
There are a few cloud pdf- to-.MOBI conversion solutions but I had no intention of using a third party site my security sensitive business content. Also, in my testing of sample pdf's the formatting of the .MOBI file was good but certainly not great.
So here are a couple option I discovered that I find useful:
Solution 1) Very easy. Simply email the pdf file to your Kindle and put 'convert' in the subject line. Amazon will convert the pdf to .MOBI and queue it up to synch the next time you are on wireless. The final e-book .MOBI version of the pdf is readable and has all of the .MOBI options available to you including the ability for you to resize fonts and maintain document flow to properly fit the Kindle screen. Unfortunately, for my requirements it did not measure-up to Solution 2 below which I found much more powerful.
Solution 2) Very Powerful. This solution takes under a minute to convert a pdf to .MOBI and the small effort provides incredible benefits to fine tune the final .MOBI book. You can even brand it with your company information and add custom search tags. In addition, it can be used for many additional input and output files including ePub which is used by many other e-reader devices including The Nook.
The free product I use is Calibre. Lots of options and fine control over documents. I download it from calibre-ebook.com. Nice UI. Very easy to import various types of documents and output to many other types of formats such as .MOBI, ePub, DocX, RTF, Zip and many more. It is a very powerful program. I played with various Calibre options and emailed the formatted .MOBI files to my Kindle. The new files automatically synched to the Kindle when I was wireless in seconds. Calibre did a great job!!
The formatting was 99.5% perfect for the great majority of pdf’s I converted and now happily read on my Kindle. Calibre even has a built-in heuristic option you can try that enables it to figure out how to improve the formatting of the raw pdf. By default it is not enabled. A few of the wider tables in my business continuity plans I have to scroll on the limited Kindle screen but I was able to minimize that by sizing the fonts and controlling the source document parameters.
Now any pdf or other types of documents can be enjoyed on a light, cheap, super power efficient e-reader. Let me know if this info helped you in any way.4
- Hi devs!
I've seeked the world but found no answer to this:
I want an android code to convert double[] to a sound file and be able to get that double[] from the file.
And yes I've tried stdAudio library but it did not work as I expected.
Give a replay, save my life 😁5
-
- Previously:
I wanted to grab a script off another computer, and was getting strange scp errors. Turns out my use of .bashrc to hold all my aliases and custom variables was not "best practice," and scp was flipping out. I renamed my .bashrc files to .bash_profile, and scp worked properly from there. But then, I found that by default xterm doesn't consider an xterm session a "login." So I had to update my .Xresources file with an option for xterm, and re-merge it with xrdb. SO! I was ready to grab my script to set my openbox config the way I like it.
All the while, I noticed that the trackpad tapping didn't work, so that was my next hurdle to take. Next post!
-
-
- Tried to dual boot Arch with Windows yesterday.
Everything was going smoothly. Shrunk the C: partition, ran the installer, installed the OS fine. But it was still booting straight to Windows.
So I edited the BCD to point to Grub instead of Wilndows. Then the plan was to boot into Arch, find Windows, and add it to Grub, problem solved.
Wrong. I had forgotten to disable secure boot. Arch and Grub were booting in BIOS mode, but Windows was UEFI. Grub couldn't boot or even see Windows.
So now I was stuck with just Arch. So I flashed a Windows drive, booted from that, automatic startup repair failed. Opened up the command prompt, tried to rebuild the BCD from there. Surely I can just rebuild it and forget about trying to dual boot right? I just want to get back to being able to use my PC.
Wrong again. Didn't find Windows. Had to get rid of the BCD file before I could rebuild it, but couldn't find it. Found out that I could use diskpart to mount the system partition and assign it a drive letter, renamed the BCD, rebuilt it, and finally was able to reboot into Windows.
Learn from my arrogance. First time Linux users should not attempt to install Arch, let alone do it alongside Windows on the same disk
- Just found out that a big hosting provider saves a user's SQL and FTP password in a plain text file just at the parent folder of the normally accessible ftproot.
Using some linux commands you can
cat ../mysql_pw
cat ../ftp_password.txt
IT'S NOT EVEN ENCRYPTED OR HASHED
(This is tested on a minecraft server, would also work on other services
- Has anyone else noticed that on Windows with Excel, if you save as text/csv and upload through browser it sends a mime type of vnb.ms-excel instead of text/csv mime type.
Searching further Windows sends mime type of the program that is default for that file not correct mime type for file. Which is irritating for my validations.
Found an article relating
-
-.1
- '-'.
- Spent about an hour wondering why my php code was showing in the browser window after submitting a form using Ajax. Found that I had start my php file with just <? And not <?php. Feeling dumb.
- I am feeling so powerful right now I can not describe it.
I found out how I can get the methods and params outta LINE.
Now that I finally understand Apache Thrift and how it works with the LINE servers, I can make a thrift file, generate communication files for the LINE servers and use them for any programming language I want. Means that I can switch to a faster language than Python. Finally :
- Awesome! //not.. :/
Was checking what the F I was doing wrong, my files didn't show up in changes.. found out someone thought it was a good idea to put *.cs to ignore file.. :/
What are .cs files?! We don't need them anyways.. :/ o.O
Fuck.
-
- By Thor (not the god, the dragon), Belial and Thor (the god, this time)...
Just got the sources for the software that runs on the SDR for my project. I think I just found the mother of all legacy code:
The whole behaviour is described in a single, 4000 lines C file. Most of the code is in a giant switch with cases selected from an enumeration with names that don't match their function. All varnames are overly long, yet hopelessly unhelpful. And why three fuck would you use pointer[0].data instead of (*pointer).data or pointer->data like a sane person would !? pointer isn't even an array, so why would you use [].8
- Error. File not found: C:\somedirectory\file.txt
*opens C:\somedirectory\ * *looks at file.txt*
*runs program again*
Error. File not found: C:\somedirectory\file.txt
*changes directory it is looking in, copies file to new directory*
Error. File blank: D:\somedirectory\file.txt
*cry... no it isn't*
I just need to deploy this contractors code... supposedly it ran on another system, but the endless Spring configs hate me... :(9
- Real story:
Started fixing one file in one repo, build, doesn't build, go into other repo fix just one file there, but first I need to make myself a toolchain, making of toolchain fails because it depends on some dirty fix in the file I was fixing, refactor and clean that to a proper state, fuck yeah toolchain builds, source toolchain run make now, breaks with undefined reference, no time to debug plus fuck this automake, remove it, make a makefile, builds fuck yeah, shit now unittest are failing because why not, refactored that makefile as well, everything compiles, automate the test fully so that they are ran on the target out of make just because I'm a nice guy, fuck yeah everything works, commit this repo, commit other repo, review time, one of the guys gave up, the other one did it properly, found some shit there, fix that, done, merge, triggers CI fucking pass
All of this was done in 3h, Talk about efficiency
- Just found a tutorial on DigitalOcean to setup traefik so I can easily make my images accessible to the outside.
"So create this file, add this in it, create this proxy, run this long ass command, and when you go to '', you should get this dashboard"
Got "This website is not available"....
-.
-
- A common walkthrough with Laravel deployment:
1.) Error 403
2.) Internal server error 🤔
3.) bad require paths in index.php....
4.) Whooops something went wrong.. What?.... Look at log file with 2MB size
5.) View not found
-
- Tried really hard to get the external css file working and after an hour found that I had not specified href in the main html file.
fml
-
- ?7
-
-]
- So 9 months back I wrote a script that asked for company's symbol to fetch data from a site, just one symbol a time. There were around 300-350 symbols, I tried storing symbols in a text file and supplying input from it, it did not work then so I decided to leave it as it is. Today when I took closer look at the code I wrote, I found that the symbols were being fed to the script, however, the "\n" was included too, so my script was failing to get data in bluk. Modified it today, it's all good. Its kinda crazy, 9 months and only thing stopping my script to work was a freakin "\n".
-
-
-
- I want to create a static JS class/file to hold shared functions but I can't seem to make it usable in other JS files.
import DbCommons from './commons' //Same folder
getCategories() {
return this.db.transaction((tx) => {
tx.executeSql('SELECT * FROM ' + DbCommons.CategoryTable, []) //Says not found
I forget how do I make things visible outisde of the actualy JS file11
-
- Today, I decided to learn build a c++ project using cmake. Since I've never done a big project in C++ I have no experience with these stuff.
Couple of hours for researching and trying to understand how that thing works, how to specify things, this and that. Wrote a small program for testing.
Everything was fine. Makefile was generated and program was worked.
Then.... Somehow, sublime text started to give me error messages like, 'the header file you included is not found.' I hit the makefile again, the built was successfull... I know that, need to add -I to compiler flag so that it can find the files. But in sublime text constantly refuses my 'possible' solutions.
Even ycm in vim does this. They expected me to write includes like '../thispkcg/include/header.h'
Where did i go wrong ..............
Btw it works like a charm in cLion I don't know why.
-?2
-'m currently making an internship at a medical software company and today i found this gem in a js file:
/*
the server does not check if the element was deleted or not; it will return success, no matter what; **it's not a bug, it's a feature**
*/
- is wrong with android storage access hierarchy?All i want to do is to make a file explorer app which could show user a list of all the files on their device and memory card(if available), but its been days and i cannot find a proper way for that.
I checked all the Environment class methods and context.getFileDir()/other methods of ContextCompat , but they either point to emulated storage or the app's folder, but not the sd card. I have scratched my head and pulled all my hairs out researching a lot deep into this area, but found nothing. The only thing that works sometime is the hardcoded paths( eg new File("/sdcard") ) , but that looks like a terrible hack and i know its not good.
I have also read briefly about Storage Access Framework, but i don't think that's what I want. From what i know, SAF works in the following manner : user opens my app>>clicks on a button>>my app fires an intent to SAF>> SAF opens its own UI>>user selects 1 or multiple file>> and my app recieves those file uris. THAT'S A FILE PICKER, AND I DON'T WANT THAT.
I want the user to see a list of his files in my app only. Because if not, then what's the point of my app with the title "File explorer".
- Just found a few methods in the same file which does the same task written by different devs just because they did not know a method already existed in the first place. How tough is it for them to do a grep on the file?1
- I spent half a day trying to figure out why the app on the staging server does not log in the app log file while it does on the dev server.
Server log said log config file found but could not find the root logger.
Problem was that the directory was readable for the app, but not the logfile configuration file.
Dear devs, when a file is not readable that might be some interesting information one could write into a log. AT LEAST MORE INTERESTING THAN "APPLICATION STARTING..."
- qemu-img keeps on reporting error:
Could not open 'some-qcow2-img': No such file or directory
Why you waste me 2 hours for troubleshooting instead of telling me it's the backing file that could not be found?
Top Tags | https://devrant.com/search?term=file+not+found | CC-MAIN-2020-10 | refinedweb | 2,822 | 72.26 |
There are two levels of correctness of an XML document. The lower level is syntactic and structural: End tags must match their start tags, elements must nest properly, all quotes must be closed, all special characters must be properly escaped, and so on. The XML specification terms such documents well- formed . Fortunately, you don't have to do anything special to ensure well- formedness : Any XML parser (used in transformation or even built into your XML authoring tool, 6.1 will report well-formedness errors immediately.
It is only at the higher levelthe level of semantic correctnessthat a well-formed document has to be validated against a source definition. As we saw in the previous section, a typical source definition may include a number of document types and be subdivided into the document and super-document layers ( 2.1.1 ). At the implementation level, the core of a source definition is one or more schema documents written in a schema language. This section examines the existing schema languages and discusses various issues related to schema design and implementation.
One of the first decisions you face is the choice of the schema language to use. Once limited, this choice is now quite wide and keeps getting wider.
Besides the old and proven DTDs, you can use any of the numerous other languages capable of formally defining the structure and content of XML documents. The best known of these is W3C's XML Schema Definition Language [6] (often called simply "XML Schema" but abbreviated XSDL in this book). However, there are other schema languages that are no less deserving of your attention. Below we'll look at the main issues to consider when choosing a schema language for your project.
[6]
[6]
All schema languages could be divided into two major groups. The first group encompasses grammar-based languages such as DTD, XSDL, and RELAX NG. [7] A grammar of a language is its formal description that aims to cover the entire language; if a document has a feature not covered by the grammar, this is because either the grammar is incomplete or the document is invalid. In either case, an error is reported .
[7]- open .org/ committees /relax-ng
[7]- open .org/ committees /relax-ng
Grammar descriptions work "downward"; that is, they start from the most global structural units and proceed to the local constructs defining everything in between. Therefore, a grammar is often similar in structure to the document it describes; for example, an element type declaration in XSDL may have the declarations for its descendants laid out exactly as are the real descendant elements in a valid document.
Grammar limitations. Defining XML vocabularies through grammars is very natural, and the resulting schemas are usually straight-forward to read and write. However, it is only in theory that this approach works perfectly ; for many practical scenarios, it is too rigid and inflexible . One of the problems is that many practical types of constraints are impossible to define in grammar-based schema languages. More importantly, in practice you may want to use only a subset of validation rules.
For example, you may want to validate first the structure of a newly created document without checking attribute values or element content, and only go for full validation at a later stage. Sometimes, on the other hand, you may need to validate attribute values even though you know that the structure of the document is not yet valid. Some checks may be more important for you than others, and new checks are likely to become necessary as your document evolves through various stages of its lifecycle.
With a grammar-based language, it is difficult to extract part of a schema and use it independently of the rest. A grammar either matches a document in its entirety, or it does not match at all. This is where the second kind of schema languages may be more suitable: the rule-based languages, of which the best known is Schematron. [8]
[8]
[8]
Precision aiming. A Schematron schema consists of an arbitrary number of rules, each describing one aspect of document structure or data values. These rules do not have to cover the entire grammar; anything in the document for which no rule is found is assumed to be OK by a Schematron validator. Rules can be given in arbitrary order having nothing in common with the order of the corresponding structural units in the document.
Thus, it is easy to start a Schematron schema by defining rules for what you think are the most importantor the most likely to get botched by document authorsfeatures of your document type. Even a one-rule schema is completely workable and may be useful. Later, you can grow your schema "upward" by adding new rules to it as you see fit, either to reflect new structures in an evolving document type or to guard against further practical markup errors. Rules can be grouped into patterns, and patterns can be turned on or off during validation to implement different validation scenarios (such as checking attribute values without checking the structure of elements).
Schematron primer. A simple Schematron example illustrates the above points. Example 2.1 is a Schematron rule combining three checks. The context attribute specifies that these checks will be applied to each section element in the source document. The first two checks verify the presence of obligatory children elements ( head and p ). The last check uses the XPath function normalize-space() to ensure that the section element contains no child text nodes, that is, no "dangling" bits of textual data not enclosed into an appropriate element.
<rule context=" section "> <assert test=" head "> A 'section' must have a 'head'. </assert> <assert test=" p "> A 'section' must have at least one 'p' (paragraph). </assert> <assert test=" normalize-space(text()) = '' "> A 'section' cannot contain text. Use a 'p' element to include a paragraph of text. </assert> </rule>
Of course, we could think up lots of other checks applicable to this simple structure. For instance, we could check that not more than one head element is a child of a section , or that a head comes before any p . However, those checks included in our example grew out of the everyday markup practicethey were added to prevent the most common errors in real documents. You can always add more checks (including those that are impossible with a grammar-based schema language) to respond to the changing requirements of XML authors.
As you can see, the only relatively tricky aspect of this example is the XPath expressions it uses. In fact, for those familiar with XPath, the learning curve of Schematron is nearly nonexistent. The reference implementation of Schematron (which we will use for our examples) is itself written in XSLT and translates a schema into an XSLT stylesheet ( 5.1.2 ). More complex Schematron schemas (Examples 3.3, 5.20) will be analyzed in the following chapters.
Growing rules into grammar. Ultimately, a set of rules in a Schematron schema may grow complete and thus become a grammar. Admittedly, because of the way it was developed, such a grammar may not be as prettily laid out and easy to read as an XSDL schema for the same document type (although it is likely to be more powerful). Of course, you can always organize it and clean it up if you feel like it, or you can even rewrite it completely in a grammar-based schema language. What's important is that your Schematron code has played its role: It allowed you to effectively validate your documents while they were being developed.
So, the rule-based approach makes Schematron an ideal "prototyping" schema language, useful at the early stages of any XML project. Moreover, the fact that Schematron is tightly coupled with XSLT and allows you to easily express rules on both document and super-document layers ( 2.1.1 ) makes it especially suitable for web site projects. If you use XSLT for transforming your XML and if you store the source in more than one document, Schematron is a natural choice.
Guided editing. One downside to a rule-based schema is that it cannot answer arbitrary questions about valid documents, such as "what attributes are permitted for this element type?" or "what type of element can come after this element?"
A rule-based schema is, in a sense, a collection of canned answers to questions that its developer deemed most importantso you cannot rely on it to contain the answer to your particular question. Conversely, a grammar-based schema is a complete description of a valid document, and you can use it to find out an answer to any question so long as it belongs to one of the types covered by this schema.
One practical consequence of this is that you need a grammar-based schema if you want your XML authoring tool to provide guided editing ( 6.1.1.1 ), that is, to suggest valid markup at any point in the document. In order to compile, for example, a list of element types that you can insert at some specific point, an XML editor must have a complete grammar of the document type, not a collection of disjointed checks from a rule-based schema.
Obviously, guided editing is a feature most useful for site editors, not developers. This gives you another reason to create a grammar of your source definition after it is developed and tested but before the bulk of the site's content is marked up with it.
Best of both worlds . With XSDL, you can embed modules written in other schema languages, including Schematron, into your grammarbased schemas. This approach is attractive because it combines the completeness and logical layout of XSDL with the power and precision of Schematron rules.
Modularity is the best way to keep complex projects under control. Without breaking your work down to manageable and reusable pieces, further development and maintenance may soon become excessively difficult.
A web site's source definition is no exception. XML is intrinsically modular in that element types and attributes, declared once, can be reused arbitrarily many times. However, for practical purposes this is not sufficient. A schema must enforce some higher-level abstractions above element type and attribute declarations, so it can be split into modules that are sufficiently orthogonal (such that changing one module introduces little risk of breaking other modules), easy to maintain, and easy to reuse.
Different schema languages provide different high-level abstractions and therefore different methods of modularizing schemas. This is another important aspect that you should consider before selecting one of the languages. Try to choose the language whose way of dividing schemas into interconnected modules appears closest to the way you tend to think about your source definition.
Since all schema languages exist in the common XML universe, the pieces they consist of at the lowest level are the same: element type declarations, attribute declarations, and content models for specifying what elements, in what order, may occur within other elements. Also, most schema languages support the notion of a document type and allow modularizing schemas at this level. Beyond this, however, it becomes more interesting.
XSDL emphasizes data types and provides an extensive set of tools that you can use to define, extend, restrict, inherit, and reuse data types. Therefore, one could say that XSDL is modular primarily at the data type level. A library of reusable components in XSDL is likely to consist mainly of type definitions that you can reuse in your schema's declarations.
In DTDs , the modularization mechanism is parameter entities (see 2.2.1.4 for an example). An entity is similar to a text editor's macro in that it works at the character level and just replaces an identifier (called a parameter entity reference ) with an associated fragment of text or external object. Any syntax checks are made only after all entity references are expanded.
This approach is proven and powerful, but may lead to hard-to-track bugs . With DTDs, however, this paradigm is effective, as it allows you to create complex schemas that are pretty well modularizedeven though sometimes hard to read.
Unlike most other schema languages, DTDs do not support local element type declarations. This means that you cannot restrict an element type to certain contexts, such as within a certain parent element. Any element type you declare becomes global, and you cannot have two global element types with the same name . For example, if a book element can have an author child and so can a song element, a DTD will validate this only if these two author s have exactly the same children and attributes, or if book and song are in different document types. This is an important reason why DTDs are hard to modularize , although it provides consistency for the authors.
Schematron is the only schema language that does not have explicit element type and attribute declarations as its basic building blocks. Instead, it allows you to specify arbitrary checks that a valid document must pass. Nothing prevents you, however, from arranging these checks into groups so that each group defines all aspects of one element type and is thus a functional equivalent of another schema language's element type declaration.
On the other hand, you can group your checks in any way that makes sense for your application. Schematron offers several levels at which checks can be grouped ( rule , pattern , phase ), and you can switch different phase s on or off for each validation pass. Finally, new rules can be defined to extend existing abstract rules when applied to specific contexts. This flexibility makes it possible to create Schematron schemas that are not only effective but modular and easy to extend.
Fake integers in DTDs. A typical schema can express much more than it can enforce . For example, if you want to declare in your DTD an attribute that only takes integer values, you might think you're out of luck because an integer attribute type is not enforceable via a DTD. However, you can define an entity:
<!ENTITY % integer "CDATA">
(here CDATA means "any character data") and then use it whenever you want to define an integer-valued attribute. True, for an XML parser this trick is meaningless, as it still won't be able to tell that a value of "xyz" for such an attribute is wrong. But for a person looking up an element's attribute list in the DTD, a reference to such an entity
<!ATTLIST element attribute %integer; #IMPLIED >
makes a lot more sense than just
<!ATTLIST element attribute CDATA #IMPLIED >
to which it is formally equivalent.
Some might argue that this trickery is useless and can even be misleading, because it gives a DTD author a false feeling of security that is not based on any solid foundation. This may be true, but it is also true that readability is an important aspect of reliability. Other schema languages have other kinds of limitations where similar unenforceable hints might be necessary.
This is a complete sentence . Even though Schematron's XPath expressions are very powerful, you cannot use them to enforce rules that can't be formulated algorithmically, even though these rules may be very important for your source definition. For example, you may require that a heading is always a complete sentence (and not, say, a single word or a phrase). While you could output a warning if the number of words in a heading seems to be too small for a sentence, you cannot reliably catch this error using XPath.
You can, however, make your schema more expressive and more useful with regard to this rule in several ways:
Document the schema (see also 2.2.3 ). This is the least obtrusive but the least efficient approach, as only those XML authors who bother to read the documentation will be aware of the restriction.
Provide validation-time diagnostics. If you cannot check if an element satisfies a rule automatically, you can still remind the user to see to it whenever your schema runs across this element type. This is obviously a more obtrusive option, but it may be advisable if the element type in question does not occur too frequently or the requirement you're trying to enforce is very important.
Choose a "talking" name. Even though it is the structural role that must be the basis for selecting the name for an element type ( 2.3.4 ), sometimes other factors can participate too. If there's an important but formally unenforceable requirement concerning some element type, you can reflect it right in its namefor example, by using heading-sentence instead of just heading if you want the heading to contain a complete sentence. This way, whoever is authoring the XML source will be reminded of the rule every time he or she inserts the corresponding element. Of course, longish and unwieldy names may become a major nuisance, so use this method only for really important aspects of your source definition.
Example 2.2 shows a fragment of a Schematron schema [9] that implements all three approaches listed above. The heading-is-a-complete-sentence rule is documented in the schema and is additionally reinforced by the choice of the element type name. An unconditional "reminder" is fired whenever a heading-sentence element is encountered , plus two additional checks ensure that the element's value contains at least one space between words and its last character is a letter. [10]
[9] The function matches() in the test expressions is from XPath 2.0 ( 4.2 ).
[9] The function matches() in the test expressions is from XPath 2.0 ( 4.2 ).
[10] Note that Schematron 1.5 does not allow p within rule , so I had to use XML comments to provide per-rule documentation.
[10] Note that Schematron 1.5 does not allow p within rule , so I had to use XML comments to provide per-rule documentation.
The question of how strict your schema must be is equivalent to the question of how wide is the gray zone of XML structures which, from the viewpoint of the schema author, do not make much sensebut do no harm either and are therefore considered valid. There are two opposite approaches here: either "whatever is not permitted is forbidden" or "whatever is not forbidden is permitted".
Each of the schema languages naturally gravitates toward one of these two approaches. For example, if you don't explicitly permit a certain attribute on a certain element type in a DTD, using this attribute in an XML document is a validity error. On the other hand, if you say nothing about some element type in a Schematron schema, corresponding instance elements are always considered valid. Still, by using techniques such as wildcards you can to some extent emulate both approaches in any schema language.
<pattern name="Heading checks"> <p> This pattern's rules check the validity of various heading elements. </p> <rule context=" heading-sentence "> <!-- This element must contain exactly one complete sentence (i.e., one with a subject and a predicate) but no punctuation at the end. --> <report test=" true() "> Check that this element contains a complete sentence. </report> <report test=" matches(normalize-space(), '[^A-Za-z0-9]$') "> The last character of this element's content is not a letter nor digit. Please check that there is no punctuation at the end of the heading sentence. </report> <report test=" not(matches(normalize-space(), ' ')) "> This element's value has no spaces. You cannot write a complete sentence without at least one space between words. </report> </rule> <!-- more rule --> </pattern>
Which approach is better? For database-like XML ( 1.2 ) produced and consumed by programs, something not explicitly prescribed in a schema is most likely an error. For documents written and read by human beings, the opposite is more often true. You cannot possibly foresee all the real-world circumstances that may force you to look for markup workarounds in your documents. Therefore, the "whatever is not forbidden is permitted" approach is usually more suitable for a web site source definition.
Once again, Schematron turns out to be designed for the task. A grammar-based schema, for example, would require you to explicitly list all allowed attributes in an element type declaration; with Schematron, you can prohibit or require certain attributes within certain elements (possibly depending on the context in which an element occurs) and pay no attention to all others. The Schematron motto is, "Don't bother defining it unless it causes you problems."
For those who prefer to get results fast, writing a formal source definition may look like a waste of time. XML is so intuitive that the temptation to jump straight into authoring (leaving the definition of the documents' structure for later) is very strong. And when the first sample pages are ready and tested (perhaps even with real content and a real stylesheet), the incentive to go back to a formal definition of what you've just created is even weaker. After all, the page templates are so self-explanatory, why bother describing them in yet another layer of complexity?
Indeed, the pedantic, make-a-plan-first-then-start-to-code approach may not be the best for everyone. Are there alternatives? This depends on the complexity of your project, your experience with XML, as well as the level of expertise of those who will be maintaining and supporting the site after it is launched. (In fact, it is likely that you'll get a strong motivation to formally define your markup once you see the incredible errors others are making in their documents.)
If your site's source structure need not be too complex, and especially if you are reusing some bits from previous projects, you can work on the schema in parallel with the actual XML documents. This way, when you think you need a new structural unit, you add it both to the XML document you're writing and to the schema. Here, the actual documents are your drafting boarda schema is simply kept in sync so your documents will validate.
However, this approach will be pointless unless you take time to carefully review, clean up, modularize, and generalize your schema as soon as most of its components are in place.
Starting small. Especially convenient are schema languages that allow the schema to be incomplete but still workable, such as Schematron. For instance, you can quickly write a Schematron schema to check that a heading element has only translation children, each having a unique (within the heading ) value of the language attribute (compare 2.3.5 ). You need not specify any other restrictions or list any other element types or attributes for this schema to work; anything not mentioned in its single check will simply be ignored during validation.
As you continue to add new structural units to your XML, you can expand this schema to express more constraints. In principle, you can even declare the project finished with such an incomplete schemaif you are sure that it catches the most likely markup errors and that whoever authors new XML documents will not break anything "obvious" that the schema does not cover (this last assumption may sound more plausible if new documents are always created from templates, 2.2.3.3 , that already contain basic structural blocks). However, it is still advisable to fill in all the blanks and make the rule-based schema as complete as possible so that only fully compliant documents will pass validation in the daily maintenance of the site.
Ending big. Even if throughout the development cycle, you were working with a rule-based language such as Schematron, you may still need to provide a grammar-based schema (e.g., a DTD or an XSDL schema) when the source definition is complete. This may be a result of several factors.
First, you have to consider the limitations of your production setting. For example, if your web site is going to be part of a larger XML framework that supports only DTDs, you must provide DTDs for your document types. The same is true if you need to integrate the web site with existing schema libraries; for example, you may want to base your web page's data types on those defined in existing XSDL schemas.
Second, you should remember that a schema is more than just a filter that separates valid and invalid documents; it is also one of the principal parts of the system's documentation, the ultimate reference manual of your source definition. It must therefore reflect not only valid structures in your documents, but also the larger ideas and concepts behind these structures. The schema language ideally satisfying these documentation requirements will likely be different from the language that is most convenient for development and practical validation; obviously, complete grammars make better documentation than collections of disjointed validation checks.
Still another reason (already mentioned in 2.2.1.2 ) to write a grammar for your source documents is to enable guided editing if your XML editor supports it.
Don't worry if you don't get it right the first time and have to make changes to your source definition, either in the process of writing the stylesheet or even during after-launch site maintenance. Admittedly, such changes can be costly because they may necessitate modifying markup in a lot of documents (although in many cases, you can automate this by creating an XSLT stylesheet that will transform your documents from the old markup to the new one), but sometimes they are unavoidable. Here are some bits of advice:
Accumulate many small changes into a few large "releases" that are put into effect simultaneously across the entire system. (Be careful, however, not to frighten your users by making these changes too sweeping.)
Carefully document all changes (this, of course, implies that the original markup rules that you are changing were also well documented).
Make sure that your schemas, transformation stylesheet, and other software are aware of both old and new versions of markup. Provide corresponding checks and helpful error messages. Whenever possible, make the system backward-compatible , but warn the user that the old format, even if it still works, should be changed to the new one as soon as possible.
An ideal schema does not need documentation because it is documentation itself. Indeed, a complete human-readable specification of an XML vocabulary is also its "schema" in the sense that you can use it as the ultimate authority on whether or not an instance of that vocabulary is conformant. The only problem with such a "schema" is that you need a human to apply it to each documentwhich makes it costly, slow, and error-prone .
It is only natural to try to combine formalized schemas that permit automatic validation with human-readable documentation. Schema languages provide embedded documentation tools that are as different as user requirements can be. Here are a few examples:
With DTDs , you can add documentation to a schema by using <!-- XML comments --> . The comments can contain XML markup, except for other comments.
XSDL offers a powerful mechanism whereby you can use element types from any vocabulary (e.g., HTML or DocBook) to provide any amount of documentation on the components of your schema. The documentation elements are distinguished from XSDL elements by their unique namespace. Because both the schema itself and its embedded documentation are in XML, it is possible to process schemas using an XSLT stylesheet (for example, to extract all documentation into a separate document).
Schematron can also embed arbitrary XML elements in schemas. [11] However, Schematron's focus is different; its rules are typically much less structured than XSDL or DTD declarations, so trying to structure the documentation according to the layout of these rules may not be an optimal strategy. Instead, what Schematron excels in is on-demand diagnostics tied to specific markup contexts or triggered by specific errors.
[11] The Schematron 1.5 specification lists a number of element types permitted inside the p elements that are intended for documentation, but most implementations will allow you to use arbitrary markup there.
[11] The Schematron 1.5 specification lists a number of element types permitted inside the p elements that are intended for documentation, but most implementations will allow you to use arbitrary markup there.
For many users, this "context-sensitive help" feature of Schematron can be even more useful than a narrative-style documentation, as it may help them learn practical markup much faster. Note also that Schematron diagnostics are delivered to the user directly and are not (unlike other languages) interspersed with markup declarationsfor some users, this makes a lot of difference in terms of documentation usability.
What should be in the documentation of a source definition for it to be useful? Surely the idea of " well-written documentation" is quite subjective : Where one user would prefer a detailed narrative with examples and explanations , another would be perfectly happy with basic templates and a validator that provides minimal diagnostics for markup errors. Your best bet, therefore, is to discuss documentation requirements with the actual users of your source definition. In my experience, the components of successful documentation include, in order of decreasing usefulness , the following:
Any relevant rules that are not in the schema itself. As we've seen, schema languages vary widely in how much of a complete source definition they can formally express. DTDs are particularly weak in this regard, but even with XPath-based Schematron rules, there may be certain conventions that you cannot check automatically. It's obviously a priority to supply such rules in human-readable form so that XML authors can avoid bad practices or at least figure out what they've been doing wrong.
<xsd:element <xsd:annotation <p> An example of a block: </p> <pre> <![CDATA[ <block> <heading>A heading</heading> <!-- no full stop! --> <p>A paragraph of text.</p> <p>Possibly one more paragraph.</p> </block> ]]> </pre> <p> Note, however, that a block may be empty if it contains a reference to an external resource: </p> <pre> <![CDATA[ <block idref="block-id" /> ]]> </pre> </xsd:annotation> ... </xsd:element>
Markup examples. As for documenting the rules that are in the schema, examples of conforming markup work best: An example is worth a thousand words. You should provide not only typical examples but also any special or borderline cases if they are likely to cause problems. If used in XML (as opposed to plain text or XML comments), use CDATA sections [12] for example code so it is not treated as part of the markup. Example 2.3 shows such a CDATA section embedded into HTML documentation in an XSDL schema.
[12]
[12]
Note how the examples alleviate the need for long descriptive documentation and allow the author to add a succinct note in an XML comment exactly where it is relevant. Note also that CDATA sections alone are not sufficientthey only protect special characters but are not elements themselves , so a pre element is added for each example.
Structural information , such as descriptions of content models and attribute data types. In a grammer-based schema, this information is already formally expressed by the schema itself, but depending on users' familiarity with your particular schema notation, it may be beneficial to reword it in plain English (possibly adding some non-formalizable usage requirements or suggestions). For rule-based schemas such as Schematron, providing this information is even more of a necessity because such a schema may not contain any coherent formal description of document structure at all.
Metadata. Finally, it is a good practice to document your schema's metadata, such as authorship and copyright information. For a schema that has already been in use, it is especially important to have a change log documenting all changes made to the current version since its first public release, including dates, authors, and details for each change (see also 2.2.2.2 ). This information should be given prominently at the top of a schema document.
An important part of a source definition is a set of document templates. A template is an example document with dummy (or no) data content, showing a typical layout of a valid XML document, usually with comments. Users can take the template as a starting point for creating a new document simply by filling in content between the template's supplied tags. You should provide a template for each sufficiently distinct type of source document.
Even if the users of your source definition (i.e., site editors and maintainers) have never worked with XML before, the concept of storing content units within matching pairs of tags should not be hard to grasp. It's actually a very natural way to think even for nontechnical people. However, starting a new document from scratch may be difficult even if you know what you want to get, and this is where page templates are invaluable.
A part of the difficulty is that, along with the meaningful content, an XML document may also contain a lot of metadata such as the XML declaration ( <?xml ... ?> ), a stylesheet processing instruction ( <?xml-stylesheet ... ?> ), a DOCTYPE declaration, or an internal DTD subset. To many "light" XML users, these constructs look (deservedly) much more frightening and indecipherable than the body of the document. So, providing a template with all this stuff already filled in (and making sure it doesn't need to change for each new document) is usually a good idea.
As far as the document layer definitions are concerned , DTDs support basic constraints such as element type names, attribute lists, and content models. You cannot use DTDs to check the data type of an element's content, [13] express the dependence of an element's content model on the presence of an attribute, or perform complex syntactic checks of data values. As for the super-document layer, it's totally out of reach for DTDs.
[13] There exists a DTD extension for this purpose called Datatypes for DTDs ; see for more information. Open source code is available at.
[13] There exists a DTD extension for this purpose called Datatypes for DTDs ; see for more information. Open source code is available at.
On the other hand, the DTD notation stands apart from other schema languages in that it is defined right in the XML Recommendation. [14] Also, DTDs have been traditionally used for defining XML vocabularies (including W3C standards), and the DTD notation is still the default schema language in many existing XML tools and frameworks. Another big advantage of this language is that a DTD validator is built into every validating XML parser, so you don't need any additional software for validation. Let's look at some of the issues related to using DTDs in a web site source definition.
[14]
[14]
DTDs are not namespace-aware, simply because namespaces were introduced to XML after the first version of the XML Recommendation, including the DTD syntax, was finalized. You can still use DTDs to declare and validate namespace-qualified namesbut they must include a fixed namespace prefix and the ":" separator to be treated by a DTD validator as a whole.
For example, you can write a DTD declaration for an element type named xsl:stylesheet to specify its content model and attributes. However, from the DTD viewpoint, this element type will have nothing in common with xsl:template and, more importantly, nothing in common with my:stylesheet even if the prefix my was declared for the same URI as xsl .
A partial workaround involves declaring names without prefixes in your DTD and always using the default (prefixless) namespace for them in your XML documents. By providing prefixless DTD declarations for your primary namespace and declarations with fixed prefixes as needed for foreign-namespace elements, you can to some extent reconcile the limitations of DTDs with the requirements of modern multi-namespace documents. (Although this approach is not likely to work if you freely mix elements from arbitrary namespaces in your documents, such documents would not be DTD-valid in any case, so the DTD would be irrelevant.)
DTDs don't need a separate processor for validation. Any validating XML parser (possibly including the one that will read your documents to pass them on to the XSLT processor) will report DTD errors immediately. All you need to do is link each of your documents to its DTD, as follows :
< !DOCTYPE page SYSTEM "page.dtd"> <page> <!--...--> </page>
Here, page.dtd is the name of the file containing your DTD (in this example, it is supposed to be in the same directory as your document file; if it is not, you can provide a relative path to the file or a URI instead). Note that the DOCTYPE declaration must also mention the name of the root element type of your document ( page ).
An XSLT processor with a validating parser will first read in the document and check it against the DTD. Only if it is valid will transformation begin. However, the same document without the DOCTYPE declaration will be transformed just as well, except that any DTD conformance errors will not be caught (only well-formedness errors, such as unclosed elements or missing quotes in attributes, will halt the parser). Therefore, you should use DOCTYPE -less documents if you have a schema other than a DTD and a corresponding processor for validation.
One feature of XML that you can't use without a DTD is mnemonic entity references , such as ü for " | https://flylib.com/books/en/1.501.1.28/1/ | CC-MAIN-2019-39 | refinedweb | 6,266 | 50.87 |
Hello,
I've recently used the toolbar from wxAgg backend:
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
I've got a problem when trying to freeze my app now because I get this
message when trying to invoke the toolbar:
Traceback (most recent call last):
File "CommandPanel.pyo", line 80, in OnOpenFile
File "AnalystPanel.pyo", line 33, in addPanel
File "Filter.pyo", line 50, in createWidget
File "A1Filter.pyo", line 70, in fillWidget
File "matplotlib\backends\backend_wx.pyo", line 1548, in __init__
File "matplotlib\backend_bases.pyo", line 1524, in __init__
File "matplotlib\backends\backend_wx.pyo", line 1570, in _init_toolbar
File "matplotlib\backends\backend_wx.pyo", line 1405, in _load_bitmap
IOError: Could not find bitmap file "mpl-data\images\home.png"; dying
It is really strange because I've put this in my setup.py:
import matplotlib
data_files = matplotlib.get_py2exe_datafiles()
So there is a directory mpl-data/images so should work.
(other files are well found like fonts etc.)
Any guys has had this issue? (Matplotlib 0.98.1)
Laurent | http://sourceforge.net/p/matplotlib/mailman/matplotlib-users/thread/48720bd7.0d375e0a.71ae.2562@mx.google.com/ | CC-MAIN-2014-52 | refinedweb | 167 | 53.78 |
27 October 2008 21:53 [Source: ICIS news]
HOUSTON (ICIS news)--Solutia's US ethyl acetate (etac) plant in Massachusetts near Springfield began a six-day scheduled turnaround this week and will restart on 2 November, a market source said on Monday.
The company completed a similar turnaround at its ?xml:namespace>
The two etac plants combined will produce about 23,000 tonnes of etac next year, the source said. BP Chemicals markets the material.
A Solutia spokesman offered no immediate comment on the turnaround.
A buyer said the Solutia plant's turnaround would likely have little impact on etac pricing because of its small output. The
While etac pricing has held steady in the past month, the buyer said it expected etac to decline the way prices for aliphatics and aromatics have, following the falling price of crude in recent weeks.
"In time it will hit everyone," the buyer said.
US etac contract prices remained unchanged last week, ranging from 70-74 cents/lb ($1,543-1,631/tonne, €1,234-1,304/tonne), according to global chemical market intelligence service ICIS pricing.
Major
($1 = €0.80)
For more on ethyl acetate, visit ICIS chemical intelligence
To discuss issues facing the chemical industry go to ICIS connect | http://www.icis.com/Articles/2008/10/27/9166672/us-etac-plant-to-restart-2-nov-after-turnaround.html | CC-MAIN-2014-52 | refinedweb | 208 | 62.38 |
Let us begin with our next day, a recap:
- Compiling TS files with TSC
- Setting up tsconfig.json
- Structuring our code to output everything to build folder
It is good to know the above, but not very helpful when you start a real project. So let us code something today and serve a file that makes our work visible via an HTTP server. Also before diving deep into something, I love the ability to include files so that I can organize my code properly. Thus let us set up the ExpressJS server and play with importing files.
Setting up Http Server – ExpressJS
Let me install ExpressJS with the simplest standard way we all know:
npm install express --save
Further, as it goes without saying let us create
server.ts that will have our server code. With ES6 I use to import express with a simple import as:
import express from "express";
But unfortunately, that does not work with typescript for CommonJS/AMD/UMD modules, the proper way to import a CommonJS module is as below:
import express = require("express");
I also came across the following:
import * as express from "express";
but apparently, that is not the correct way to do it because
import * as creates an identifier that is a module object, emphasis on an object. According to the ES6 spec, this object is never callable or
newable – it only has properties. Attempting to use
import * as express and then invoking
express() is always illegal according to the ES6 spec. In some runtime+transpilation environments, this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.
We will understand the imports in more details after we set up the HTTP server ;)
Setting up the standard “ Hello, World! ” example by official ExpressJS docs in our
server
.js
import express = require("express"); const app = express(); const port = 3000; app.get('/', (req, res) => res.send('Hello, World!')); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
and now running from the project root terminal:
./node_modules/.bin/tsc && node build/server.js
Everything works great and accessing I can see the glorious “Hello, World!”
But his is not the end, there is more to the above example, we can specify types for ExpressJS in TS project as following and can actually use the benefit of TypeScript.
npm i @types/express --save-dev
and thus this gives the developer a great autocomplete feature and exposing the methods & properties available, which is great:
and thus making our
server.js more typed as below:
import express = require("express"); const app: express.Application = express(); const port: number = 3000; app.get('/', (req: express.Request, res: express.Response): express.Response => { return res.send('Hello, World!'); }); app.listen(port, (): void => console.log(`Example app listening on port ${port}!`));
I can see typescript is really really simple and figured out the below myself for functions:
function (arg1: <type>, arg2: <type>): <function-return-type> { // return something of <function-return-type> }
And string , number , boolean & void are very general types mostly available in any programming language, but for express.Application , express.Request & express.Response types, the autocomplete helped me!
The above is really great.
I already have a feeling that I am going to use TypeScript the rest of my life!
Back to our HTTP server, we really don’t want to server “Hello, World!” but we would like our TS compiled javascript to be executed on the home page, so I updated the server.ts to following:
import express = require("express"); const path = require("path"); const app: express.Application = express(); const port: number = 3000; app.use("/static", express.static(path.join(__dirname, '..', 'build'))); app.get('/', (req: express.Request, res: express.Response): express.Response => { return res.send(`<!DOCTYPE html> <html> <head> <title>My experiments with TypeScript</title> /index.js" async></script> </body> </html> `); }); app.listen(port, (): void => console.log(`Example app listening on port ${port}!`));
I have done nothing special here, just sending HTML with a bit of styling and have asked express to server static files from build folder. I know it is not ideal right now as
server.js can also be served from the static path, but this is just temporary and for learning.
Updating the index.ts file
We have a simple logger output that is being served via express and can include our code from compiled index.js, so let us update index.ts to the following, giving it the ability to log content inside the logger:()}: ${JSON.stringify(s)}`; logger.appendChild(logWrapper); } log(str);
You may test your server by running the following command:
./node_modules/.bin/tsc && node build/server.js
You should see the following screen if you visit
Pretty sleek right!
Just one last thing and we are almost done with our most simplistic ExpressJS setup with TypeScript.
I really do not want to restart the server whenever I update the code base, thus adding nodemon to our repo. Also, I would not want to compile the code again and again so would start the TS compiler with
--watch option enabled, start server with nodemon and update the start script to execute both with concurrently node package
npm i nodemon concurrently --save
And updating our start script to:
"scripts": { "start": "tsc && concurrently -n \"TypeScript,Nodemon\" \"npm run ts-watch\" \"npm run server-watch\"", "ts-watch": "tsc -w", "server-watch": "nodemon --watch build/server.js build/server.js", "test": "echo \"Error: no test specified\" && exit 1" }
I guess that should do be already and would be helpful for our learning and research further!
Before moving on to Types and other details, I would like to learn more about imports and compatibility with CommonJS, AMD, UMD & ES6 etc, so will focus more on that tomorrow!
The code base of this episode, Part 2, is available at:
The post ExpressJS Server with TypeScript – Part 2 – The novice programmer appeared first on Atyantik Technologies.
Discussion (0) | https://dev.to/tirthbodawala/expressjs-server-with-typescript--part-2--the-novice-programmer-2p98 | CC-MAIN-2021-39 | refinedweb | 990 | 55.95 |
This action might not be possible to undo. Are you sure you want to continue?
Introduction
IMMIGRATION
A Critical Analysis
Canaoa is a lano ol immigrants.¨ What ooes this olt repeateo
phrase mean? The answer seems clear enough Canaoa was built
bv ano is maoe up ol people ol manv oillerent races. nationalities.
cultures ano languages. However. this cozv pluralistic notion hioes
manv complicateo realities ol both the historv ol immigration
ano the experience ol coming to Canaoa as an immigrant tooav.
On the surlace migration appears to be a straightlorwaro process.
Feople move. either bv choice or oisplacement. lrom one countrv to
another. Each countrv sets its own criteria. or immigration policv.
lor people entering to settle permanentlv or to work temporarilv.
Ior the migrant. the move can be riskv ano mav represent oppor-
tunitv. mav emboov hope ano lear. Ior the receiving countrv. the
innux ol new people mav be benencial economicallv. sociallv ano
culturallv. But immigration raises a complex web ol political ano
social issues that are mireo in a countrv`s specinc historv. values ano
hierarchies. Ior Canaoa. the motives lor encouraging immigration
incluoe ensuring population ano economic growth ano preserving
territorial bounoaries. These motives change over time. as Canaoa
shilts its own internal priorities ano its place on a global stage.
There continues to be a perception that Canaoa`s laws make it
easv lor immigrants to come here ano that Canaoa is more welcom-
8 ABOUT CANADA: IMMIGRATION
ing ano hospitable to new immigrants than manv other countries.
The perceptions. however. are not alwavs true or true lor evervone.
This book criticallv examines these perceptions ano investigates the
historv ol how ano which immigrants contributeo to the making
ol Canaoa. We oo not take as a given that all immigrants` lives are
enhanceo in Canaoa. Like some earlv immigrants who lelt mioole-
class ano privilegeo lives lor the haroship ol pioneer lile in Canaoa.
manv immigrants who come to Canaoa tooav oo not experience
an improvement in their lives. Iurthermore. the selection ol who
gets to come to Canaoa. while no longer explicitlv baseo on race
as was historicallv the case. is still preoicateo on a certain class ol
immigrants. who olten oiscover that neither their eoucation nor
their work experience allows them to continue their prolession or
occupation. In aooition to these issues. this book explores pressing
issues such as temporarv labour programs. labour market integra-
tion issues. incluoing lack ol skills` recognition ano unoocumenteo
labour. ano the role ol the state in welcoming ano integrating new
citizens.
Migration
Migration is a global phenomenon. ano there are more people on
the move tooav than ever belore. The reasons incluoe economic
oisplacement. lamilv reunincation. environmental oegraoation. war
ano civil unrest ano sometimes. quite simplv. the search lor a better
lile. The International Organization lor Migration estimates that
there are approximatelv 21! million international migrants in the
worlo tooav. which is about 3.1 percent ol the global population. This
number ol migrants woulo equal the nlth most populous countrv in
the worlo. Contrarv to the mvth that it is primarilv men who migrate.
!9 percent ol international migrants are women.
1
As a receiving countrv lor migrants. Canaoa lalls right in the
mioole ol the top ten. hosting approximatelv 7.2 million migrants
in 2008 see Table 0.1. The top countrv to host immigrants is the
IMMIGRATION: A CRITICAL ANALYSIS 9
Uniteo States !2.8 million. lolloweo bv the Russian Ieoeration.
Germanv ano Sauoi Arabia. While Canaoa mav not be the nrst
countrv ol choice lor international migrants. we oo have a larger
proportion ol immigrants 21.o percent in our general popula-
tion than either the Uniteo States 13.8 percent or the Russian
Ieoeration 8.7 percent. The top three migrant-senoing countries
are China 35 million. Inoia 20 million ano the Fhilippines 7
million.
2
Manv global migration trenos run counter to the mvths
we commonlv associate with immigration. Ior example. the major-
itv ol Alrican migrants move within Alrica. while Asia. the largest
source ol temporarv workers. is also characterizeo bv large nows
ol intra-regional migration. particularlv in China ano Inoia. The
Mioole East is the most important oestination lor temporarv Asian
workers. ano temporarv migrant labour is on the rise in Europe.
the Uniteo States ano Canaoa. In the case ol Canaoa. the number
ol migrants coming through temporarv worker channels has latelv
exceeoeo those coming through the permanent resioencv categorv.
+W]V\Za 6]UJMZWN 5QOZIV\[
UQTTQWV[
Uniteo States !2.8
Russian Ieoeration 12.3
Germanv 10.8
Sauoi Arabia 7.3
Canaoa 7.2
Irance o.7
Uniteo Kingoom o.5
Spain o.!
Inoia 5.!
Ukraine 5.3
Source: International Organization for Migration, “World Migration 2008: Managing Labour Mobility in the Evolving
Global Economy: Regional and Country Figures,” at <iom.int/jahia/Jahia/about-migration/facts-and-figures/regional-
and-country-figures>. (n.d.).
Table 0.1 Top Ten Countries Hosting International Migrants, 2008
10 ABOUT CANADA: IMMIGRATION
Myths about Immigration
There exists a plethora ol mvths about immigration. Belore explor-
ing some ol the more complex issues surrounoing immigration. we
oiscuss ano oebunk some ol the most olten citeo beliels arouno
immigrants ano immigration to Canaoa.
It Is Easy to Immigrate to Canada
Canaoa`s point svstem makes it verv oilncult except lor the most
highlv skilleo ano highlv eoucateo people to achieve enough points
to even be consioereo lor immigration. In lact. it is estimateo that
manv Canaoians woulo not pass the point svstem test il it was ap-
plieo to them.
Immigrants Steal Jobs from Canadian Workers
Although the majoritv ol immigrants who come to Canaoa as per-
manent resioents are highlv skilleo prolessionals. their qualincations
are lrequentlv not recognizeo. Consequentlv. thev are not able to
compete with Canaoians lor jobs in their nelo. In lact. it is estimateo
that new immigrants are three times more likelv to be working in
low-skilleo jobs than their Canaoian counterparts. Iurthermore.
between 1993 ano 2001. even semi-establisheo immigrants those
who hao been in the countrv lor ten vears or less hao higher rates
ol overqualincation than Canaoians ooing similar work.
3
Immigrants are Destitute, Uneducated and a Drain on the System
Canaoa`s immigration svstem is oesigneo to bring in more Skilleo
Workers than anv other categorv ol immigrants. Most immigrants
come to Canaoa with aovanceo oegrees. prolessional status ano a
high level ol experience. all ol which contributes to giving Canaoa
an eoge in the competitive global market. Immigrants who come to
Canaoa as business migrants are requireo to have a minimum net
worth ol S800.000¦ Upon settling in Canaoa. thev establish busi-
nesses ano create new jobs lor Canaoians. Regaroless ol the channel
ol immigration. whether it be Economic or Iamilv Class. immigrants
IMMIGRATION: A CRITICAL ANALYSIS 11
are requireo to bring a certain amount ol monev to ensure that thev
will not be oepenoant on Canaoa`s social securitv svstem.
Immigrants Bring Crime to Canada
Immigrants actuallv have lower crime rates than the Canaoian-born
population. ano accoroing to the International Centre lor Criminal
Law Relorm ano Criminal ]ustice Folicv. immigrants are much
less involveo in criminal activitv than are those who were born in
Canaoa.¨
!
Immigrants Do Not Want to Work
Most immigrants come to Canaoa because thev seek a better lile lor
themselves ano their chiloren. As part ol that new lile. most immi-
grants hope to nno suitable ano lulnlling work. However. lor manv
immigrants. nnoing a oecent job is lrequentlv more challenging than
thev anticipateo. Manv immigrants who are ooctors ano engineers
eno up working as orivers. cleaners ano securitv agents because thev
cannot lano a job in their nelo.
Theories of Migration
There are numerous theories about whv people migrate. On the lace
ol it. most people move because thev want a better lile. While this
reason lor migration is almost alwavs true. there are olten other more
complex lactors at work that compel people to uproot themselves ano
their lamilies lrom their jobs. homes. lrienos ano lamilies in oroer to
attempt a new lile somewhere else. Some ol these lactors mav involve
inoivioual experiences i.e.. loss ol lano. oeath in the lamilv. while
others mav be more structural i.e.. civil unrest. economic oownturn.
Whatever the reason. the realitv is that migration is almost never an
easv oecision or process.
There are two approaches to looking at migration the inoi-
vioual ano the structural. The inoivioual approach. also known as
human capital theorv.¨ argues that inoiviouals will rationallv assess
which countrv is ollering the best emplovment ano wage prospects
12 ABOUT CANADA: IMMIGRATION
lor their skills ano experience ano make their oecisions accoroinglv.
The limitation to this approach is that migration oecisions are
rarelv maoe bv lone inoiviouals who simplv evaluate monev ano
jobs. Migration oecisions are lrequentlv innuenceo bv other lamilv
members. contacts inoiviouals have in other countries. the oesirabilitv
ol locating to other countries. ano a host ol other lactors.
Another wav ol looking at migration is the structural approach.
which is also relerreo to as push-pull theorv.¨ This theorv at its
most simple argues that there are lactors. such as povertv. unemplov-
ment ano connict to name just a lew. that push people out ol their
countries. ano other lactors. such as jobs. economic prosperitv ano
political stabilitv. that pull those same people into other countries.
There are a number ol variations on this theorv as well. Ior exam-
ple. the oual or segmenteo labour market theorv¨ asserts that a
capitalist svstem will create two levels ol emplovment high-skilleo
ano low-skilleo. High-skilleo emplovment consists ol jobs that are
well-paio. secure ano oller job protection ano benents. Low-skilleo
emplovment. also known as the three-D jobs oirtv. oangerous ano
oilncult are lrequentlv oilncult to nll because most locals are not
interesteo in working unoer those conoitions. Thus. countries olten
import immigrants to work in low-skilleo jobs. olten louno in the
construction. agriculture ano service inoustries. A secono variation
ol the push-pull theorv is the neoclassical economic theorv.¨ which
argues that international migration is connecteo to the global supplv
ano oemano lor labour. In this theorv. migrants lrom countries with
surplus labour are attracteo to the potential lor high wages ano gooo
jobs in countries that are experiencing labour shortages. Lastlv. the
worlo svstems theorv¨ posits that international migration is a con-
sequence ol global capitalism. The inoustrial oevelopment ol rich
nations the pull countries has createo structural economic problems
in poor countries the push countries. resulting in the large-scale
international migration ol people lrom the Thiro Worlo¨ to the
Iirst Worlo.¨
5
IMMIGRATION: A CRITICAL ANALYSIS 13
How This Book Is Organized
The book contains seven chapters. with Chapter 1 examining how
Canaoian immigration policv lrom 18o7 to 19o7 was explicitlv lor-
mulateo with the goal ol creating ano maintaining a white settler
societv. This chapter also explores immigration policies since 19o7.
alter the elimination ol race-baseo criteria. ano oiscusses whether
racial oiscrimination has been eliminateo. Chapter 2 outlines current
immigration policv ano explains how it works. It analvzes the shilts
in immigration policv. noting the oevolution ol leoeral government
control ol the process ano the increasing involvement ol other ac-
tors such as post-seconoarv institutions. provincial governments ano
emplovers. While the policies are no longer baseo on race. thev are
still highlv selective. lavouring mioole-class prolessionals.
Chapter 3 aooresses labour issues lor immigrant prolessionals
ano skilleo workers. As immigration trenos have shilteo with respect
to source countries ano annual quotas. prolessionals are experiencing
greater oilnculties in establishing themselves in their prolessions than
immigrants ol the past. Chapter ! oeals with integration issues rang-
ing lrom language training to accessing culturallv appropriate health
ano social services. Ior the most recent wave ol immigrants. manv
ol whom come lrom the Global South. integrating into Canaoian
societv is a challenging process lraught with manv obstacles incluoing
povertv ano social isolation. This chapter investigates the lramework
ol settlement services in Canaoa ano whether these loster the social
inclusion ol new immigrants or exacerbate their social exclusion.
Chapter 5 oiscusses the oramatic growth in the numbers ol tem-
porarv workers ano work programs in the past nve vears. Iollowing on
the heels ol both Europe ano the Uniteo States. Canaoa is witnessing
an explosion in temporarv worker programs. These programs import
migrants. tvpicallv lrom countries in the Global South. to perlorm
labour lor a specineo perioo. Upon completion ol this perioo. mi-
grants are sent back to their countries ol origin. Temporarv labour
programs are oesigneo to meet the labour neeos in inoustries where
14 ABOUT CANADA: IMMIGRATION
there is a shortage ol Canaoians workers. Lauoeo as a panacea lor
both Canaoian inoustrv ano poor workers lrom the South. Canaoian
temporarv labour programs are being heraloeo across the globe. But
who reallv benents lrom these programs? Are structural inequali-
ties in these programs ushering in a new lorm ol slave¨ labour?
This chapter highlights the Seasonal Agricultural Migrant Worker
Frogram to examine how temporarv labour programs in Canaoa
are creating a new unoerclass ol labourers.
Non-status migrants is the theme ol Chapter o. Ferlorming
invisible labour lrom cleaning olnces to constructing basements
Canaoa`s estimateo 200.000 unoocumenteo workers lorm an
integral vet hiooen part ol the national worklorce. Ior example. the
construction inoustrv in Ontario emplovs over 7o.000 illegal workers.
This chapter explores the rise ol unoocumenteo labour in Canaoa
ano contemporarv oebates surrounoing this sector ol workers.
The nnal chapter argues that there is a neeo lor leoeral. provin-
cial ano municipal levels ol government to work together to improve
the outcomes ol immigration lor both the inoiviouals who migrate
ano lor the communities in which thev live. The unoer ano unem-
plovment ol immigrants in Canaoa is the result ol svstemic policies
ano practices. such as not recognizing international creoentials ano
work experience as equivalent to Canaoian. ano thev can be changeo.
Immigrants oeserve to be treateo with more respect in Canaoa. The
aim ol this book is to contribute to making much neeoeo changes to
immigration policies ano practices. emplover hiring practices ano
Canaoians` attituoes towaros immigrants.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview. | https://www.scribd.com/document/50285788/About-Canada-Immigration | CC-MAIN-2016-50 | refinedweb | 2,413 | 60.31 |
cswinMinidumpWriter Class ReferenceHelper to write minidumps on Win32. More...
#include <csutil/win32/minidump.h>
Detailed DescriptionHelper to write minidumps on Win32.
- minidump.h.
Member Typedef Documentation
Callback that can be provided by the application to further deal with the crash dump file.
Definition at line 45 of file minidump.h.
Member Function Documentation
Disable the built-in crash handler.
Enable the built-in crash handler.
Sets up an exception handler that creates a dump using WriteWrappedMinidump(). In case a custom handler is provided, it is called. Otherwise, a message box containing the dump file is displayed.
Set the object registry used by the built-in crash handler.
It is needed to collect some extra information, notable the reporter log.
- Remarks:
- Not setting this value will not result in failure later.
Write a dump of the current state of the process.
- Returns:
- The filename where the dump was written to. Is created in a location for temp files.
Write a mini dump that is wrapped inside a zip and also contains a textual stack trace and the reporter log file.
- Returns:
- The filename where the zip was written to. Is created in a location for temp files.
The documentation for this class was generated from the following file:
- csutil/win32/minidump.h
Generated for Crystal Space 1.2.1 by doxygen 1.5.3 | http://www.crystalspace3d.org/docs/online/api-1.2/classcswinMinidumpWriter.html | CC-MAIN-2015-48 | refinedweb | 223 | 69.89 |
In this tutorial, we'll look at how to prevent a Celery task dependent on a Django database transaction from executing before the database commits the transaction. This is a fairly common issue.
Django + Celery Series:
Contents
Objectives
After reading, you should be able to:
- Describe what a database transaction is and how to use it in Django
- Explain why you might get a
DoesNotExisterror in a Celery worker and how to solve it
- Prevent a task from executing before the database commits a transaction
What is a database transaction?
A database transaction is a unit of work that is either committed (applied to the database) or rolled back (undone from the database) as a unit.
Most databases use the following pattern:
- Begin the transaction.
- Execute a set of data manipulations and/or queries.
- If no error occurs, then commit the transaction.
- If an error occurs, then roll back the transaction.
As you can see, a transaction is a very useful way to keep your data far away from chaos.
How to use database transactions in Django
You can find the source code for this tutorial on Github. If you decide to use this code as you work through this post, keep in mind that the username must be unique. You could use a random username generator for testing purposes like Faker.
Let's first take a look at this Django view:
def test_view(request): user = User.objects.create_user('john', '[email protected]', 'johnpassword') logger.info(f'create user {user.pk}') raise Exception('test')
What happens when you visit this view?
Default behavior
Django's default behavior is to autocommit: Each query is directly committed to the database unless a transaction is active. In other words, with autocommit, each query starts a transaction and either commits or rolls back the transaction as well. If you have a view with three queries, then each will run one-by-one. If one fails, the other two will be committed.
So, in the above view, the exception is raised after the transaction is committed, creating the user
john.
Explicit control
If you'd prefer to have more control over database transactions, you can override the default behavior with transaction.atomic. In this mode, before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. On the other hand, if the view produces an exception, Django rolls back the transaction. If you have three queries and one fails, then none of the queries will be committed.
So, let's re-write the view using
transaction.atomic:
def transaction_test(request): with transaction.atomic(): user = User.objects.create_user('john1', '[email protected]', 'johnpassword') logger.info(f'create user {user.pk}') raise Exception('force transaction to rollback')
Now the
user create operation will rollback when the exception is raised, so the user will not be created in the end.
transaction.atomic is a very useful tool which can keep your data organized, especially when you need to manipulate data in models.
It can also used as decorator like so:
@transaction.atomic def transaction_test2(request): user = User.objects.create_user('john1', '[email protected]', 'johnpassword') logger.info(f'create user {user.pk}') raise Exception('force transaction to rollback')
So if some error gets raised in the view, and we do not catch it, then the transaction would rollback.
If you want to use
transaction.atomic for all view functions, you can set
ATOMIC_REQUESTS to
True in your Django settings file:
ATOMIC_REQUESTS=True # or DATABASES["default"]["ATOMIC_REQUESTS"] = True
You can then override the behavior so that the view runs in autocommit mode:
@transaction.non_atomic_requests
DoesNotExist exception
If you don't have a solid understanding of how Django manages database transactions, it can be quite confusing when you come across random database-related errors in a Celery worker.
Let's look at an example:
@transaction.atomic def transaction_celery(request): username = random_username() user = User.objects.create_user(username, '[email protected]', 'johnpassword') logger.info(f'create user {user.pk}') task_send_welcome_email.delay(user.pk) time.sleep(1) return HttpResponse('test')
The task code looks like:
@shared_task() def task_send_welcome_email(user_pk): user = User.objects.get(pk=user_pk) logger.info(f'send email to {user.email} {user.pk}')
- Since the view uses the
transaction.atomicdecorator, all database operations are only committed if an error isn't raised in the view, including the Celery task.
- The task is fairly simple: We create a user and then pass the primary key to the task to send a welcome email.
time.sleep(1)is used to introduce a race condition.
When run, you will see the following error:
django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.
Why?
- We pause for 1 second after enqueueing the task.
- Since the task executes immediately,
user = User.objects.get(pk=user_pk)fails as the user is not in the database because the transaction in Django has not yet been committed.
Solution
There are three ways to solve this:
Disable the database transaction, so Django would use the
autocommitfeature. To do so, you can simply remove the
transaction.atomicdecorator. However, this isn't recommended since the atomic database transaction is a powerful tool.
Force the Celery task to run after a period of time.
For example, to pause for 10 seconds:
task_send_welcome_email.apply_async(args=[user.pk], countdown=10)
Django has a callback function called
transaction.on_committhat executes after a transaction successfully commits. To use this, update the view like so:
@transaction.atomic def transaction_celery2(request): username = random_username() user = User.objects.create_user(username, '[email protected]', 'johnpassword') logger.info(f'create user {user.pk}') # the task does not get called until after the transaction is committed transaction.on_commit(lambda: task_send_welcome_email.delay(user.pk)) time.sleep(1) return HttpResponse('test')
Now, the task doesn't get called until after the database transaction commit. So, when the Celery worker finds the user, it can be found because the code in the worker always runs after the Django database transaction commits successfully.
This is the recommended solution.
It's worth noting that you may not want your transaction to commit right away, especially if you're running in a high-scale environment. If either the database or instance are at high-utilization, forcing a commit will only add to the existing usage. In this case, you may want to use the second solution and wait for a sufficient amount of time (20 seconds, perhaps) to ensure that the changes are made to the database before the task executes.
Testing
Django's
TestCase wraps each test in a transaction which is then rolled back after each test. Since no transactions are ever committed,
on_commit() never runs either. So, if you need to test code fired in an
on_commit callback, use TransactionTestCase in your test code.
Database transaction in a Celery task
If your Celery task needs to update a database record, it makes sense to use a database transaction in the Celery task.
One simple way is
with transaction.atomic():
@shared_task() def task_transaction_test(): with transaction.atomic(): from .views import random_username username = random_username() user = User.objects.create_user(username, '[email protected]', 'johnpassword') user.save() logger.info(f'send email to {user.pk}') raise Exception('test')
A better approach is to write a custom
decorator which has
transaction support:
class custom_celery_task: """ This is a decorator we can use to add custom logic to our Celery task such as retry or database transaction """ def __init__(self, *args, **kwargs): self.task_args = args self.task_kwargs = kwargs def __call__(self, func): @functools.wraps(func) def wrapper_func(*args, **kwargs): try: with transaction.atomic(): return func(*args, **kwargs) except Exception as e: # task_func.request.retries raise task_func.retry(exc=e, countdown=5) task_func = shared_task(*self.task_args, **self.task_kwargs)(wrapper_func) return task_func ... @custom_celery_task(max_retries=5) def task_transaction_test(): # do something
Conclusion
This tutorial looked at how to make Celery work nicely with Django database transactions.
The source code for this tutorial can be found on GitHub.
Thanks for your reading. If you have any question, please feel free to contact me.
Django + Celery Series: | https://testdriven.io/blog/celery-database-transactions/ | CC-MAIN-2020-40 | refinedweb | 1,331 | 50.53 |
03 April 2012 07:46 [Source: ICIS news]
By Feliana Widjaja
SINGAPORE (ICIS)--International titanium dioxide (TiO2) producers are aiming for another round of price hikes in the second quarter in Asia amid rising feedstock titanium ore prices that are showing no signs of abating, industry sources said on Tuesday.
DuPont and Cristal Global have announced price hikes of $200/tonne (€225/tonne) CFR (cost & freight) ?xml:namespace>
In addition, Huntsman and Ishihara Sangyo Kaisha (ISK) have declared a $300/tonne and $400/tonne price increment, respectively.
These price augmentations are effective from 1 April for the Asia-Pacific region.
TiO2 prices were last assessed at $4,000-4,200/tonne CFR Asia on 30 March, hovering at this level since the beginning of the year, ICIS data shows.
Strong resistance from buyers has hampered producers’ intention to achieve the full price increase of $200-350/tonne that was initially announced in late 2011 for the Asia Pacific region, effective from 1 January 2012.
As a result, price rollovers were evident in first quarter settlements.
A number of TiO2 suppliers managed to achieve partial price increases but these were said to be incremental and they were staggered across the first quarter instead of being implemented in full at once.
Several buyers managed to achieve some price reductions in the first quarter of this year, especially those who had paid around the high end of the range in the fourth quarter of last year, sources said.
Demand in the first quarter was generally lacklustre, affected by the tightening of monetary policies in
“Demand is softer than normal because of the hangover of what happened in Q4. People are still concerned about the economic situation”, a US-based producer said.
Despite the lack of success in implementing the full price increase in the first quarter, suppliers are gearing up for another round of price hikes in the second quarter.
Producers said that price increases are necessary to offset the impact of soaring values of feedstock titanium and rutile, where in some cases, prices have gone up by 70-75% from the second half of 2011 to the first half of 2012.
“Actually, an increase of $200/tonne is too small to cope with raw material increases,” a Japan-based producer said.
Furthermore, producers are expecting demand to recover slowly, starting late in the first quarter or early in the second quarter when the paints and coatings season traditionally starts.
"TiO2 demand tends to follow gross domestic product (GDP) growth. Coupled with high raw material costs and the absence of significant new TiO2 capacities coming on-stream in the next two to three years, we expect the market to remain strong," another US-based TiO2 producer said.
TiO2 buyers are determined to put up stiff resistance to the latest round of price hikes.
Buyers contend that the price increases are not justified as the tight supply situation seen last year seemed to have eased this year amid slower demand which was a result of macroeconomic woes.
Furthermore, buyers are finding it tough to pass the additional costs on to their end-users, they said.
The ample availability of lower-priced cargoes from
“There may be some price increase but not as high as producers’ expectations because of the supply from
Although the TiO2 price rally seen in 2011 is unlikely to be repeated this year as demand will be vulnerable to the anticipated global economic slowdown, prices are likely to remain firm because of persistently high feedstock titanium ore prices, market sources said.
TiO2 prices surged by $1,200/tonne in 2011, a jump of around 40% from values at $2,800-3,000/tonne CFR Asia in early January 2011, according to ICIS data.
Cost of raw materials like TiO2 and others are expected to grow 5-10% this year, | http://www.icis.com/Articles/2012/04/03/9547133/tio2-makers-keen-on-price-hikes-in-asia-on-steep-feedstocks.html | CC-MAIN-2014-52 | refinedweb | 638 | 53.04 |
I got this program which I have pasted below is not behavouring as I would expect it to.
It works fine but the thing is that it is not displaying the random numbers in the range i want it to, which is 1000-1112.
When I run it I find that the numbers are outside of this range!
I have no idea why?????????
Could someone help me out :)
Many thanks :)
#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand( time(0));
for ( int i = 1; i <= 20; i++ ) {
cout << setw( 10 ) << ( 1000 + rand() % 1112 );
if ( i % 5 == 0 )
cout << endl;
}
return 0;
} | http://cboard.cprogramming.com/cplusplus-programming/11405-random-numbers-printable-thread.html | CC-MAIN-2015-27 | refinedweb | 108 | 93.85 |
File contents and manipulation
Reading from and writing to files was one of the first things we looked at. For some programs, however, we're not just concerned with the contents of files, but with files and folders themselves. This is especially likely to be the case for programs that have to operate as part of a work flow involving other tools and software. For example, we may need to copy, move, rename and delete files, or we may need to process all files in a certain folder.
Although it seems like a simple task (after all, the file manager tools that come with your operating system can carry most of them out), file manipulation in a language like Python is actually quite tricky. That's because the code that we write has to function identically on different operating systems – including Windows, Linux and Mac machines – which may handle files quite differently.
Thankfully, Python includes a couple of modules that take care of these differences for us and provide us with a set of useful functions for manipulating files. The modules' names are
os (short for Operating System) and
shutil (short for SHell UTILities). In the next section we'll see how they can be used to carry out various common (but important) tasks.
A note on the code examples
Since the code examples in this page unavoidably involve interaction with the operating system, some of the details will be operating system specific. In other words, the examples in this page might not run on your computer without some tweaking. In addition to the paths being different, the success of the code examples for many functions relies on the files and folders actually being present on the computer on which the examples are run. The code examples in this page will use Linux style paths, and will refer to folders and files on my computer, so if you want to try running them, you'll probably need to change the paths to refer to files on your own computer.
Basic file manipulation
To rename an existing file, we import the
os module, then use the
os.rename() function. The
os.rename() function takes two arguments, both strings. The first is the current name of the file, the second is the new name:
import os os.rename("old.txt", "new.txt")
The above code assumes that the file
old.txt is in the folder where we are running our Python program (also known as the working directory). If it's elsewhere in the filesystem, then we have to give the complete path:
os.rename("/home/martin/biology/old.txt", "/home/martin/biology/new.txt")
If we specify a different folder, but the same filename in the second argument, then the function will move the file from one folder to another:
os.rename("/home/martin/biology/old.txt", "/home/martin/python/old.txt")
Of course, we can move and rename a file in one step if you like:
os.rename("/home/martin/biology/old.txt", "/home/martin/python/new.txt")
os.rename() works on folders as well as files:
os.rename("/home/martin/old_folder", "/home/martin/new_folder")
If we try to move a file to a folder that doesn't exist we'll get an error. We need to create the new folder first with the
os.mkdir() function:
os.mkdir("/home/martin/python")
If we need to create a bunch of directories all in one go, we can use the
os.mkdirs() function (note the s on the end of the name):
os.mkdirs("/a/long/path/with/lots/of/folders")
To copy a file or folder we use the
shutil module. We can copy a single file with
shutil.copy():
shutil.copy("/home/martin/original.txt", "/home/martin/copy.txt")
or a folder with
shutil.copytree():
shutil.copytree("/home/martin/original_folder", "/home/martin/copy_folder")
To test whether a file or folder exists, use
os.path.exists(). This function returns
True or
False, so we can use it as a condition:
if os.path.exists("/home/martin/email.txt"): print("You have mail!")
Deleting files and folders
There are different functions for deleting files, empty folders, and non-empty folders. To delete a single file,
use os.remove():
os.remove("/home/martin/unwanted_file.txt")
To delete an empty folder, use
os.rmdir():
os.rmdir("/home/martin/empty")
To delete a folder and all the files in it,
use shutil.rmtree():
shutil.rmtree("home/martin/full")
Listing folder contents
The
os.listdir() function returns a list of files and folders. It takes a single argument which is a string containing the path of the folder whose contents you want to search. To get a list of the contents of the current working directory, use the string
"." for the path:
for file_name in os.listdir("."): print("one file name is " + file_name)
To list the contents of a different folder, we just give the path as an argument:
for file_name in os.listdir("/home/martin"): print("one file name is " + file_name)
Running external programs
Another feature of Python that involves interaction with the operating system is the ability to run external programs. Just like file and folder manipulation, the ability to run other programs is very useful when using Python as part of a work flow. It allows us to use existing tools that would be very time consuming to recreate in Python, or that would run very slowly.
Running external programs from within your Python code can be a tricky business, and this feature wouldn't normally be covered in an introductory programming course. However, it's so useful for biology (and science in general) that we're going to cover it here, albeit in a simplified form.
As with the above section on file operations, the exact details of how external programs are run will vary with your operating system and the way your computer is set up. On UNIX-based systems, the program that you want to run might already be in your path, in which case you can simply use the name of the executable as the string to be executed. On Windows, you'll probably have to supply the full path to the program you want to run.
Running a program
The functions for running external program reside in the
subprocess() module. The reasoning behind the name is slightly convoluted: when talking about operating systems, a running program is called a process, and a process that is started by another process is called a subprocess.
To run an external program, use the
subprocess.call() function. This function takes a single string argument containing the path to the executable you want to run:
import subprocess subprocess.call("/bin/date")
Any output that is produced by the external program is printed straight to the screen – in this case, the output from the Linux
date program:
Fri Jul 26 15:15:26 BST 2013
If we want to supply command line options to the external program then we just include them in the string, and set the optional shell argument to
True. Here we call the Linux
date program with the options which cause it to just print the month:
subprocess.call("/bin/date +%B", shell=True)
July
Capturing program output
Often, we want to run some external program and then store the output in a variable so that we can do something useful with it. For this, we use
subprocess.check_output(), which takes exactly the same arguments as
subprocess.call():
current_month = subprocess.check_output("/bin/date +%B", shell=True)
Just like when reading file contents, the output from an external program can run over multiples lines, so the string that's returned by
subprocess.check_output() might contain multiple lines separated by newline characters.
User input makes our programs more flexible
The exercises and examples that we've seen so far have used two different ways of getting data into a program. For small bits of data, like short DNA sequences, restriction enzyme motifs, and gene accession names, we've simply stored the data directly in a variable like this:
dna = "ATCGATCGTGACTAGCTACG"
When data is mixed in with the code in this manner, it is said to be hard-coded.
For larger pieces of data, like longer DNA sequences and tabular data, we've typically read the information from an external text file. For many purposes, this is a better solution than hard-coding the data, as it allows the separation of data and code, making our programs easier to read. However, in all the examples we've seen so far, the names of the files from which the data are read are still hard-coded.
Both of these approaches to getting data into our program have the same shortcomings – if we want to change the input data, we have to open the code and edit it. In the case of hard-coded variables, we have to edit the statement where the variables are created. In the case of files, we have two choices – we can either edit the contents of the file, or edit the hard-coded filename.
Real life useful programs don't generally work that way. Instead, they allow us to specify input files and options at the time when we run the program, rather than when we're writing it. This allows programs to be much more flexible and easier to use, especially for a person who didn't write the code in the first place.
In the next couple of sections we're going to see tools for getting user input, but more importantly we're going to talk about the transition from writing a program that's only useful to you, to writing one that can be used by other people. This involves starting to think about the experience of using a program from the perspective of a user.
There are many reasons why you might need your programs to be usable by somebody who's not familiar with the code. If you write a program that solves a problem for you, chances are that it could solve a problem for your colleagues and collaborators as well. If you write a program that forms a significant part of a piece of work which you later want to publish, you may have to make sure that whoever is peer reviewing your paper can get your program working as well. Of course, making your program easier to use for other people means that it will also be easier to use for you, a few months after you have written it when you have completely forgotten how the code works!
Interactive user input
To get interactive input from the user in our programs, we can use the
raw_input() function.
raw_input() takes a single string argument, which is the prompt to be displayed to the user, and returns the value typed in as a string:
accession = raw_input("Enter the accession name") # do something with the accession variable
Note: in Python 3, this function has been renamed to
input().
The
raw_input() function behaves a little differently to other functions and methods we've seen, because it has to wait for something to happen before it can return a value – the user has to type in a string and press enter. The user input will be returned as a string (so if we need to use is as something else – e.g. a number – we'll have to do the conversion manually) and will end with a newline (so we might want to use
rstrip() to remove it).
Capturing user input in this way requires us to think quite carefully about how our program behaves. Programs that we write to carry out analysis of large datasets will often take a considerable amount of time to run, so it's important that we minimize the chances of the user having to rerun them. When using the
raw_input() function, there are two situations in particular that we want to avoid.
One is the situation where we have a long-running program that requires some user input, but doesn't make this fact clear to the user. What can happen in this scenario is that the user starts the program running and then switches their attention to something else, assuming that the program will continue to make progress in the background. If the user doesn't notice (or is not at their computer) when the program reaches the point where it requires input and halts, the program may be stuck waiting for input for a long time.
The other scenario to avoid is where a program runs for some time before asking the user for input, then fails to work due to an incorrect input or typo, requiring the user to restart the program from scratch.
A good way to avoid both of these problems is to design our programs so that they collect all necessary user input at the start, before any long-running tasks are carried out. We can also reduce the chances of incorrect input on the part of the user by offering clear instructions and documentation.
An important part of user input is input validation – checking that the input supplied by the user makes sense. For example, you might require that a particular input is a number between some minimum and maximum values, or that it's a DNA sequence without ambiguous bases, or that it's the name of a file that must exist. A good strategy for input validation is to check the input as soon as it's received, and give the user a second chance to enter their input if it's found to be invalid. Here's an example which uses a while loop to give the user multiple attemps to enter a number between 1 and 10:
answer = "" while answer < 1 or answer > 10: answer = int(raw_input("enter a number between 1 and 10\n")) print("final answer is " + str(answer))
A better way to do this is to use Python exception system: see the chapter on exceptions in Advanced Python for Biologists for details.
One big drawback of getting user input interactively is that it makes it harder to run a program unsupervised as part of a work flow. For most biological analyses, specifying program options when it's run using command line arguments is a better approach.
Command line arguments
If you're used to using existing programs that have a command line user interface (as opposed to a graphical one) then you're probably familiar with command line arguments. These are the strings that you type on the command line after the name of a program you want to run:
myprogram one two three
In the above command line,
one,
two and
three are the command line options. To use command line arguments in our Python scripts, we import the
sys module. We can then access the command line arguments by using the special list
sys.argv. Running the following code:
import sys print(sys.argv)
with the command line:
python myprogram.py one two three
shows how the elements of
sys.argv are made up of the arguments given on the command line:
['myprogram.py', 'one', 'two', 'three']
Note that the first element of
sys.argv is always the name of the program itself, so the first command line argument is at index one, the second at index two, etc.
Just like with
raw_input(), options and filenames given on the command line are stored as strings so if, for example, we want to use a command line argument as a number, we'll have to convert it with
int().
Command line arguments are a good way of getting input for your Python programs for a number of reasons. All the data your program needs will be present at the start of your program, so you can do any necessary input validation (like checking that files are present) before starting any processing. Also, your program will be able to be run as part of a shell script, and the options will appear in the user's shell history.
Recap
We started this page by examining two features of Python that allow your programs to interact with the operating system – file manipulation and external processes. We learned which functions to use for common file system operations, and which modules they belong to. We also saw two ways to call external programs from within your Python program.
When using these techniques to solve real life problems, or when working on the exercises, remember that you may encounter errors that are nothing to do with your program. For instance, when trying to rename a file you may get an error if a specified file doesn't exist or you don't have the necessary permissions to rename it. Similarly, if you get unexpected output when running an external program the problem may lie with the external program or with the way that you're calling it, rather than with your Python program. This is in contrast to the rest of the exercises in this book, which are mostly self contained. If you run into difficulties when using the tools in this chapter, check the external factors as well as checking your program code.
In the last portion, we saw two different ways to get user input when your program runs. Using command line arguments is generally better for the type of programming that forms part of scientific research. In real world scientific programming, we often need to make a command line interface that's usable by non-programmers. For a detailed discussion of building user interfaces, with many more examples, see the chapter in Effective Python development for Biologists (which you can find on the books page).
Exercises
Both of these exercises use the same set of files - click here to download them, then extract the zip file to a convenient folder. Remember, you can always find solutions and explanations for all exercises in the Python for Biologists books.
Binning DNA sequences
Write a program which creates nine new folders – one for sequences between 100 and 199 bases long, one for sequences between 200 and 299 bases long, etc. Write out each DNA sequence in the input files to a separate file in the appropriate folder.
Your program will have to:
- iterate over the files in the folder
- iterate over the lines in each file
- figure out which bin each DNA sequence should go in based on its length
- write out each DNA sequence to a new file in the right folder
Kmer counting
Write a program that will calculate the number of all kmers of a given length across all DNA sequences in the input files and display just the ones that occur more than a given number of times. You program should take two command line arguments – the kmer length, and the cutoff number.
SOLUTIONS
You can find solutions to all the exercises, along with explanations of how they work, in the Python for Biologists books - head over to the books page to check them out. | https://pythonforbiologists.com/files-programs-and-user-input/ | CC-MAIN-2018-26 | refinedweb | 3,182 | 57.1 |
I have a function that creates classes derived from it's arguments:
def factory(BaseClass) :
class NewClass(BaseClass) : pass
return NewClass
NewA = factory(ClassA)
NewB = factory(ClassB)
print type(NewA()) # <class __main__.NewClass>
print type(NewB()) # <class __main__.NewClass>
__name__
NewA.__name__ = 'NewA'
print type(NewA()) # <class __main__.NewA>
Yes, setting
__name__ is the correct thing to do; you don't need to set anything else to adjust the class name.
For example:
def factory(BaseClass) : class NewClass(BaseClass): pass NewClass.__name__ = "factory_%s" % BaseClass.__name__ return NewClass
type is the wrong thing to use here. It doesn't let you define classes with Python's normal class syntax, instead making you set up every class attribute manually. It's used to create classes by hand, eg. if you have an array of base classes and you want to create a class using it (which you can't do with Python's class syntax). Don't use it here. | https://codedump.io/share/0kSpTn8zNZCU/1/how-to-set-class-names-dynamically | CC-MAIN-2016-44 | refinedweb | 159 | 68.47 |
Adding Code To My SageMath Notebook
I have written a class, LRC, using the Sage Notebook which works just fine. Now I would like to put it into my sage environment without including it on each worksheet.
Before I go on I should describe my environment a bit. I am running a windows 7 machine with Virtual Box. I imported a Sage Notebook virtual machine and run it. The virtual box shares some of the drive space with the windows machine, in particular a spot called D:\unixshare
So I extracted the code from the cell to a file and placed it at D:\unixshare\forLRC\LRC.py which at least in theory available to the virtual box machine.
In a new worksheet I put this in a cell.
import sys sys.path.append('/media/sf_D_DRIVE//unixshare/forLRC') # move your python files here
import LRC
lrc = LRC()
.-.-.-.-.-.-.-.-.-.-
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_sage_input_4.py", line 10, in <module>
exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("aW1wb3J0IHN5cwpzeXMucGF0aC5hcHBlbmQoJy9tZWRpYS9zZl9EX0RSSVZFLy91bml4c2hhcmUvZm9yTFJDJykgIyBtb3ZlIHlvdXIgcHl0aG9uIGZpbGVzIGhlcmUKCmltcG9ydCBMUkMKCmxyYyAgICA9IExSQygp"),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
File "", line 1, in <module>
File "/tmp/tmpMF8IdA/___code___.py", line 5, in <module> import LRC File "/media/sf_D_DRIVE//unixshare/forLRC/LRC.py", line 22, in <module> class LRC( object ): File "/media/sf_D_DRIVE//unixshare/forLRC/LRC.py", line 31, in LRC var( "myOmega" ) # sometimes used as the angular frequency
NameError: name 'var' is not defined
I did get a new file: D:\unixshare\forLRC\LRC.pyc
So I have a problem that does not let me go any farther. I am not a particularly experienced python programmer, but have programmed in various languages for some time. Some help? Thanks. | https://ask.sagemath.org/question/11052/adding-code-to-my-sagemath-notebook/ | CC-MAIN-2017-26 | refinedweb | 289 | 50.12 |
I don't know if there is something wrong with my eclipse program, but nothing shows up on the console screen after I run this code(it runs without errors). All of the other codes are working perfectly, so there must be something wrong with this code that I can't find?
Code Java:
import java.util.Scanner; public class SimpleAverage { public static void main(String[] args) { Scanner input = new Scanner(System.in); int total = 0; int grade; int average; int counter= 0; while ( counter < 10 ) { grade = input.nextInt(); total = total + grade; counter = counter++; } average = total/10; System.out.println("This is the grade average" +average); } } | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/34145-why-isnt-grade-averaging-working-printingthethread.html | CC-MAIN-2016-36 | refinedweb | 106 | 66.44 |
Using SoapClient, this should give you an idea of how to create the SOAP call:
try { $client = new SoapClient('CRMLeadServiceV10.wsdl'); $header = new SoapHeader('', 'Security', array( 'UsernameToken' => array( 'Username' => 817221, 'Password' => array( '_' => 1234, 'Type' => '')))); $params = new stdClass(); $params->createLead = new stdClass(); $params->createLead->LeadSourceId = 1234; $result = $client->__soapCall('createLead', $params, null, $header); print_r($result); } catch (SoapFault $e) { die($e->getMessage()); }
Thanks George. I'll try this. For the 'Title' parameter, how should I write it since it contains <code>?
I'm getting this error: "SOAP-ERROR: Encoding: object has no 'createLead' property". I'm really wondering why.
SoapClient should take care of encoding it for you. Maybe it's looking for objects - see my edit.
The soap:address location in WSDL is different from that makelsabido puts in the comment and even more, the WSDL location doesn't exist. If you create SoapClient proxy with this WSDL it won't work. In the other hand the location in maikelsabido's comment has transport level security with client certificate authentication (confirmed with wireshark), a valid certificate for https connection is needed to succefull https soap call. I don't know how to do this in PHP SoapClient...
xml - Web Service SOAP Request is working on SOAPUI but not working on...
I think the best you can do is log the time right before you return a value. The only way I've seen for services to continue processing after they send a response is to create another thread for it, which wouldn't help in this case.
That's what I thought but I was hoping there would be a better way around this. I'll do as suggested, thanks.
xml - How to send a C# SOAP response to SoapUI before closing the web ...
I'm quite sure what you're asking for is not possible with SoapUI MockServices. There are some extensive possibilities involving scripting, and it is even possible to access the underlying javax.servlet.http.HttpServletRequest and Response objects. Have a look here for details:
Using scripting, it is possible to write a mock service request handler like this in SoapUI that just resets and closes the output stream:
mockRequest.getHttpResponse().reset(); mockRequest.getHttpResponse().getOutputStream().close();
But the client will still see a HTTP response header like this generated by the servlet container:
HTTP/1.1 200 OK Content-Length: 0 Server: Jetty(6.1.x)
It is generally not possible to abort the connection immediately from inside a servlet (which is what SoapUI mock services are built upon). Have a look here about this topic:
I'd use something completely different than SoapUI, most likely a scripting technology like PHP or Perl to achieve what you're asking for.
Thanks for very detailed answer!
soap - SoapUI : Mock service that not returning response - Stack Overf... ...
I was able to connect to the webservice using the following code:
$client = new SoapClient ($wsdl, array('location' => $momurl, 'action'=>$action, 'style' => SOAP_DOCUMENT, 'trace' => 1, 'soap_version' => SOAP_1_1, 'exceptions' => false, 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP, 'ssl_method' => SOAP_SSL_METHOD_TLS)); $header='<wsse:Security xmlns: <wsse:UsernameToken wsu: <wsse:Username>'.$usname.'</wsse:Username> <wsse:Password'.$password.'</wsse:Password> </wsse:UsernameToken> </wsse:Security>'; $headerSoapVar = new SoapVar($header,XSD_ANYXML); $soapheader = new SoapHeader('wsse', "Security" , $headerSoapVar , true); $client->__setSoapHeaders($soapheader); $params['/* the function or method that you want to use */'] = array(/* insert your parameters here */); $result = $client->__soapCall("/* the function or method that you want to use */", $params);
Check the header part of your request if it is similar to mine. If it's not then just use your own header. Basically, just copy your request's header part and just set the variables for username and password. I've tried it on another webservice and it's working fine.
xml - Web Service SOAP Request is working on SOAPUI but not working on...
Using the XML view of a Test Request test step in soapUI you can freely edit what shall be sent.
<soap...> <MyUpdateRequest> <name>true</name> </MyUpdateRequest> </soap...>
You mean to say I can sent the above request "update_request" with name parameter only. There will be no error in calling with flag parameter as null?
Yes, I think so. soapUI should send the message as long as the server component providing the webservice accepts this.
and in above case? I have updated the example.
As I have written you can type anything you like. You could also edit the SOAP message to look like <soap>HelloWorld</soap> and send it.
soap - Is it possible to call web service method with less parameters ...
- create a new SoapUI project
- double click on project in the tree
- configure WSS settings in "WS-Security Configurations" tab
- select WSS configuration for the mock service (beware - it is not in a pop-up but in a properties table in bottom left of the screen - see How to apply WSS to mocked response in SoapUI?
You have quite fine grained control over configuration details (used encryption and signature algorithms, encrypting only parts of messages aso.) but you do not control raw XML tags for encryption.
soapui - soap UI to generate a mock service and test client - Stack Ov...
definitions is a root element of WSDL so it looks like you are not loading WSDL.
I tested it and it looks like the whole problem is with your web server. Your web server returns WSDL to browser but it doesn't return it to any tool because these tools are using very minimalistic HTTP requests without many HTTP headers. One of missing headers is Accept. Once this header is not included in the request your server throws HTTP 400 Bad request.
The easy approach to continue is opening WSDL in the browser, save the wsdl to a file and import that file to soapUI instead of the WSDL from URL.
Please can you help me ?? it's 5 days i tray to fix the problem. I have not understand your answer, i am sorry. How i can test my wsdl ?? is the log error says that my web services is not working ?? thanks for your answer
No, when i add it, it show tho me the " Loading definition from url", it take this for several minutes and it show me " com.ev...: Error importing wsdl . is this mean that my wsdl is not working ?
Yes that means that WSDL cannot be downloaded or it is not correct. Can you open WSDL in browser?
I used IE/Firefox to see WSDL and I used Visual studio / svcutil (MS tools for creating service proxies) to simulate soapUI behavior (I don't have soapUI installed at home). I used Fiddler to compare communication over HTTP with your server and to test different HTTP requests until I found the difference causing the problem.
web services - WSDL/SOAP Test With soapui - Stack Overflow
A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.
The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.
web services - WSDL/SOAP Test With soapui - Stack Overflow
This is the way I used before may be not the best.
Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).
web services - Parsing and Recursion of SOAP response in SoapUI - Stac...
Mocking with SoapUI will start a Jetty server listening on a specified port with either REST or SOAP services. The response can be based on request content and you can run scripts in Groovy on several phases of the execution, which enables an almost unlimited extension of the tool.
soapui - Soap UI mock service - Stack Overflow
This is probably a WS-A addressing issue.
In the WS-A tab of your Request, check "Enable WS-A addressing". You may also have to check "Add default was:To".
SOAP Action mismatch error while testing a WCF service with SoapUI - S...
SoapUI by default do not support swagger.
But there is an official plugin. You could give a try:
soapui - Sending Complete Response of a REST service as Input to anoth...
The SOAP UI raise the exception because your certificate not properly installed in SOAP UI trust store.
To resolve the above exception follow the below steps.
- Export the certificate from the key store or browser (which contain the public key)
- Go to the SOAPUI installed directory and locate following directory \SmartBear\soapUI- 4.0.1\jre\lib\security
- Import the certificate in to cacerts trust store (Which is the default trust store)
- Restart the SOAP UI and load the WSDL...
To understand more about SSL ... follow the below link ...JSSE documentation
soap - Test internal secured web service with SoapUI? - Stack Overflow
public String getRequestResult(String wsdl, String operationName) throws Exception { // create new project WsdlProjectPro project = new WsdlProjectPro(); // import amazon wsdl WsdlInterface iface = WsdlInterfaceFactory.importWsdl(project, wsdl, true)[0]; // get desired operation WsdlOperation operation = (WsdlOperation) iface .getOperationByName(operationName); // create a new empty request for that operation WsdlRequest request = operation.addNewRequest("Java Req"); // generate the request content from the schema request.setRequestContent(operation.createRequest(true)); // submit the request @SuppressWarnings("rawtypes") WsdlSubmit submit = (WsdlSubmit) request.submit(new WsdlSubmitContext( request), false); // wait for the response Response response = submit.getResponse(); return response.getContentAsString(); }
web services - How to generate example SOAP request with SoapUI in jav...
Instead of using AutoIt to push the SoapUI gui automatically,
You can also setup an AutoIt script to execute testrunner.bat.
I have setup SoapUI project for the web service. Now I am trying to execute it from command line using the 'testrunner.bat' but I am getting following error 'log4j:ERROR setFile(null,false) call failed. java.io.FileNotFoundException: soapui.log (Access is denied)' in the command prompt. I assume the problem is with the write permissions for the folder I have mentioned to log my results into. I gave write permissions to the folder but I am still getting the error. What might be going wrong?
give a try to run testrunner in admin mode or start testrunner from your user directory
Thanks @codedad. The problem was solved. The write permissions for the 'soapui.log' file was missing. I gave the write permissions to the concerned files in the SOAPUI/Bin folder and the problem got solved. I am able to run SOAP UI tests from command line but there's another problem now. When I run the tests from SOAP UI window, the requests are successful but when I run from command line, the reports being generated for each testcase is showing me the status as 'UNKNOWN' ie. the status in response is 'HTTP/1.1 404 Not Found'.What might be the reason for this?
soapui - Can we automate sending requests to a web service in SOAP UI ...
Your web service is returning a SOAPFault which is saying that web service expects a SOAP Action http header. In order to add a SOAP action in your SOAP request from SOAPUI you must add a http header named SOAPAction, to do so do the next step:
- In the bottom of your SOAP test request there are some tabs (Header(0), Attachments(0)...), open the Header(0) tab.Then using + add button, add a header with SOAPAction name and your value:
Yes thats right. Can you also reply how to add this using a Java client. I generated the stubs using Apache Cxf from the wsdl.
@james2611nov take a look at this question which explains a possible way to add the SOAPHeader in http-header using CXF. If this doesn't fit your requirements try to ask your own question with more details about your exact problem. Hope this helps :)
SOAP Action mismatch error while testing a WCF service with SoapUI - S...
Try disabling the proxy in SOAP-UI, which indicated in the attached screen shot. Or Give a valid proxy connection under Proxy settings in SOAP UI Global preference.
By disabling the proxy preference SOAP UI may work in offline.
soap - Getting an error connecting web service using SOAPUI - Stack Ov... ...
- That didn't fix my problem, though. I had to create a new WCF project from the beginning and manually copy the code. That fixed it. Good luck.
When you change a namespace in your code, also make sure you change it in web.config! | https://recalll.co/app/?q=soapui%20-%20Soap%20UI%20mock%20service%20-%20Stack%20Overflow | CC-MAIN-2019-18 | refinedweb | 2,100 | 56.66 |
AVS Display Cards for Tablets 1.0
The guidance on this page is based on implementing the TemplateRuntime 1.0 and PlaybackController 1.0 APIs for Tablets. If you are using different versions, choose another page from the drop-down menu above. This page contains Tablet-specific Display Card design guidance. For general multimodal best practices, please see Multimodal Display.
Display Cards for Alexa provide visuals to support verbal responses, and give your customers an additional way to interact with Alexa.
If you are implementing Display Cards on a device, the Cards should properly display all content, templates, media attributions, and media controls. In addition, we expect that:
- A Display Card will appear as soon as Alexa begins responding or media begins playing, and the Display Card’s contents will match the Alexa response or media.
- Transitions between Display Cards will be smooth, as will the transition into displaying Cards and dismissing Cards.
- Display Cards will respond to screen interactions and voice utterances as described in the design guidelines for your product’s device class.
- Alexa attention states for Listening and Thinking will appear on top of any visible Display Card, and will not be obscured.
Details for each of these are provided in the guidelines below.
Static Display Cards
Global elements
Alexa shows Static Display Cards in response to certain non-media queries. All Display Cards in this section have the following global elements.
Elements
The numbered elements in the illustration above are described in more detail here.
Titles: All cards will have a mainTitle. Some will have a subTitle.
Alexa Skills Icon: This icon (top right) appears when a third-party provides the information being displayed on the Card. If the information is not being provided by a third-party, this icon will not appear.
Barge-In Button: This button (bottom center) can be tapped at anytime to activate and talk to Alexa.
GUI Dismiss Button: Tapping the "X" hides the GUI and ends the Alexa response.
Notes on the guidelines for static Display Cards
All specs are based on a reference template of 1280 x 800dp.
Layout is given in percentages to help adapt the template to your device’s screen resolution.
Font sizes are given on the reference screen. These sizes should scale as the resolution of screen changes. If no line-height is given, the line-height is the same as the font size.
mainTitle and subTitle should never exceed one line. If the text exceeds the width of the container, the crop the text and use an ellipsis.
Image assets and icons marked in dp size should scale as the resolution of screen changes.
All of the assets URL can be found in the Asset section of this documentation.
Voice Chrome
Voice chrome is a visual indicator of the Alexa attention states such as Listening, Thinking, and Responding. Most tablets will use on-screen voice chrome, although it is possible to use on-device LEDs to display the states instead.
Details of how and when voice chrome should be displayed can be found in the Interactions section below, and in the Interruption Scenarios section on this page. The colors and animations of voice chrome should follow the patterns specified in the Attention System documentation.
Interactions
There are two modes you can choose from for the static Display Cards: light and dark. Depending on the color scheme of the card, Alexa will be evoked on a white or black overlay.
Note: NowPlaying cards use only dark mode.
The following is an example of the screen states a customer might view when interacting with Alexa.
Invoke Alexa in light mode
Note: Active voice chrome is on the top of a white overlay with 50% opacity.
Invoke Alexa in dark mode
More information on dark mode is available under Dark Mode.
Note: Active voice chrome is on the top of a black overlay with 50% opacity.
Example interaction breakdown
Step 1: Invocation
The customer activates Alexa with the wake word “Alexa” or with a control on the device (physical or GUI button for example). This activates voice chrome to show Alexa is listening.
Step 2: Listening
Once Alexa is invoked and voice chrome is displayed, the customer can control Alexa with their voice. If Alexa recognizes an utterance, it processes the intent and display a Card. If Alexa doesn’t hear anything from the customer within 8 seconds, voice chrome dismisses.
Step 3: Response and Dismissal
Alexa responds verbally, and when applicable, with a Display Card. Audio and visuals should always be in sync, showing the card and playing audio simultaneously. Once Alexa finishes speaking, the card should dismiss automatically after 2 seconds of inactivity.
If, before playback is complete, the customer:
Taps the barge-in button (the Alexa logo), then TTS stops and voice chrome should display on top of the Card.
Taps the “X”, then the card clears and the TTS stops.
The Card should not be dismissed before TTS is complete, unless the customer has done so manually. Tapping the barge-in button (the Alexa logo) should stop the TTS, dismiss the Card, and open the voice chrome.
Additional interaction scenarios are described in the Interruption Scenarios section.
BodyTemplate1
BodyTemplate1 is used for Q&A, Wikipedia queries, and third-party Skill requests that do not contain a photo. Sample utterances that would invoke BodyTemplate1 include:
- “How deep is the ocean?”
- “What is the definition of “paradox”?”
- "What is the Karman line?"
- "What is bike polo?"
Style
Layout
Note: The body content (textField) can extend off the bottom of the screen, which the customer can access by scrolling.
Data
JSON
{ "directive": { "header": { "namespace": "TemplateRuntime", "name": "RenderTemplate" }, "payload": { "token": "{{STRING}}", "type": "BodyTemplate1", "title": { "mainTitle": "Who is Usain Bolt?", "subTitle": "Wikipedia" }, "skillIcon": { "sources": [ { "url": "", "size": "small" } ] }, "textField": "Usain St Leo Bolt, OJ, CD born 21..." } } }
BodyTemplate2
BodyTemplate2, like BodyTemplate1, is used for Q&A, Wikipedia queries, and third-party Skill requests but, unlike BodyTemplate1, it also returns an image. Sample utterances that would invoke BodyTemplate2 include:
- “Who is Usain Bolt?”
- “What is 5 miles in kilometers?”
- “Who wrote To Kill a Mockingbird?”
- “Where is New Mexico?”
Style
Layout
Note: The image height and width are maximum dimensions. Images should resize to avoid exceeding either dimension.
Data
JSON
{ "directive": { "header": { "namespace": "TemplateRuntime", "name": "RenderTemplate" }, "payload": { "token": "{{STRING}}", "type": "BodyTemplate2", "title": { "mainTitle": "Who is Usain Bolt?", "subTitle": "Wikipedia" }, "skillIcon": { "sources": [ { "url": "", "size": "small" } ] }, "textField": "Usain St Leo Bolt, OJ, CD Born 21 August...", "image": { "contentDescription": "Image with two sources." "sources": [ { "url": "", "size": "small" }, { "url": "", "size": "large", "widthPixels": 1200 , "heightPixels": 800 } ] } } } }
ListTemplate1
ListTemplate1 is used to display items in a list, such as a calendar or shopping list. Sample utterances that would invoke ListTemplate1 include:
- “What’s on my to do list?”
- “Add eggs to my shopping list.”
- “When is my next event?”
- “Add “Lunch with Jayla” to my calendar.”
Style
Layout
Note: The distance between leftTextField and rightTextField is static. For example, if leftTextField displays more characters than shown here, rightTextField should push right and the distance between the two should remain the same.
Data
Variation: Calendar
Note: The distance between the time and event is static.
JSON
{ "directive": { "header": { "namespace": "TemplateRuntime", "name": "Render" }, "payload": { "token": "{{STRING}}", "type": "ListTemplate1", "title": { "mainTitle": "Title", "subTitle": "Subtitle" }, "skillIcon": { "contentDescription": "Source for the skill icon.", "sources": [ { "url": "", "size": "small" } ] }, "listItems": [ { "leftTextField": "1.", "rightTextField": "Alfa" }, { "leftTextField": "2.", "rightTextField": "Bravo" }, { ... } ] } } }
WeatherTemplate
WeatherTemplate is used with all weather-related utterances, such as:
- “What’s the weather?”
- “Will it rain today?”
- “What’s the weather in [location]?”
Style
Layout
Weather template layout in 3 digits
Data
JSON
{ "directive": { "header": { "namespace": "TemplateRuntime", "name": "RenderTemplate" }, "payload": { "token": "{{STRING}}", "type": "WeatherTemplate", "title": { "mainTitle": "San Francisco", "subTitle": "Friday, October 31" }, "skillIcon": null, "currentWeather": "75°", "description": "Mostly cloudy and more humid with a couple of showers and ...", "currentWeatherIcon" { "contentDescription": "Weather image sources.", "sources": [ { "url": "", "size": "medium" } ] }, "highTemperature": { "value": "76°", "arrow": { "contentDescription": "Up arrow sources.", "sources": [ { "url": "", "size": "medium" } ] }, }, "lowTemperature": { "value": "45°", "arrow": { "contentDescription": "Down arrow sources.", "sources": [ { "url": "", "size": "medium" } ] }, }, "weatherForecast": [ { "image": { "contentDescription": "Partly cloudy...", "sources": [ { "url": "", "size": "small" } ] }, "day": "Sat", "date": "Oct 22", "highTemperature": "71°", "lowTemperature": "55°" }, { ... } ] } } }
Dark mode
You may want to adapt the templates to use a dark mode, for example for night-time use. Dark mode provides a more pleasant experience in low lighting. To implement dark mode:
- Change body and footer backgrounds to black (#000000).
- Change all black text (#151320) to white (#ffffff).
- For image URLs on the WeatherTemplate, use “darkBackgroundUrl” instead of “url”.
Here are examples of the result.
NowPlaying Cards
Alexa uses NowPlaying in response to media requests. Sample utterances that would invoke NowPlaying include:
- “Play jazz music”
- “Play Smoke & Retribution”
- “Play Freakonomics on iHeartRadio”
- “Play a country station from [third-party music provider]”
VUI Playback Commands
The customer can control media playback either using GUI or VUI. VUI playback commands include:
- Play
- Stop
- Cancel
- Pause
- Resume
- Rewind
- Start Over
- Louder
- Softer
- Set Volume
- Mute
- Unmute
- Shuffle
- Restart
- Get details
- Who is this?
Global Elements
Alexa shows the NowPlaying GUI in response to media queries. All NowPlaying Cards in this section have the following global elements.
The global elements in the NowPlaying Card include:
Media metadata
Playback controls: These will vary depending on the media type and the service.
Progress bar: Appears with most media types.
Barge-in button (Alexa logo): This button can be tapped at any time to activate and talk to Alexa.
“X" button: Tapping the “X" should hide the GUI and stop playback.
Media artwork: This could be album art, a radio station logo, a program logo, or book artwork.
Music provider logo: The logo of the service providing the media.
Controls Per Music Service Provider
Alexa can play music from multiple Music Service Providers. Controls vary per provider offering. For example, a live radio station might not have forward and back controls. The correct controls for each offering will be specified in the PlayerInfo directive.
Controls per Music Service Provider
Note: Amazon Music and Pandora are available only for commercial devices.
Interactions
The following is an example of the screen states a customer might view when interacting with Alexa.
Step 1: Invocation
The customer activates Alexa with the wake word “Alexa” or with a control on the device (depending on the device). This activates voice chrome to show Alexa is listening.
Step 2: Listening and intent processing
Once voice chrome is invoked the customer can control Alexa with their voice. If Alexa recognizes an utterance it will process their intent and display a GUI. If Alexa doesn’t hear anything from the customer within 5 seconds, clear the voice chrome.
Step 3: Response and dismissal
In response to media requests, Alexa displays a NowPlaying GUI with media metadata and playback controls.
If the customer:
- Dismisses the GUI by tapping the “X" or navigating away from the Card with device controls, then both the Card dismisses and audio stops. Note: If your device supports playback controls elsewhere on your device (see Additional Playback Controls), then the "X" should dismiss only the GUI and allow music playback to continue.
- Pauses or stops the music via voice or the button, then the audio stops and the Card remains. The Card should then auto-dismiss after one minute of inactivity.
- Activates Alexa again while the music is playing, the music attenuates and voice chrome reappears awaiting the next command.
Additional interaction scenarios are described in the Interruption Scenarios section.
Specs
Style
Layout
Note: Media artwork is constrained by the container shape and should never exceed these dimensions. In cases where artwork is not a square or is smaller than the container shape, it should be horizontally and vertically centered within the container shape.
Notes
- The source/author information is one line, and the mainTitle can be two lines maximum. If the mainTitle exceeds two lines, truncate the text and use an ellipsis.
- If content extends past its maximum number of lines, truncate the text and use an ellipsis.
- When mainTitle has two lines, titleSubtext1 and titleSubtext2 push down to accommodate. The controls and progress bar do not move.
Data
Examples
Example 1: Amazon Music
“Alexa, play Smoke & Retribution”
JSON The “name” key-value pair may come back as “Amazon Music,”“Prime Music,” or “Prime Station.” If Prime is not enabled, “name” will be “Digital Music Store.”
The
name key-value pair may come back as “Amazon Music”, “Prime Music”, or “Prime Station”. If Prime is not enabled,
name will be “Digital Music Store.”
{ "directive": { "header": { "namespace": "TemplateRuntime", "name": "RenderPlayerInfo", "messageId": "{{STRING}}", "dialogRequestId": "{{STRING}}" }, "payload": { "audioItemId": "{{STRING}}", "content": { "title": "{{STRING}}", "titleSubtext1": "{{STRING}}", "titleSubtext2": "{{STRING}}", "header": "{{STRING}}", "headerSubtext1": "{{STRING}}", "mediaLengthInMilliseconds": {{LONG}}, "art": {{IMAGE_STRUCTURE}}, "provider": { "name": "{{STRING}}", "logo": {{IMAGE_STRUCTURE}} } } "controls": [ // This array includes all controls that must be // rendered on-screen. { "type": "{{STRING}}", "name": "{{STRING}}", "enabled": {{BOOLEAN}}, "selected": {{BOOLEAN}} }, { "type": "{{STRING}}", "name": "{{STRING}}", "enabled": {{BOOLEAN}}, "selected": {{BOOLEAN}} }, { ... } ] } } }
Example 2: iHeartRadio Live Radio
“Alexa, play Hollywood Breakdown on iHeartRadio”
JSON
{ "directive": { "header": { "namespace": "TemplateRuntime", "name": "RenderPlayerInfo", "messageId": "{{STRING}}", "dialogRequestId": "{{STRING}}" }, "payload": { "audioItemId": "{{STRING}}", "content": { "title": "The summer of \"sequel-itis\" and beginning of awards season", "header": "KCRW's Hollywood Breakdown", "mediaLengthInMilliseconds": 0, "art" : { "sources" : [ { "size" : "medium", "url" : "" } ] }, "provider": { "name": "iHeartRadio Live Radio", "logo" : { "sources" : [ { "url" : "" } ] } } } "controls": [ { "type": "BUTTON", "name": "PLAY_PAUSE", "enabled": true, "selected": false }, ] } } }
Controls-Only Template
There may be instances when no metadata is returned from a NowPlaying request. In this instance, use the Controls-Only Template, which includes a minimized set of visuals.
Note: For certain Music Service Providers, the PlayerInfo directive is sent after the PlaybackStarted Event. In these cases, we recommend adding logic to wait 2 seconds for the PlayerInfo directive. If metadata is not returned after this time, display the Controls-Only Template.
Controls-Only Template
Style
Layout
Data
Native Playback Controls
Many tablets support playback controls on the customer's notifications panel or other universally accessible panel. If your device supports this native framework, then you should support the use of these controls for music playback from Alexa.
This playback controller should display the following metadata:
- art (album artwork)
- title
- titleSubtext1
- provider name
- any other applicable playback controls.
Tapping on the metadata should return the customer to the nowPlaying GUI of the current song.
Transitions
Transitions should be quick (< 1 sec) and employ easing to create a smooth feel. First the background fades in, followed by the content. To account for latency, a background placeholder box should appear in place of an image, which transitions to the fully loaded image when it arrives.
Cards exit the opposite way they came in. The text fades out first and then the Card fades.
Interruption Scenarios
The following are examples of the states the customer sees when interrupting Alexa's response.
Card to Card
Step 1: Utterance1
At Utterance1, voice chrome overlays the existing screen.
Step 2: TTS1 + GUI1
Alexa responds.
Step 3: Utterance 2 (Interruption)
When the customer interrupts Alexa (via tap or wake word), Alexa stops speaking and voice chrome overlays the existing card.
Step 4: TTS2 + GUI2
Alexa responds to utterance2 via voice and replaces the old card with a new one. This card dismisses according to regular dismissal rules.
NowPlaying to Card
Step 1: Utterance1
At Utterance1, voice chrome overlays the existing screen.
Step 2: TTS1 + GUI1
Alexa responds. Music plays.
Step 3: Utterance 2 (Interruption)
When the customer interrupts Alexa (via tap or wake word), the music attenuates and voice chrome overlays the nowPlaying GUI.
Step 4: TTS2 + GUI2
If the utterance is understood and a card is required, Alexa responds to the utterance via voice and a new card. Once the TTS completes, the music returns to the regular volume. The card dismisses according to regular dismissal rules, except that when dismissed, the customer returns to the nowPlaying card.
If the song changes during this time, when returning the nowPlaying GUI should reflect the new song.
Card to NowPlaying
Step 1: Utterance1
At Utterance1, voice chrome overlays the existing screen.
Step 2: TTS2 + GUI1
Alexa responds.
Step 3: Utterance2 (Interruption)
When the customer interrupts the music (via tap or wake word), Alexa stops speaking and the voice chrome overlays the existing card.
Step 4: TTS + GUI2
Alexa responds to Utterance 2 via voice and a new card. Once the TTS completes, music begins playing. This card dismisses according to regular dismissal rules.
NowPlaying to Error
Step 1: Utterance1
At Utterance1, voice chrome overlays the existing screen.
Step 2: TTS2 + GUI1
Alexa responds. Music plays.
Step 3: Utterance2 (Interruption)
When the customer interrupts the music (via tap or wake word), the music attenuates and voice chrome overlays the nowPlaying GUI.
Step 4: GUI1
If no utterance is understood, the voice chrome removes, returning to the nowPlaying GUI, and the music returns to it’s original volume.
Assets
These resources are provided for you to use with your display cards.
For tablets with a resolution of 1280x800dp or higher, we recommend using the large assets listed below. For lower resolution tablets, use the small assets. For resolutions that are much larger or smaller, you can also scale the assets for your needs.
Alexa
- Alexa logo (barge-in button): small tablets, large tablets
- GUI dismiss button ("X" button): small tablets, large tablets
Transport controls
The following are assets for media player controls.
Play
Pause
Prev
Alexa. | https://developer.amazon.com/en-US/docs/alexa/alexa-voice-service/display-cards-tablets-1-0.html | CC-MAIN-2021-25 | refinedweb | 2,864 | 56.05 |
Download presentation
Presentation is loading. Please wait.
Published byAna Binney Modified over 2 years ago
1
NOOR RAZA CHEEMA AMINA NAWAZ
2
GDI+ GDI+ is the next version of GDI. GDI+ drawing has graphics classes that can be used to write graphics on screen.GDI+ resides in the assembly System.Drawing.dll.
3
Namespaces The System.Drawing Assembly in the.Net Framework is broken into 6 namespaces Drawing Drawing 2D Imaging Text Design Printing
4
Colors Colors in GDI+ are represented by instances of the System.Drawing.Color struct. Generally, once you’ve instantiated this struct, you just need to pass it to whatever method you are calling that requires a Color.
5
..contd Now we’ll examine several different ways that we can construct a Color.
6
Red-Green-Blue (RGB) Values The total number of colors that can be displayed by a monitor is over 16 million. So we need a way by which we can indicate which of these is the color we want to display at any given pixel. The most common way of indexing colors is by dividing them into the red, green, and blue components.
7
..contd the amount of each component light is divided into 256 possible intensities. Therefore the colors are specified by giving the amounts of these components on a scale of 0 to 255 where 0 means that the component is not present and 255 means that it is at its maximum intensity.
8
..contd Color is Constructed using FromArgb(). Red, green, and blue values of colors can be called by the static function Color.FromArgb(). allow to specify something called an alpha-blend. Alpha blending allows to paint a color by combining it with whatever color was already on the screen. This can give some beautiful effects and is often used in games.
9
The Named Colors It’s a lot easier to name the color that is wanted. this.BackColor = Color.White; // has the same effect as: this.BackColor = Color.FromArgb(255, 255, 255); There are several hundred such colors. The full list is given in the SDK documentation.
10
Graphics Display Modes In practice the color display depends on the display properties of computer. In Windows traditionally three main color options are: true color (24-bit). high color (16-bit). 256 colors. Only true-color mode allows to display all of the RGB colors simultaneously. 3 bytes are needed to hold a full RGB value, which means 3 bytes of graphics card memory are needed to hold each pixel that is displayed. If graphics card memory is at a premium you might want to choose one of the other modes. High color mode gives 2 bytes per pixel. That’s enough to give 5 bits for each RGB component. That is just enough to give apparent photographic quality though areas of subtle shading tend to be broken up a bit..
11
..contd The 256-color mode gives even fewer colors. System sets up something known as a palette. This is a list of 256 colors chosen from the 16 million RGB colors. Once colors are specified in the palette, the graphics device will be able to display just those colors. The palette can be changed at any time, but the graphics device can only display 256 different colors on the screen at any one time. The 256-color mode is only used when high performance and video memory is at a premium. Most computer games will use this mode, and they can still achieve decent-looking graphics because of a very careful choice of palette.
12
The Safety Palette Safety palette is a very commonly used default palette. The way it works is that we set six equally spaced possible values for each color component: 0, 51, 102,153, 204, and 255. In other words, the red component can have any of these values. So can the green component. So can the blue component.. If Windows is set to 256-color mode, the default palette get is the safety palette.
13
Pens and Brushes Pens and Brushes are two helper classes that are needed in order to draw shapes. The Pen class is used to instruct the graphics instance how to draw lines. A related class is System.Drawing.Brush, which instructs the graphics instance how to fill regions. For example: the Pen is needed to draw the outlines of the rectangle and ellipse etc. If we had needed to draw these shapes as solid, we would have used a brush.
14
Brushes GDI+ has several different kinds of brush. Each type of brush is represented by an instance of a class derived from the abstract class System.Drawing.Brush. The simplest brush is System.Drawing.SolidBrush, indicates that a region is to be filled with solid color: Brush solidBeigeBrush = new SolidBrush(Color.Beige); Brush solidFunnyOrangyBrownBrush = new SolidBrush(Color.FromArgb(255,155,100)); Alternatively, if the brush is one of the Web-safe colors you can construct the brush using another class. System.Drawing.Brushes. Brushes is one of those classes that you never actually instantiate (it has a private constructor to stop you from doing that). It simply has a large number of static properties, each of which returns a brush of a specified color. You can use Brushes like this: Brush solidAzureBrush = Brushes.Azure; Brush solidChocolateBrush = Brushes.Chocolate;
15
..contd Hatch brush, which fills a region by drawing a pattern. This type of brush is considered more advanced, so it’s in the Drawing2D namespace, represented by the class System.Drawing.Drawing2D.HatchBrush. The Brushes class don’t include hatch brushes it is constructed by supplying the hatch style and two colors, the foreground color followed by the background color. The hatch style comes from an enumeration, System.Drawing.Drawing2D.HatchStyle.: ❑ System.Drawing.Drawing2D.LinearGradientBrush fills in an area with a color that varies across the screen. ❑ System.Drawing.Drawing2D.PathGradientBrush is similar, but in this case the color varies along a path around the region to be filled.
16
Pens Pens are represented by just one class: System.Drawing.Pen. However, the pen is slightly more complex than the brush, because it needs to indicate how thick lines should be (how many pixels wide) and, for a wide line, how to fill the area inside the line. This property might contain a reference to a Brush instance. There are four different ways that you can construct a Pen instance.For example, you can construct pens like this:
17
..contd, contains a number of stock pens. These pens all have one-pixel width and come in the usual sets of Web-safe colors. This allows you to construct pens in this way: Pen solidYellowPen = Pens.Yellow;
18
Drawing Shapes and Lines System.Drawing.Graphics has a large number of methods that allow you to draw various lines, outline shapes, and solid shapes. The following table lists the main ones and should give you some idea of the variety of shapes you can draw.
19
..contd
20
21
Displaying Images One.
22
..contd The class we need is the.NET base class, System.Drawing.Image. An instance of Image represents one image. Reading in an image simply takes one line of code: Image myImage = Image.FromFile(“FileName”); FromFile() is a static member of Image and is the usual way of instantiating an image. Displaying an image is also very simple, assuming we will use DrawImage(), like this: dc.DrawImage(myImage, points); In this line of code, dc is assumed to be a Graphics instance, while myImage is the Image to be displayed. points is an array of Point structs, where points[0], points[1], and points[2] are the coordinates of top- left, top-right, and bottom-left corner of the image.
23
.. Create an object representing the image you want to display. This object must be a member of a class that inherits from Image, such as Bitmap or MetaFile. An example is shown: Image Piccy;
24
.. load the file in our InitializeComponent routine private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.Size = new System.Drawing.Size(600, 400); this.Text = "Display COMFest Image"; this.BackColor = Color.White; Piccy = pg"); this.AutoScrollMinSize = Piccy.Size; }
25
..); }
26
Issues When Manipulating Images The most important point to understand about images is that they are always rectangular. All modern graphics cards have hardware built in that can efficiently copy blocks of pixels from one area of memory to another area of memory and the block of pixels represents a rectangular region. This hardware-accelerated operation can occur virtually as one single operation. Indeed, it is the key to modern high-performance graphics. This operation is known as a bitmap block transfer (or BitBlt). Graphics.DrawImageUnscaled() internally uses a BitBlt. If the computer had to copy the image to the screen pixel by pixel, you’d see the image gradually being drawn over a period of up to several seconds. BitBlts are very efficient; therefore almost all drawing and manipulation of images is carried out using them. In the days of GDI, the Windows 32 API function BitBlt() was arguably the most important and widely used function for image manipulation.
27
..contd It’s not possible to BitBlt areas of images that are not rectangular.. Note that the Graphics object implements another method, DrawImage(). This is similar to DrawImageUnscaled() but comes in a large number of overloads that allow you to specify more complex forms of BitBlt to be used in the drawing process. DrawImage() also allows you to draw (using BitBlt) only a specified part of the image, or to perform certain other operations on it such as scaling it (expanding or reducing it in size)as it is drawn.
28
Drawing Text Drawing text to the screen is more complex than drawing simple graphics. This is for two reasons: If you’re concerned about getting the appearance just right, you must understand fonts. The process of drawing text requires fonts as helper objects. And understanding fonts is not a trivial task. The space a word occupies on the screen a has to be calculated because it affects where in the document every subsequent word is placed. If application does any line wrapping then it’ll need to assess word sizes carefully before deciding where to place the line break.
29
..contd
30
The example demonstrates the use of the Graphics.DrawString() method to draw items of text. The method DrawString() comes in a number of overloads, of which we demonstrate three. The different overloads require parameters that indicate the text to be displayed, the font that the string should be drawn in, and the brush that should be used to construct the various lines and curves that make up each character of text. There are a couple of alternatives for the remaining parameters.
31
..contd If a Point is specified, the text will start with its top-left corner at that Point and simply stretch out to the right. If a Rectangle is specified, then the Graphics instance will lay out the string inside that rectangle. If the text doesn’t fit within the boundaries of the rectangle, then it’ll be cut off. Passing a rectangle to DrawString() means that the drawing process will take longer, as DrawString() will need to figure out where to put line breaks.
32
Fonts and Font Families A font describes exactly how each letter should be displayed. Most people, if asked to name a font,might mention Arial or Times New Roman (if they are Windows users) or Times or Helvetica (if they are Mac OS users). In fact, these are not fonts at all—they are font families. The font family tells you in generic terms the visual style of the text and is a key factor in the overall appearance of your application. An actual font would be something like Arial 9-point italic. In other words, the size and other modifications to the text are specified as well as the font family.
33
..contd
34
...contd Terms that are commonly used to describe certain font families. ❑ Serif font families have little tick marks at the ends of many of the lines that make up the characters Times New Roman is a classic example of this. ❑ Sans serif font families, by contrast, don’t have these ticks Good examples of sans serif fonts are Arial and Verdana. The lack of tick marks often gives text a blunt, appearance,so sans serif fonts are often used for important text. ❑ A True Type font family is one that is defined by expressing the shapes of the curves that make.
35
..contd Microsoft has provided two main classes that we need to deal with when selecting or manipulating fonts. These are: ❑ System.Drawing.Font ❑ System.Drawing.FontFamily When we want to draw text we instantiate an instance of Font and pass it to the DrawString() method to indicate how the text should be drawn. A FontFamily instance is used to represent a family of fonts.
36
..contd The static properties GenericSerif, GenericSansSerif, and GenericMonospace return default fonts that satisfy these criteria: FontFamily sansSerifFont = FontFamily.GenericSansSerif;
37
..contd Fonts available can be found out using a class called InstalledFontCollection, which is in the System.Drawing.Text namespace. This class implements a property, Families, which is an array of all the fonts that are available to use on your system: InstalledFontCollection insFont = new InstalledFontCollection(); FontFamily [] families = insFont.Families; foreach (FontFamily family in families) { // do processing with this font family }
38
Editing a Text Document: The CapsEditor Sample The CapsEditor example is designed to demonstrate how the principles of drawing are applied in a more realistic context. The CapsEditor example responds to the user input via the mouse and shows how to manage the drawing of text.
39
..contd The CapsEditor program is functionally quite simple. It allows the user to read in a text file, which is then displayed line by line in the client area. If the user double-clicks any line, that line will be changed to all uppercase. That’s literally all the sample does. The contents of the document can change either when the user selects the menu option to read a new file, or when he double-clicks to capitalize a line. In the first case we need to update the document size so the scroll bars still work correctly, and we have to redisplay everything. In the second case, we need to check carefully whether the document size has changed, and what text needs to be redisplayed.
40
..contd We’ll start by reviewing the appearance of CapsEditor. When the application is first run, it has no document loaded.
41
42
..contd The File menu has two options: Open, which evokes OpenFileDialog when selected and reads in whatever file the user clicks, and Exit, which closes the application when clicked. The sizes of the horizontal and vertical scrollbars are correct. The client area will scroll just enough to view the entire document. CapsEditor doesn’t try to wrap lines of text. It just displays each line of the file exactly as it is read in. There are no limits to the size of the file, but we are assuming it is a text file and doesn’t contain any non- printable characters.
43
The Invalidate() Method Invalidate() is a member of System.Windows.Forms.Form. It marks an area of the client window as invalid and, therefore, in need of repainting, and then makes sure a Paint event is raised. There are a couple of overrides to Invalidate(): you can pass it a rectangle that specifies (in page coordinates) precisely which area of the window needs repainting, or if you don’t pass any parameters it’ll just mark the entire client area as invalid.
44
Calculating Item Sizes and Document Size This method simply runs through each line that has been read in and uses the Graphics.MeasureString() method to work out and store how much horizontal screen space the string requires. We store the value, because MeasureString() is computationally intensive.
45
OnPaint() At the heart of this OnPaint() override is a loop that goes through each line of the document, calling Graphics.DrawString() to paint each one. The rest of this code is mostly to do with optimizing the painting—the usual stuff about figuring out what exactly needs painting instead of rushing in and telling the graphics instance to redraw everything.
46
Coordinate Transforms Coordinate transforms are the WorldYCoordinateToLineIndex() and LineIndexToWorldCoordinates() methods as well as a couple of other methods. First, LineIndexToWorldCoordinates() takes a given line index, and works out the world coordinates of the top left corner of that line, using the known margin and line height. WorldYCoordinateToLineIndex() works out the line index, but it only takes into account a vertical world coordinate. This is because it is used to work out the line index corresponding to the top and bottom of the clip region.
47
Responding to User Input Getting a GDI+ application to respond to user input is actually a lot simpler than writing the code to draw to the screen.
48
Printing For the ability of an application to print data add three items to the application’s main File menu: ❑ Page Setup, which allows the user to choose options such as which pages to print, which printer to use and so on. ❑ Print Preview, which opens a new Form that displays a mock-up of what the printed copy should look like. ❑ Print, which prints the document.
49
..contd In many ways printing is just the same as displaying to a screen. System.Drawing.Printing.PrintDocument System.Drawing.Printing.PrintPreview-Dialog. These two classes handle the process of making sure that drawing instructions passed to a device context are handled appropriately for printing.
50
..contd The process of printing is quite simple. : Instantiate a PrintDocument object. call its Print() method. This method signals the PrintPage eventto print the first page. PrintPage takes a PrintPageEventArgs parameter, which supplies information concerning paper size and setup, as well as a Graphics object used for the drawing commands. Make an event handler that set a Boolean property of the PrintPageEventArgs, HasMorePages, to either true or false to indicate whether there are more pages to be printed. The PrintDocument.Print() method will repeatedly raise the PrintPage event until it sees that HasMorePages has been set to false.
51
…contd Print Previewing. In this case, you instantiate both a PrintDocument object and a Print PreviewDialog object. You attach the PrintDocument to the PrintPreviewDialog (using the property PrintPreviewDialog.Document) and then call the dialog’s ShowDialog() method.
52
END THANK YOU
Similar presentations
© 2016 SlidePlayer.com Inc. | http://slideplayer.com/slide/2479069/ | CC-MAIN-2016-50 | refinedweb | 3,123 | 64 |
User:Ianweller/mw thoughts
From FedoraProject
Local junk
- mw init API_URL_OR_ALIAS
- mw login
- mw logout
- mw local-reset — when you've somehow fucked up your local repository; should let you keep what you have downloaded, but reverts them to the most recent version, and also clears out the metadir as much as possible
Aliases
Aliases are kind of like bookmarks for a wiki, so you can easily do "mw init fpwiki" for the Fedora Project wiki, for instance.
To prevent cruft, we should only implement code to automatically include aliases for WMF wikis (Wikipedia, Wiktionary, etc) in their different languages (aliases should be like en.wikipedia, wikipedia-en, whatever we decide, whatever's easiest). We don't need to store these locally; en.wikipedia's API provides functionality for determining a full list of WMF wikis.
Aliases should be addable/removable in a global config (/etc/mwrc, ~/.mwrc, other standards) with relevant commands. The global config code probably needs to be implemented.
User documentation
I don't care how we do user documentation, whether it's all in "mw command --help" (output to screen or through man pages), or built with python-sphinx, or whatever. It just needs to be done.
Fetching
- mw fetch [ --rv=DATESPEC ] PAGE_NAME
- mw fetch-category [ --rv=DATESPEC ] CATEGORY_NAME
- mw fetch-all [ --rv=DATESPEC ]
- mw update [ FILE ... ]
Page functions
- mw add FILE ...
- mw delete FILE ...
- mw move OLD_FILE NEW_FILE
- mw protect FILE ...
- mw watch FILE ...
- mw unwatch FILE ...
History and repo status
log and blame are considered most important by Ian
- mw status [ FILE ... ]
- mw diff [ --rv=REV_ID ] [ FILE ... ]
- mw log FILE
- mw blame FILE
Committing / editing
- mw commit [ FILE ]
- mw undo REV_ID
- mw revert REV_ID
Media files
Media files have a text description as well as the actual file. Therefore we need separate download/upload commands for media files.
Repository directory layout
<repo>/ .mw/ config cat/ <folders with symlinks to pages in category> img/ <where stuff from the Media/File/Image namespaces go> <all pages -- subpages have slashes converted to exclamation points>
Things that would be rockin' but totally not needed
- Preview (if local, requires MediaWiki and deps to be installed, I guess -- and also doesn't handle extensions or templates on the wiki you're saving to)
- Or what about saving in your user space on a wiki, like User:Username/mw_test_XXXXXX (XXXXXX is a temporary ID), and providing a link to that? Or even opening your browser? Configurable?
- Can we somehow have tagging/branching support? Does that even make sense for a MediaWiki?
- Syncing per-wiki settings across instances by saving to User:Username/mw_settings? (branches and tags could be defined here too) | https://fedoraproject.org/wiki/User:Ianweller/mw_thoughts | CC-MAIN-2017-17 | refinedweb | 440 | 56.15 |
Python Glossary
If you know a term you'd like defined, simply enter it with ??? for the definition, then subscribe to updates to this page (you'll need to set up a profile on the UserPreferences page). Someone will come along and complete it and you'll be reminded to check back when you are notified of changes to this page.
A symbol glossary is also available.
A-M
Attribute - Values associated with an individual object. Attributes are accessed using the 'dot syntax': a.x means fetch the x attribute from the 'a' object.
BDFL - Acronym for "Benevolent Dictator For Life" - a.k.a. Guido van Rossum, Python's primary creator, figurehead and decision-maker.
byte code - The internal representation of a Python program in the interpreter. The byte code is also cached in .pyc and .pyo files so that executing the same file is faster the second time (the step of compilation from source to byte code can be saved). This "intermediate language" is said to run on a "virtual machine" that calls the subroutines corresponding to each bytecode.
class - A template for creating user-defined objects. Class definitions normally contain method definitions that operate on instances implicitly invoked with the coerce builtin function; thus, 3 + 4.5 is equivalent to operator.add(*coerce(3, 4.5)) and results in operator.add(3.0, 4.5) which is of course imagary part. Imaginary numbers are real multiples of the imaginary unit, often written i in mathematics or j in engineering. Python has builtin support for complex numbers, which are written with this latter notation; the imaginary part is written with a j suffix, e.g., 3+1j. To get access to complex equivalents of the math module, use cmath. Use of complex numbers is a fairy advanced mathematical feature; if you're not aware of a need for complex numbers, it's almost certain you can safely ignore them.
conversion - The invocation of a well-defined mechanism from of transforming an instance of one type of object to an instance of another; for example, int('3') will convert a string ('3') to an int (3).
decorator - A function that modifies another function or method. Its return value is typically a callable object, possibly the original function, but most often another function that modifies the original function's behavior in some fashion.
descriptor - Any object that defines the methods __get__(), __set__(), or __delete__(). When a class attribute is a descriptor, its special binding behavior is triggered upon attribute lookup. Normally, writing a.b looks up the object b in the class dictionary for a, but if b is a descriptor, the defined method gets called. Understanding descriptors is a key to a deep understanding of Python because they are the basis for many features including functions, methods,properties, class methods, static methods, and reference to super classes.
dictionary - A built-in Python data type composed of arbitrary keys and values; sometimes called a "hash" or a "hash map" in other languages, although this is technically a misnomer (hashing is one way to implement an associative array but not the only way). The use of dict much resembles that for list, but the keys can be any object with a __hash__ function, not just integers starting from zero. Examples: d = {'A':65, 'B':66}, d = dict([('A', 65), ('B', 66)]), d['C'] = 67
docstring - A string that appears as the lexically first expression in a module, class definition or function/method definition is assigned as the __doc__ attribute of the object where it is available to documentation tools or the help() builtin function.
duck typing - From the "If it walks, talks, and looks like a duck, then its a duck" principle. Python uses duck typing in that if an object of some user-defined type exhibits all of the expected interfaces of some type (say the string type), then the object can be treated as if it really were of that type.
dynamic typing - A style of typing of variables where the type of objects to which variables are assigned can be changed merely by reassigning the variables. Python is dynamically typed. Thus, unlike as in a statically typed language such as C, a variable can first be assigned a string, then an integer, and later a list, just by making the appropriate assignment statements. This frees the programmer from managing many details, but does come at a performance cost.
EAFP - Acronym for the saying it's "Easier to Ask for Forgiveness than Permission". This common Python coding style assumes the existance of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statments. The technique contrasts with the LBYL style that is common in many other languages such as C.
EIBTI - Acronym for "Explicit Is Better Than Implicit", one of Python's design principles, included in the Zen of Python.
exception ???
first-class object A first class object in a programming language is a language object that can be created dynamically, stored in a variable, passed as a parameter to a function and returned as a result by a function (from). In Python, practically all objects are first-class, including functions, types, and classes.
function - A block of code that is invoked by a "calling" program, best used to provide an autonomous service or calculation.
generator function - A function that returns a generator iterator. Its definition looks like a normal function definition except that it uses the keyword yield. Generator functions often contain one or more for or while loops that yield elements. The function execution is stopped at the yield keyword (returning the result) and its resumed there when the next element is requested (e.g., by the builtin function next()). For details see PEP 0255 and PEP 0342.
generator - The common name for a generator iterator. The type of iterator returned by a generator function or a generator expression.
global interpreter lock or GIL - the lock used by Python threads to assure that only one thread can be run at a time. This simplifies Python by assuring that no two processes can access the same memory at the same time. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of some parallelism on multi-processor machines. Efforts have been made in the past to create a "free-threaded" interpreter (one which locks shared data at a much finer granularity), but performance suffered in the common single-processor case. See GlobalInterpreterLock.
greedy regular expressions - Regular expressions which match the longest string possible. The *, + and ? operators are all greedy. Their counterparts *?, +? and ?? are all non-greedy (match the shortest string possible).
hash - A number used to correspond to objects, usually used for 'hashing' keys for storage in a hash table. Hashing in Python is done with the builtin hash function
hash table - An object that maps more-or-less arbitrary keys to values. Dictionaries are the most visible and widely used objects that exhibit this behavior.
hashable - An object is hashable if it is immutable (ints, floats, tuples, strings, etc) or user-defined classes that define a __hash__ method.
id - id is a built-in function which returns a number identifying the object, referred to as the object's id. It will be unique during the lifetime of the object, but is very often reused after the object is deleted.
IDLE - an Integrated Development Environment for Python. IDLE is a basic editor and intepreter environment that ships with the standard distribution of Python. Good for beginners and those on a budget, it also serves as clear example code for those wanting to implement a moderately sophisticated, multi-platform GUI application.
immutable - An object with fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed such as the keys of a dictionary.
integer division - Mathematical division discarding any remainder, for example 3 / 2 returns 1, in contrast to the 1.5 returned.
interactive - Python has an interactive interpreter which means that you can try out things and directly see its result, just launch python with no arguments. A very powerful way to test out new ideas, inspect libraries (remember x.__doc__ and help(x)) and improve programming skills.
interpreted - Python is an interpreted language (like Perl), as opposed to a compiled one (like C). This means that the source files can be run directly without first creating an executable which is then run. Interpreted languages typicaly have a shorter development/debug cycle than compiled ones, though their programs generally also run more slowly. See also interactive.
iterable - A container object capable of returning its members one at a time. Examples of iterables include all sequence types (list, str, tuple, etc.) and some non-sequence types like dict and file and objects of any classes you define with an __iter__ or __getitem__ method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...). When an iterable object is passed as an argument to the built, generator and reiterable.
iterator - that attempts multiple iteration passes. A container object (e.g. a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object from the second iteration pass and on, making it appear like an empty container.
LBYL - Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized the presence of many if statements.
list - A built-in Python datatype, which is a mutable sorted sequence of values. Note that only sequence itself is mutable; it can contain immutable values like strings and numbers. Any Python first-class object can be placed in a tuple as a value.
list comprehension - A neat syntactical way to process elements in a sequence and return a list with the results. result = ["0x%02x" % x for x in range(256) if x % 2 == 0] generates a list of strings containing hex numbers (0x..) that are even and in the range from 0 to 255. The if part is optional' all elements are processed when it is omitted.
mapping - A container object (such as dict) that supports arbitrary key lookups using __getitem__..
method ???
module ???
mutable - Mutable objects can change their value but keep their id(). See also immutable.
N-Z
namespace - The place where a variable is stored in a Python program's memory. Namespaces are implemented as a dictionary. There are the local, global and builtins namespaces and the nested namespaces in objects (in methods). Namespaces support modularity by preventing naming conflicts. For instance, __builtins__.open() and os.open() are distinguished by their namespaces. Namespaces also aid readability and maintainabilty by making it clear which modules implement a function. For instance, writing random.seed() and itertools.izip() will make it clear that those functions are implemented by the random and itertools modules that inherits from object. This includes all built-in types like list and dict. Only new style classes can use Python's newer, versatile features like __slots__, descriptors, properties, __getattribute__, class methods, and static methods.
object - Any data with state (attributes or value) and defined behavior (methods).
object oriented - Programming typified by a data-centered (as opposed to a function-centered) approach to program design.
old-style class - Any class that does not inherit (directly or indirectly) from object.
pie syntax - A syntax using '@' for decorators that was committed to an alpha version of Python 2.4. So called because the '@' vaguely resembles a pie and the commital came on the heels of the Pie-thon at an open source conference in 2004.
property - a built-in data type, used to implement managed (computed) attributes. You assign the property object created by the call property( optional-args ) to a class attribute of a new-style class. When the attribute is accessed through an instance of the class, it dispatches functions that implement the managed-attribute operations, such as get-the-value and set-the-value.
Python 3000 - A mythical Python release, allowed to be backward incompatible, with telepathic interface.
regular expression - A formula for matching strings that follow some pattern. Regular expressions are made up of normal characters and metacharacters. In the simplest case, a regular expression looks like a standard search string. For example, the regular expression "testing" contains no metacharacters. It will match "testing" and "123testing" but it will not match "Testing". Metacharacters match some expressions like '.' metacharacter match any single character in a search string.
reiterable - An iterable object which can be iterated over multiple times. Reiterables must not return themselves when used as an argument to iter().
sequence - An iterable that also supports random access using __getitem__ and len. Some builtin sequence types are list, str, tuple, and unicode. Note that dict also supports these two operations but is considered a mapping rather than a sequence because the lookups use arbitrary keys rather than consecutive numbers and it should be considered unsorted.
_.
static typing - A style of typing of variables common to many programming languages (such as C) where a variable, having been assigned an object of a given type, cannot be assigned objects of different types subsequently.
string - One of the basic types in Python that store text. In Python 2.X strings store text as a 'string of bytes', and so the string type can also be used to store binary data. Also see Unicode.
triple-quoted string - A string that is bounded by three instances of either the double quote mark (") or the single quote mark ('). For instance:
'''This is such a string'''
They are useful for multiple reasons: they allow you to include both single and double quotes within a string quite easily, and they can span multiple lines without the use of line-continuation characters (very useful in docstrings).
tuple - (pronounced TUH-pul or TOO-pul) A built-in Python datatype, which is an immutable ordered sequence of values. Note that only the sequence itself is immutable. If it contains a mutable value such as a dictionary, that value's content may be changed (e.g. adding new key/value pair). Any Python first-class object can be placed in a tuple as a value.
type - A "sort" or "category" of data that can be represented by a programming language. Types differ in their properties (such as mutability and immutability), the methods and functions applicable to them, and in their representations. Python includes, among others, the string, integer, long, floating point, list, tuple, and dictionary types.
unicode - The unicode type is the companion to the string type. They are used to store text with characters represented as Unicode code points.
whitespace - The unconventional use of space characters (' ') to control the flow of a program. Instead of a loosely-enforced ideal, this is an integral part of Python syntax. It's a tradeoff between readability and flexibility in favor of the former.
Zen of Python - listing of Python design principles and philosophies that are helpful in understanding and using the language effectively. The listing can be found by typing "import this" at the interactive prompt.
misc
>>> - The typical Python prompt of the interactive shell. Often seen for code examples that can be tried right away in the interpreter. Not to be confused with ">" symbols used for the indentation of cited material on email lists. | https://wiki.python.org/moin/PythonGlossary?highlight=(CategoryDocumentation) | CC-MAIN-2016-22 | refinedweb | 2,627 | 55.95 |
I need help with True, False, NOT, AND, OR, I know what they do but how do I use them in code?(btw I am a complete nobbie I just started like 2 days ago...) thanks!
This is a discussion on Help with True, False, NOT, AND, OR... within the C++ Programming forums, part of the General Programming Boards category; I need help with True, False, NOT, AND, OR, I know what they do but how do I use them ...
I need help with True, False, NOT, AND, OR, I know what they do but how do I use them in code?(btw I am a complete nobbie I just started like 2 days ago...) thanks!
That's a very open ended question.... You can use them in many, many scenarios..
AND/OR/NOT are represented as operators: &&/||/! respectively.. true and false are both keywords (false represents Zero, and true typically represents One), and are generally the 2 possible outcomes of any expression involving these operators.
Thanks Bench82 but I ment how do I use them in code I know what they do I just dont know how 2 use them...
Alright if you know how to use them then what are you doing here?
if you need examples you should know from what your getting the knoledge from.
//Enouph of the flame
Alright here are some examples.
its untested but those are examplesits untested but those are examplesCode:#include <iostream>//Basic Library using namespace std;// Namespace for not typing out the whole function like so std::cout// int main(){// You need int main for compiler even to read this. int i=0,a=0; // Numbers only Thats 6 digit limit// bool event; // True and False// if(i==0 &&/* && means AND*/ a==0){ // example of AND event=true;// example of True event=false;//Example of false } if(event==true || event==false){ // example of or i=1; } if(i != 0){//Example of Not cout<<"i does not equal 0"<<endl;// This is Outputing whats inside of quotes// system("PAUSE");// This pauses the system for you to see ouput // } }
OK - well, it's still a very open ended question... You might be better off looking at this tutorial.... - well, it's still a very open ended question... You might be better off looking at this tutorial....
Originally Posted by cgsarebeastOriginally Posted by cgsarebeast
I have I need It more explaned basicly
Dude how basic do you need it I just gave you examples!!!
Srry like I said I just started 2 days ago, I dont know how 2 describe it, I guess It would be explaning thanks for ur help i'm a slow learner
...........Dude your not slow your just feeble minded .
I dont think no ones going to spoon feed you everything
that example was 2 advance if you can could u break it down (btw I'm only on lesson 3 of this sites help)
dude I am not lazy (well sort of lol
) but I really am a slow learner and if u cant help me PLEASE dont make comments like that cuz u dont know me or if I am a slow learner or not!) but I really am a slow learner and if u cant help me PLEASE dont make comments like that cuz u dont know me or if I am a slow learner or not!
but I do apresheate you help if you wanna give it (srry I'm a VERY bad speller)
Your kidding me if thats to advance then im god.
watch maybe your thinking this is code
//<--- its not those are comments anything after this is commented.
and
/* */ those are also comments anything between these are commented.
Last edited by unkownname; 05-09-2006 at 06:07 PM.
I need 2 put 2 -n- 2 tougther for ex. how would I use a True, False, AND, OR, NOT with text.... like how would I combinde the 2 things and it work, I dont know how else 2 desribe it... thanks though
right, first off. Learn to spell. if you can't even spell, coding is not for you. But I don't believe you can't spell, I think you're just being lazy.
I'll give you some starters:
- '2' is a number. 'to' is a word. They have different meanings.
- there is no such word in the english language as '-n-'. The word is
'and', and it takes the same amount of time to type!
edit: and if you still can't spell, use a spell checker!
You might think, I'm being pedantic (or just being an ..............), but when you code, if you make a speeling mistock, your code won't work.
as for your question, boolean logic (true, false, and, or, etc) is used to make decisions in a program.
Code:int age = 20; if (age < 10) // evaluates to true { cout << "you are young"; // this means print "you are young" on the screen } else if (age >= 10 && age < 20) // this means if the age is greater than 10 AND less than 20 { cout << "you are an? | http://cboard.cprogramming.com/cplusplus-programming/78952-help-true-false-not.html | CC-MAIN-2015-48 | refinedweb | 849 | 79.09 |
Java Exercises: Find a contiguous subarray with largest sum from a given array of integers
Java Basic: Exercise-122 with Solution
Write a Java program to find a contiguous subarray with largest sum from a given array of integers.
Note: In computer science, the maximum subarray problem.
The subarray should contain one integer at least.
Pictorial Presentation:
Sample Solution:
Java Code:
public class Main { public static void main(String[] args) { int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; System.out.print(max_SubArray(nums)); } public static int max_SubArray(int[] nums) { if (nums.length < 1) { return 0; } int max = nums[0]; int max_Begin = 0; int max_End = 0; int begin = 0; int end = 0; int sum = 0; while (end < nums.length) { sum += nums[end]; if (sum < 0) { sum = 0; begin = end + 1; } else { if (sum > max) { max = sum; max_Begin = begin; max_End = end; } } end++; } return max; } }
Sample Output:
6
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to reverse a given linked list.
Next: Write a Java program to find the subarray with smallest sum from a given array of integers.
What is the difficulty level of this exercise?
New Content: Composer: Dependency manager for PHP, R Programming | https://www.w3resource.com/java-exercises/basic/java-basic-exercise-122.php | CC-MAIN-2019-18 | refinedweb | 205 | 53.61 |
I want to run different remote procedure on different servers without waiting for a reply from server. and as a server completes the procedure I want to have reply at the client. Can it be possible to do with grpc golang?
I want to run different remote procedure on different servers without waiting for a reply from server. and as a server completes the procedure I want to have reply at the client. Can it be possible to do with grpc golang?
I want to implement a blockchain network and I want to ask different peers to execute a transaction but I don't want to wait until one peer provides the output of execution and then I move to other peer.
In other word I want to broadcast the execution of procedure and then have all the answers as execution is being done.
I tried the common methods for connecting client and server but it waits for the response from the server. it will increase the time when execution needs to be done on more peers.
This post will explain some of the reasons why we decided to leave Python behind and make the switch to Go. Switching to a new language is always a big step, especially when only one of your team members has prior experience with that language.
Switching to a new language is always a big step, especially when only one of your team members has prior experience with that language. Early this year, we switched primary programming language from Python to Go. This post will explain some of the reasons why we decided to leave Python behind and make the switch to Go.Reasons to Use Go
Go is extremely fast. The performance is similar to that of Java or C++. For our use case, Go is typically 30 times faster than Python. Here’s a small benchmark game comparing Go vs Java.
For many applications, the programming language is simply the glue between the app and the database. The performance of the language itself usually doesn’t matter much.
Stream, however, is an API provider powering the feed infrastructure for 500 companies and more than 200 million end users. We’ve been optimizing Cassandra, PostgreSQL, Redis, etc. for years, but eventually, you reach the limits of the language you’re using... .Disadvantages of Using Gol.
We have a small development team at Stream powering the feeds for over 200, you’ll hearn how to build an app with Vuejs and Golang
I know, these two aren’t popular to be used along with each other. But, let’s try…Background
Okay so first, let’s talk about the features these technologies provide.Golang
Golang and Vuejs both are fast during runtime. Thus, making them work with each other provide a fast single page application.
Ok, let’s start.Setting up directories
First, set up your directories like below. “LICENSE” and “README.md” for
Git.
Now, in backend directory create a file
server.go
For frontend, type the following in the terminal to create a new app
Calculator,
vue create calculator
It will ask you to choose a preset. Choose the default one (babel, eslint).
Now this will be the folder structure.
The skeleton is ready!
Now, let’s see what we are going to build. It’s not a fancy app but will help you get started to build complex apps.
We are going to build a calculator in which you will enter two numbers, they will be grabbed by Vue frontend and sent to the Golang server using a POST request. The server will compute addition, multiplication, subtraction and division and send back the results using a POST request. The frontend will then render the results.Build the backend
Golang is fast and the reason for it is the compiler, which doesn’t let you declare variables unless you use them. If you declare something or import any package you will have to use it. It is very strict about it. And also whatever you are going to do you have to tell the compiler beforehand like: if you want to grab the POST data, you have to declare the structure of the JSON data beforehand. This is a little tricky but worth the speed.
Coming to the code.
So, we’ll use the
encoding/json and
net/http packages. Then, we’ll declare the structures for the JSON data.
packages and the JSON data structures
Now, we’ll write a simple function to do the calculations. Here, we need to specify the return type explicitly.
process function
We need to write a function which will be called when we have to process the JSON data coming to the backend using POST request.
On line 33, we are declaring a
JSON decoder to decode the incoming JSON data from the
request's body.
numsData and
numsResData are the declared structures.
The incoming data is stored in
numsData and is decoded on line 38.
Then we set up the
ResponseWriter’s headers and then send the JSON response on line 47 and check for errors.
At last, the main function. Here we can define the HTTP routing. For every URL the respective function can be defined like on line 53. The backend server will run on PORT
8090.
The complete code is below:
package mainNow let’s build the frontend
import (
"encoding/json"
"fmt"
"net/http"
)
type numbers struct {
Num1 float64
json:"num1"
Num2 float64
json:"num2"
}
type numsResponseData struct {
Add float64
json:"add"
Mul float64
json:"mul"
Sub float64
json:"sub"
Div float64
json:"div"
}
func process(numsdata numbers) (numsResponseData) {
var numsres numsResponseData numsres.Add = numsdata.Num1 + numsdata.Num2 numsres.Mul = numsdata.Num1 * numsdata.Num2 numsres.Sub = numsdata.Num1 - numsdata.Num2 numsres.Div = numsdata.Num1 / numsdata.Num2 return numsres
}
func calc(w http.ResponseWriter, request *http.Request) {
decoder := json.NewDecoder(request.Body)
var numsData numbers var numsResData numsResponseData decoder.Decode(&numsData) numsResData = process(numsData) fmt.Println(numsResData) w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(numsResData); err != nil { panic(err) }
}
func main() {
http.HandleFunc("/", calc)
http.ListenAndServe(":8090", nil)
}
First
cd into the frontend directory and install the dependencies using the below command.
npm install --save bootstrap-vue bootstrap axios vee-validate
We’ll use
axios for handling POST requests,
vee-validate for validating the input form data and,
bootstrap-vue for pretty interfaces.
In
src/Calculator.vue we have to write the frontend part.
From line 17 to 25, we are defining the input boxes and labels to get the data.
v-model is used to get the data in Vue.
The lines 30–35 define the UI for displaying the calculations and on line 43 a button, which will trigger the
postreq() function which we will be defining next.
In the
script tag, we write the javascript. First, we’ll import the requirements.
writing scripts tag
Lines 54–59 are the necessary stuff, importing
axios and
vee-validate.
Then, we’ll define the variables which we’ll use on lines 64–69. The
data variable stores all the variables for the Calculator component.
In
methods, all the functions are defined. We created
postreq() function from where we are sending the POST request with JSON data to the url: . Remember the
calc function we created in
server.go file? We are sending the JSON data there. After the data is sent, the response from the backend is stored in the result variable, from which we set the
add, mul, sub and
div variables which are binded to the HTML using
{{ add }} etc. to show the result.
<template>
<div class="hello">
<!-- <h1>{{ msg }}</h1> -->
<div> <h1 class="title">Calculator</h1> </div> <hr> <div> <b-container fluid> <b-row <b-col</b-col> <b-col <form> <div class="field"> <label class="label">First Number</label> <b-form-input</b-form-input> </div> <div class="field" style="margin-top:13px;"> <label class="label">Second Number</label> <b-form-input</b-form-input> </div> </form> </b-col> <b-col <div><label class="label">Addition: {{ add }}</label></div> <div><label class="label">Multiplication: {{ mul }}</label></div> <div><label class="label">Subtraction: {{ sub }}</label></div> <div><label class="label">Division: {{ div }}</label></div> </b-col> </b-row> </b-container> </div> <div> <b-buttonCalculate</b-button> </div> <hr>
</div>
</template>
<script>
import axios from 'axios';
import Vue from 'vue'
import VeeValidate from 'vee-validate'
/* eslint-disable */
Vue.use(VeeValidate)
export default {
name: 'Calculator',
data: function() {
return {
add: "", multi: "", sub: "", div: "",
num1: "", num2: ""
}
},
methods: {
postreq: function() {
var data = {"num1": parseFloat(this.num1), "num2": parseFloat(this.num2)}
/*eslint-disable*/ console.log(data) /*eslint-enable*/ axios({ method: "POST", url: "", data: data, headers: {"content-type": "text/plain" } }).then(result => { // this.response = result.data; this.add = result.data['add'] this.mul = result.data['mul'] this.sub = result.data['sub'] this.div = result.data['div'] /*eslint-disable*/ console.log(result.data) /*eslint-enable*/ }).catch( error => { /*eslint-disable*/ console.error(error); /*eslint-enable*/ }); }
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
Pretty simple huh? Yes, it is!
And that’s all we need to do. Just remember the points.
The backend server can be run using
go run server.go
It will run on PORT
8090.
The frontend can be run using
npm run serve
Congratulations !!! Your app is ready.
The whole code is available on the Github repo.
Also, checkout an app Rocket Engine Designer, I built using Vuejs and Golang here.
Thanks for reading ❤
If you liked this post, share it with all of your programming buddies!
☞ The Complete JavaScript Course 2019: Build Real Projects!
☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
☞ Best JavaScript Frameworks, Libraries and Tools to Use in 2019
☞ Build a Progressive Web App In VueJs
☞ Build a CMS with Laravel and Vue
☞ Beginner’s Guide to Vue.js
☞ Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)
☞ Vue.js Tutorial: Zero to Sixty
☞ Moving from NodeJS to Go
☞ Building Modern Desktop Apps in Go
☞ Google’s Go Essentials For Node.js / JavaScript Developers
☞ The Complete Guide to Arrays in Go
☞ Go Programming Language Tutorial | Golang Tutorial For Beginners | Go / Golang Crash Course
If you are new to Go language then, you may be heard or seen in the code about interface{} a lot in code snippets and tutorials. This can be very daunting seeing this at first. Interface implementation is one of the core concepts of Object-oriented programming language. If you have used Java, PHP, or Python then you might know what interface is and how it can be useful to build a scalable application.Go Interface
An interface in Go is a type defined using a set of method signatures. The interface defines the behavior for similar type of objects.
For example, Here is an interface that defines the behavior for Geometrical shapes:
// Go Interface - `Shape` type Shape interface { Area() float64 Perimeter() float64 }
An interface is declared using the
type keyword, followed by the name of the interface and the keyword
interface. Then, we specify a set of method signatures inside curly braces.
To implement an interface, you just need to implement all the methods declared in the interface.
Go Interfaces are implemented implicitly
Unlike other languages like Java, you don’t need to explicitly specify that a type
implements an interface using something like an implements keyword.
Here are two Struct types that implement the
Shape interface:
// Struct type `Rectangle` - implements the `Shape` interface by implementing all its methods. type Rectangle struct { Length, Width float64 } func (r Rectangle) Area() float64 { return r.Length * r.Width } func (r Rectangle) Perimeter() float64 { return 2 * (r.Length + r.Width) }
Using an interface type with concrete valuesUsing an interface type with concrete values
// Struct type `Circle` - implements the `Shape` interface by implementing all its methods. type Circle struct { Radius float64 } func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius } func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius } func (c Circle) Diameter() float64 { return 2 * c.Radius }
An interface in itself is not that useful unless we use it with a concrete type that implements all its methods.
Let’s see how an interface can be used with concrete values.
package main import ( "fmt" "math" ) func main() { var s Shape = Circle{5.0} fmt.Printf("Shape Type = %T, Shape Value = %v\n", s, s) fmt.Printf("Area = %f, Perimeter = %f\n\n", s.Area(), s.Perimeter()) var s1 Shape = Rectangle{4.0, 6.0} fmt.Printf("Shape Type = %T, Shape Value = %v\n", s1, s1) fmt.Printf("Area = %f, Perimeter = %f\n", s1.Area(), s1.Perimeter()) }
# Output Shape Type = main.Circle, Shape Value = {5} Area = 78.539816, Perimeter = 31.415927 Shape Type = main.Rectangle, Shape Value = {4 6} Area = 24.000000, Perimeter = 20.000000
package main import ( "fmt" ) // Interface types can also be used as fields type MyDrawing struct { shapes []Shape bgColor string fgColor string } func (drawing MyDrawing) Area() float64 { totalArea := 0.0 for _, s := range drawing.shapes { totalArea += s.Area() } return totalArea } func main() { drawing := MyDrawing{ shapes: []Shape{ Circle{2}, Rectangle{3, 5}, Rectangle{4, 7}, }, bgColor: "red", fgColor: "white", } fmt.Println("Drawing", drawing) fmt.Println("Drawing Area = ", drawing.Area()) }
Interface values: How does an interface type work with concrete values?Interface values: How does an interface type work with concrete values?
# Output Drawing {[{2} {3 5} {4 7}] red white} Drawing Area = 55.56637061435917
Under the hood, an interface value can be thought of as a tuple consisting of a value and a concrete type:
// interface (value, type)
Let’s see an example to understand more:
package main import ( "fmt" ) func main() { var s Shape s = Circle{5} fmt.Printf("(%v, %T)\n", s, s) fmt.Printf("Shape area = %v\n", s.Area()) s = Rectangle{4, 7} fmt.Printf("(%v, %T)\n", s, s) fmt.Printf("Shape area = %v\n", s.Area()) }
# Output ({5}, main.Circle) Shape area = 78.53981633974483 ({4 7}, main.Rectangle) Shape area = 28
Checkout the output of the above program and notice how the variable
s has information about the value as well as the type of the
Shape that is assigned to it.
When we call a method on an interface value, a method of the same name on its underlying type is executed.
For example, in the above program, when we call the method
Area() on the variable
s, it executes the
Area() method of its underlying type. | https://morioh.com/p/170ab93b1d7b | CC-MAIN-2019-47 | refinedweb | 2,444 | 58.28 |
I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles.
Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (
user.get_template.lastIP, for example), I get the following error:
Environment: Request Method: GET Request URL: Django Version: 1.1 Python Version: 2.6.1 Template error: In template /path/to/base.tpl, error at line 19 Caught an exception while rendering: too many values to unpack 19 : Hello, {{user.username}} ({{ user.get_profile.rep}}). How's it goin? Logout Exception Type: TemplateSyntaxError at / Exception Value: Caught an exception while rendering: too many values to unpack
Any ideas as to what's going on or what I'm doing wrong?
That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3
def returnATupleWithThreeValues(): return (1,2,3) a,b,c = returnATupleWithThreeValues() print a print b print c
But this raises your error
def returnATupleWithThreeValues(): return (1,2,3) a,b = returnATupleWithThreeValues() print a print b
raises
Traceback (most recent call last): File "c.py", line 3, in ? a,b = returnATupleWithThreeValues() ValueError: too many values to unpack
Now, the reason why this happens in your case, I don't know, but maybe this answer will point you in the right direction.
try unpacking in one variable,
python will handle it as a list,
then unpack from the list
def returnATupleWithThreeValues(): return (1,2,3) a = returnATupleWithThreeValues() # a is a list (1,2,3) print a[0] # list[0] = 1 print a[1] # list[1] = 2 print a[2] # list[2] = 3 | https://pythonpedia.com/en/knowledge-base/1479776/-too-many-values-to-unpack--exception | CC-MAIN-2020-45 | refinedweb | 301 | 50.97 |
What are the main references to the fish-eye camera model in OpenCV3.0.0dev?
Hi Guys,
I am wrestling with the Fish-Eye Camera Model used in OpenCV 3.0.0.dev. I have read the documentation in this link several times, especially the "Detailed Description" part and formulas modelling fish-eye distortion. By now I have two concerns:
Based on the projection models listed here and their conceptual explanations in "Accuracy of Fish-Eye Lens Model" By Hughes, I can't figure out which projection model has been used in OpenCV implementation.
Since the description is so concise, I need to know the main reference papers used by OpenCV developers for implementing fish-eye namespace, so that I could be on the ball and get through more details.
P.S. I checked OpenCV 3.0.0-dev Documentation and did not find anything useful.
Thanks everyone for your help,
Kind Regards,
Masih | https://answers.opencv.org/question/65020/what-are-the-main-references-to-the-fish-eye-camera-model-in-opencv300dev/ | CC-MAIN-2019-47 | refinedweb | 154 | 62.27 |
7 Common Mistakes Made By C# Programmers
WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
Introduction
Making mistakes is inevitable in programming. Even a small mistake could prove to be very costly. The wise thing is to learn from your mistakes and try not to repeat them. In this article I will be highlighting the mistakes which I consider to be the 7 most common mistakes made by C# developers.
Formatting a string
There lies the strong possibility of making costly mistakes while working with string types in C# programming. String is always an immutable type in the .NET Framework. When a string is modified it always creates a new copy and never changes the original. Most developers always format the string as shown in the sample below:
string updateQueryText = "UPDATE EmployeeTable SET Name='" + name + "' WHERE EmpId=" + id;
The above code is really messy and also as the string is immutable it creates 3 unnecessary garbage string copies in the memory as a result of multiple concatenations.
The better approach is to use
string.Format as it internally uses
StringBuilder which is mutable. It also paves the way for a clean code.
string updateQueryText = string.Format("UPDATE EmployeeTable SET Name='{0}' WHERE EmpId={1}", name, id);
Nested Exception Handling
Developers who intend to write nested methods end up doing exception handling for each methods as shown in the below code:; } } }
So what would happen with the above code if the same exception were handled multiple times and more over catching exceptions, throwing it will definitely add a performance overhead.
I try to avoid this by putting the exception handling in a single place that is in the MainMethod as shown below:
public class NestedExceptionHandling { public void MainMethod() { try { //some implementation ChildMethod1(); } catch(Exception exception) { //Handle exception } } private void ChildMethod1() { //some implementation ChildMethod2(); } private void ChildMethod2() { //some implementation } }
Using Foreach on Huge Collections
Most developers prefer to use a
foreach loop than
for loop because
foreach is easier to use. This will however prove to be costly when working with collections with a large amount of data. Consider the below sample in which I am looping through the same datatable using
for); / loop is slow, it takes almost double the amount of time as that of the
for loop. This is because in the
foreach loop
dt.Rows will access all the rows in the datatable.
For bigger collections always use
for loop in case
if looping is required.
There are no comments yet. Be the first to comment! | https://www.codeguru.com/csharp/article.php/c17911/7-Common-Mistakes-Made-By-C-Programmers.htm | CC-MAIN-2017-51 | refinedweb | 431 | 51.07 |
KendoReact Data Binding Overview
You can data-bind all KendoReact components, for which it makes sense to connect a data set. This includes a long list of components, such as the React Data Grid, KendoReact Scheduler and many more. As a result, when the state updates, the controlled components will re-render to reflect the changes in the UI.
To set the default values of the uncontrolled KendoReact components, you can use any variable from the application.
The KendoReact components do not manipulate the data internally or make requests to the server. The components have a public API that allows you to make requests by providing events and parameters with important information about the event. This approach follows the React best practices to provide you with the freedom to use any server technology and tooling for interacting with the server.
Binding to Local Data
When the data is locally available in a JSON format, you can:
- Directly set the data to the respective prop of the component:
const data = ["X-Small", "Small", "Medium", "Large", "X-Large", "2X-Large"]; return ( <DropDownList data={data} /> );
- Set the local data in the state and set that state variable to the KendoReact component. This will automatically update the KendoReact component UI when the data in the state is updated:
const [data, setData] = React.useState(["X-Small", "Small", "Medium", "Large", "X-Large", "2X-Large"]); return ( <DropDownList data={data} /> );
Binding to Remote Data
All KendoReact components can work with data from any server as long as it is received or parsed in JSON format. All KendoReact components follow the same flow when integrating with remote data. These are the most common cases:
- Load data from an API to the component.
- Perform server operations like sorting, paging, filtering, etc.
- Update the data on the server after editing.
You can load the data by making a request to the server and then updating the state with it:
- Bind the KendoReact component to a state variable.
- When the component loads or on any other event occurs, make a request to the API to get the data. The request is made on the application level by the developer.
- When the request is completed, update the state with the data from the API. This will automatically update the KendoReact component.
Using Server Data Operations
- Bind the KendoReact component to a state variable.
- Use the component event associated with the data operation that must be done on the server. For example, if you need server filtering for the DropDownList, use its onFilterChange event.
- During that event, make a request to the server using the parameters provided inside the event arguments. The request has to be done on the application level by the developer.
- When the data from the server is received, update the state variable that is bound to the component. This will automatically update the component with the new data.
Saving Changes After Editing
Saving the changes on the server is done on the application level by the developer and based on user action. The exact implementation can vary based on the used component and the application requirements. For example, you can update a single item in a component after an update button is clicked or you can save the entire data state at once after editing multiple elements. All this is done by programmatically making a server request with the data that has to be updated. | https://www.telerik.com/kendo-react-ui-develop/components/data-binding/ | CC-MAIN-2022-40 | refinedweb | 565 | 52.8 |
View Complete Post am a bit new to the .NET environment, and though I feel I was able to get a good handle on most of the basics of .NET, I believe I've encountered a problem beyond the basics. I am trying to talk with a device called a ColorPAL that uses
asynchronous serial communication, but it is half-duplex instead of full-duplex. I am able to send it the hex string commands that it wants just fine with the TX line. However, I find myself unable to read because the RX isn't connected to anything.
Basically what I want to do is that I want to be able to swap the TX line to become a RX line so that I can then read line of the half-duplex. I read that there is a PinChanged event, so it lead me to believe there is a way to change pins??
If the RX line is very high impedance I could connect it to the TX line, but I have no idea about that.
How can I get a full duplex to read a half-duplex using the visual studio software?
Here is the code I'm using, in case that helps.
#include "stdafx.h"
#include <Windows.h>
using namespace System;
using namespace
While I have not bothered about this earlier I am going to need to get this sorted asap now that we are building a large Persisted (File System Based) Data Store.
The code below as it is will output this XML File contents
<?xml version="1.0"?>
<SimpleSerializationObject xmlns:
<HyphenatedNumber34>
?
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/links/7559-faq-how-do-i-use-serialport-class-for-simple.aspx | CC-MAIN-2018-05 | refinedweb | 281 | 71.24 |
programming best practices for warnings
Will Klem
Greenhorn
Posts: 21
posted 6 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Being a rank newbie to programming, I want to get started on the right foot. Forming good habits now will be much easier than breaking bad habits later. Several of my programs have had "variable not used" warnings; however, they have both compiled properly and provided the desired (and correct) results. I am quite certain that ignoring the warnings because the program works is unprofessional. For example: if I initialize variables in main as placeholders for use in a method, I receive the warnings. Should I make an effort to resolve these warnings, or are there some warnings which should be ignored?
This code, which I posted in another
thread
, works properly and has "the value of local variable ... is not used" warnings in lines 22-26.
/* This program uses methods to calculate the distance between * two points */ public class DistanceBetweenTwoPoints { public static double distance(double x1, double y1, double x2, double y2) { double dx = x2 - x1; double dy = y2 - y1; double dsquared = dx*dx + dy*dy; double result = Math.sqrt(dsquared); System.out.println("dx is " + dx); System.out.println("dy is " + dy); System.out.println("dsquared is " + dsquared); System.out.println("distance is " + result); return result; } public static void main(String args[]) { double x1 = 0.0; //value is place holder double x2 = 0.0; //value is place holder double y1 = 0.0; //value is place holder double y2 = 0.0; //value is place holder double result = 0.0; DistanceBetweenTwoPoints.distance(1.0, 2.0, 4.0, 6.0); System.out.println(DistanceBetweenTwoPoints.distance(1.0, 2.0, 4.0, 6.0)); /* answer received from Java Ranch forum: * You have the method "distance" which returns the result. So, think about it as your result being returned to line 28, from where you're calling it. There are two options to solve that quickly: 1. on line 28 you do "double result = DistanceBetweenTwoPoints.distance(1.0, 2.0, 4.0, 6.0);" in this case "result" will hold the returned value 2. put line 28 inside line 30 print statement, it will return value and will print out without storing it. */ /* this solution #1 works: * double result = DistanceBetweenTwoPoints.distance(1.0, 2.0, 4.0, 6.0); * /*System.out.println("result = " + result); /* this solution #2 works: * System.out.println(DistanceBetweenTwoPoints.distance(1.0, 2.0, 4.0, 6.0)); */ } }
Your thoughts on this subject will be appreciated.
Bear Bibeault
Sheriff
Posts: 67663
173
I like...
posted 6 years ago
1
Number of slices to send:
Optional 'thank-you' note:
Send
The warnings are a sign that your code is flawed. You are wise to realize that just because something "works" doesn't mean that it is good.
You should
strive to find out what the warnings mean, how they point out the flaws in the code, and resolve them.
It's also quite likely that the conditions causing the warnings are "bugs waiting to happen" that can reveal themselves with future changes in the code. (Be aware that code has "lifetime". The problems you create
today
can haunt you for years to come.)
It's sort of like if a car were designed with flaws in steering such that the steering works
now
, but if a different set of tires were put on, well, maybe it'd stop working.
[
Asking smart questions
] [
About Bear
] [
Books by Bear
]
Mike. J. Thompson
Bartender
Posts: 689
17
posted 6 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
If you declare a variable in one method it is not possible to use it in another method because its scope will be local to the method you declared it in.
Take for example your variables
x1, x2, y1, y2
and
result
in main. You say they're placeholders, but what are they placeholders for? You're not using them, so they shouldn't be there. They're not breaking anything but they will likely cause confusion to you and whoever reads the code.
And just to be clear, those variables in main have no relationship to and have no effect on the parameters to the distance() method. They happen to have the same name, but they are different.
Mike. J. Thompson
Bartender
Posts: 689
17
posted 6 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
And just to add about warnings in general. The compiler does sometimes warn you about things that aren't actually a problem. In these situations you can suppress the warning with an annotation.
However you need to fully understand why the compiler is warning you about something before you can know if it is a problem or not. If you don't know whether something is a problem or not then it needs investigating
The moustache of a titan! The ad of a flea:
the value of filler advertising in 2021
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
pass four parameters to a method and return a value
Calculating the distance between two points problem
Distance between points
Java program method to calculate distance.
Aggregating class
More... | https://coderanch.com/t/656153/java/programming-practices-warnings | CC-MAIN-2022-40 | refinedweb | 875 | 63.8 |
Prefetching in create-react-app with Quicklink
This codelab uses Chrome DevTools. Download Chrome if you don't already have it.
This codelab shows you how to implement the Quicklink library in a React SPA demo to demonstrate how prefetching speeds up subsequent navigations.
Measure
Before adding optimizations, it's always a good idea to first analyze the current state of the application.
- Click Remix to Edit to make the project editable.
- To preview the site, press View App. Then press Fullscreen
.
The website is a simple demo built with create-react-app.
Complete the following instructions in the new tab that just opened:
Control+Shift+J(or
Command+Option+Jon Mac) to open DevTools.
- Click the Network tab.
- Select the Disable cache checkbox.
- In the Throttling drop-down list, select Fast 3G to simulate a slow connection type.
- Reload the app.
- Type
chunkinto the Filter textbox to hide any resources that do not include
chunkin their name.
The site uses route-based code splitting, thanks to which only the necessary code is requested at the beginning.
- Clear the network requests in DevTools.
- Within the app, click the Blog link to navigate to that page.
The JS and CSS chunks for the new route are loaded to render the page.
Next, you'll implement Quicklink in this site, so that these chunks can be prefetched in the home page, making the navigation faster.
This allows you to combine the best of both techniques:
- Route-based code splitting tells the browser to only load the necessary chunks at a higher priority at page load time.
- Prefetching tells the browser to load the chunks for in-viewport links at the lowest priority, during the browser's idle time.
Configure
webpack-route-manifest
The first step is to install and configure webpack-route-manifest, a webpack plugin that lets you generate a manifest file associating routes with their corresponding chunks.
Usually, you would need to install the library, but we've already done it for you. Here's the command that you would need to run:
npm install webpack-route-manifest --save-dev
config-overrides.js is a file placed in your project root directory where you can override existing behaviour of the webpack configuration, without having to eject the project.
- To view the source, press View Source.
Open
config-overrides.js for edit and add the
webpack-route-manifest dependency at the beginning of the file:
const path = require('path');
Next, configure the
webpack-route-manifest plugin by adding the following
code to the bottom of
config-overrides.js:
module.exports = function override(config) {
config.resolve = {
...config.resolve,
alias: {
'@assets': `${path.resolve(__dirname, 'src/assets')}`,
'@pages': `${path.resolve(__dirname, 'src/pages')}`,
'@components': `${path.resolve(__dirname, 'src/components')}`,
},
};
config.plugins.push(
new RouteManifest({
minify: true,
filename: 'rmanifest.json',
routes(str) {
let out = str.replace('@pages', '').toLowerCase();
if (out === '/article') return '/blog/:title';
if (out === '/home') return '/';
return out;
},
}),
);
return config;
};
The new code does the following:
config.resolvedeclares variables with the internal routes to pages, assets and components.
config.plugins.push()creates a
RouteManifestobject and passes it the configuration so that the
rmanifest.jsonfile can be generated based on the site's routes and chunks.
The
manifest.json file will be generated and made available at.
Configure quicklink
At this point you would need to install the Quicklink library in your project. For simplicity, we already added it to the project. Here's the command that you would need to run:
npm install --save quicklink
Open
src/components/App/index.js for edit.
First, import the Quicklink higher order component (HOC):
import React, { lazy, Suspense } from 'react';
import { Route } from 'react-router-dom';
import Footer from '@components/Footer';
import Hero from '@components/Hero';
import style from './index.module.css';
const Home = lazy(() => import(/* webpackChunkName: "home" */ '@pages/Home'));
const About = lazy(() => import(/* webpackChunkName: "about" */ '@pages/About'));
const Article = lazy(() => import(/* webpackChunkName: "article" */ '@pages/Article'));
const Blog = lazy(() => import(/* webpackChunkName: "blog" */ '@pages/Blog'));
Next, create an
options object after the
Blog variable declaration, to use as an argument when calling
quicklink:
Finally, wrap each route with the
withQuicklink() higher order component, passing it an
options parameter and the target component for that route:
const App = () => (
<div className={style.app}>
<Hero />
<main className={style.wrapper}>
<Suspense fallback={<div>Loading...</div>}>
</Suspense>
</main>
<Footer />
</div>
);
The previous code instructs to prefetch chunks for the routes wrapped with
withQuicklink(), when the link comes into the view.
If Glitch throws an error at this point about the lack of a dependency,
try opening the Glitch Terminal (Tools > Terminal), running
refresh in the Terminal, then running
npm run build.
Measure again
Repeat the first 6 steps from Measure. Don't navigate to the blog page yet.
When the home page loads the chunks for that route are loaded. After that, Quicklink prefetches the route's chunks for the in-viewport links:
These chunks are requested at the lowest priority and without blocking the page.
- Clear the Network log again.
- Disable the Disable cache checkbox.
- Click the Blog link to navigate to that page.
The Size column indicates that these chunks were retrieved from the "prefetch cache", instead of the network. Loading these chunks without a Quicklink took approximately 580ms. Using the library it now takes 2ms, which represents a 99% reduction! | https://web.dev/en/codelab-quicklink/ | CC-MAIN-2020-29 | refinedweb | 881 | 57.87 |
Hello everyone! I hope someone can help me. I'm not very good with programming, so please bear with me, because I'm sure this is very simple for better programmers. But I digress. I am trying to write a C++ program to calculate your "ideal body weight".
Here is the question/story:
A simple rule to estimate your ideal body weight is to allow 110 pounds for the first 5 feet of height and 5 pounds for each additional inch. Write a program with a variable for the height of a person in feet and another variable for the additional inches and input values for these variables from the keyboard..
And here is the code I have so far!
I'm not very good with math, so that is where I am having the most trouble!I'm not very good with math, so that is where I am having the most trouble!Code:#include <iostream> using namespace std; int main( ) { int feet; int inches; int ideal; cout << "Please enter how many feet tall you are: "; cin >> feet; cout << "Please enter the additional inches of your height: "; cin >> inches; //math equation cout << "Your ideal body weight is" return 0; }
Thank you, for any help/feedback!
Kyle | https://cboard.cprogramming.com/cplusplus-programming/150425-calculating-body-weight.html | CC-MAIN-2017-30 | refinedweb | 207 | 76.76 |
Configure an MRSS feed (such as iTunes) with Fire App Builder
If you have an iTunes MRSS feed, which follows a formal specification used for services such as iTunes, you can follow an example configuration to simplify the setup. The sample MRSS feed in Fire App Builder uses a feed for a This Week in Tech (TWIT) podcast called Ham Nation, whose feed is publicly available here.
- MRSS Configuration Overview
- Demo: Configure Fire App Builder with the TWIT Feed
- Configure Fire App Builder with Your Own MRSS Feed
MRSS Configuration Overview
If your feed contains the same elements as the example iTunes feed, your setup can be as simple as swapping in your own feed URL and using the existing TWIT category and content recipes.
However, iTunes MRSS feeds have a variety of potential elements. In the sample TWIT feed, the content elements in the feed are matched through an XPath query with the
query and
matchList parameters in the categories recipe contents recipe. You might need to adjust some of this query syntax if your MRSS feed differs from the sample TwitTV MRSS feed. More details are provided in the steps that follow.
urlin your feed element cannot point to a source on YouTube, Vimeo, or Dropbox. Your videos need to be on a host that allows your app to access the media directly. Additionally, your app must match on all of the elements listed in the previous code sample. For example, you cannot omit one of the elements (such as the
url). Otherwise your build will fail.
Demo: Configure Fire App Builder with the TWIT Feed
Before swapping in your own MRSS feed into the sample TWIT configuration, let's build Fire App Builder using the TWIT feed to get a sense of how it looks and works. To configure Fire App Builder to use the TWIT feed:
Open BasicFileBasedUrlGeneratorConfig.json (in your app's assets > configurations folder). Change the value for the
url_fileproperty to
twitTvUrlFile.json:
{ "url_file": "twitTvUrlFile.json" }
Press Shift twice to open the Search Everywhere dialog box, and type Navigator.java to locate this file. Change the NAVIGATOR_FILE field's value to
Navigator_TwitTv.json:
public static final String NAVIGATOR_FILE = "Navigator_TwitTv.json";
This tells Fire App Builder to use this particular navigator file rather than the default (Navigator.json).
Click the Run App button
. (If you need help running your app on a Fire TV device, see Connect to Fire TV Through ADB.)
The TWIT feed populates in Fire App Builder and looks somewhat as follows:
Configure Fire App Builder with Your Own MRSS Feed
To configure Fire App Builder with your own MRSS feed, essentially you just swap it in place of the TWIT feed and make sure the same elements match in your recipes. You can also rename some files so they reflect your own feed rather than saying "Twit."
Before configuring your app, make sure your iTunes MRSS actually validates. Go to Cast Feed Validator and ensure your feed is valid. Beyond validating, your feed must also have the following elements to satisfy Fire App Builder's minimum requirements:
title
guid
itunes:subtitle
media:content url
media:thumbnail url
You can see the sample TWIT feed as an example for these elements in context. These elements will map to the
mTitle,
mId,
mDescription,
mUrl,
mCardImageUrl, and
mBackgroundImageUrlmodel elements in the Fire TV UI. If your valid iTunes feed doesn't have these elements, you can later adjust the category recipe and contents recipe to target similar elements. More detail is provided in the steps that follow.
Duplicate the twitTvUrlFile.json file (in your app's assets folder) and give the copy a unique name, such as AcmeUrlFile.json.Tip: To duplicate a file, you can either right-click the file name and choose Refactor > Copy, or just highlight the file and use Cmd + C to copy and Cmd + V to paste (on Windows, Ctrl instead of Cmd).
Open your "AcmeUrlFile.json" file and replace the URL with your own iTunes MRSS feed URL:
{ "urls": [ "" ] }
Open BasicFileBasedUrlGeneratorConfig.json (in your app's assets > configurations folder). Change the value for the
url_fileto the name of the file you created in the previous step (e.g., "AcmeUrlFile.json").
{ "url_file": "AcmeUrlFile.json" }
Press Shift twice to open the Search Everywhere dialog box, and type Navigator.java to locate this file. Change the NAVIGATOR_FILE field's value to a unique name, such as
Navigator_acmemedia.json:
public static final String NAVIGATOR_FILE = "Navigator_acmemedia.json";
This tells Fire App Builder to use this particular Navigator file rather than the default (Navigator.json).
Duplicate the Navigator.json file (located in app > assets) and give the new file the same name you used in the previous step (e.g., Navigator_acmemedia.json).
Open the Navigator_acmemedia.json file (or whatever you named it in the previous step). The default
globalRecipescode has a special hard-coded category with content processed by a different recipe. This section is highlighted in red below. Remove this section.
": { "name": "Hardcoded Category Name" }, "contents": { "dataLoader": "recipes/LightCastDataLoaderRecipe1.json", "dynamicParser": "recipes/LightCastAllContentsRecipe.json" } } ]
Your
globalRecipesobject should look as follows:
"globalRecipes": [ { "categories": { "dataLoader": "recipes/TwitTvDataLoaderRecipe0.json", "dynamicParser": "recipes/TwitTvCategoriesRecipe.json" }, "contents": { "dataLoader": "recipes/TwitTvDataLoaderRecipe0.json", "dynamicParser": "recipes/TwitTvContentsRecipe.json" } } ]
In the same Navigator_acmemedia.json file, change the "TwitTv" names in the following files to reflect your own project's name:
- TwitTvDataLoaderRecipe0.json
- TwitTvCategoriesRecipe.json
- TwitTvContentsRecipe.json
For example, if your app were named AcmeMedia, you might rename these JSON files as follows:
"globalRecipes": [ { "categories": { "dataLoader": "recipes/AcmeMediaDataLoaderRecipe0.json", "dynamicParser": "recipes/AcmeMediaCategoriesRecipe.json" }, "contents": { "dataLoader": "recipes/AcmeMediaDataLoaderRecipe0.json", "dynamicParser": "recipes/AcmeMediaContentsRecipe.json" } } ]
- Now, in the Android Studio left pane that lists the files, either duplicate or rename the TwitTvDataLoaderRecipe0.json, TwitTvContentsRecipe.json, and TwitTvCategoriesRecipe.json files (located in app > assets > recipes) to match the names you customized in the previous step.
- Open the AcmeMediaCategoriesRecipe.json file (or whatever you renamed it) and make sure that the query targeting the categories will work for your feed:
- Go to the XPath Tester.
- Paste in your XML feed into the XML Input box. Be sure to remove the text at the top that says "This XML file does not appear to have any style information …." Also, escape any
&characters (which are illegal in XML) by changing them to
&.
- In your AcmeMediaCategoriesRecipe.json file, copy the
queryvalue (
//item/category/text()) into the XPath Expression field in the XPath Tester. (Don't include the quotation marks.)
Click Test XPATH. If you see a result such as what's shown in the following code sample, you're all set because the
querycorrectly identifies the categories in your feed.
Text='Technology' Text='Ham Radio' Text='Technology' Text='Ham Radio' Text='Technology' Text='Ham Radio'
If the query doesn't correctly select your categories, you'll need to adjust your query syntax to select your feed.Targeting Elements with Namespaces
If you're trying to target an element with a namespace, such as
<media:category>, you can't simply update the query syntax to
//item/media:category/text(). This is because Fire App Builder's XML Parser doesn't support namespaces directly in the XPath expressions. Instead, you would use
//*[name()='media:category']/text(). For more details, see the "Targeting Elements with Namespaces" section in the XML tab in Step 7: Contents Recipe: Query Parameters.
For more details on creating XPath queries in general, see Step 4: Categories Recipe: Query Parameters. For more on XPath query syntax, see XPath Syntax or other online resources.
- Open the AcmeMediaContentsRecipe.json file (or whatever you named this file) and make sure that the query syntax targeting the contents will work for your feed:
- From the previous step, your feed should already be in XPath Tester.
- In your AcmeMediaContentRecipe.json file, copy the
queryvalue (
//item[./category='$$par0$$']) into the XPath Expression field in the XPath Tester. (Don't include the quotation marks.)
- Because XPath won't understand the
$$par0$$variable (which is specific to Fire App Builder and not standard XPath syntax), substitute in one of your category names instead. For example,
//item[./category='Lifestyle'].
Click Test XPATH. If you see a result containing your items such what's shown in the following code sample, you're all set because the
querysyntax correctly identifies the contents in your feed's items.
Element='<item> <title>HN 361: Tonight: Hams Young and Old</title> <itunes:title xmlns:Tonight: Hams Young and Old</itunes:title> <itunes:episodeType xmlns:full</itunes:episodeType> <pubDate>Wed, 01 Aug 2018 21:36:19 PDT</pubDate> <itunes:episode xmlns:361</itunes:episode> <link></link> <comments></comments> <itunes:author xmlns:TWiT</itunes:author> <category>Technology</category> <category>Ham Radio</category> <itunes:explicit xmlns:clean</itunes:explicit> <itunes:subtitle xmlns: Don Wilbanks interviews 2018 Young Ham of the Year Bryant Rascoll KG5HVO. </itunes:subtitle> <itunes:keywords xmlns: Ham Radio, arrl, young ham of the year, ham holiday </itunes:keywords> <description> ...
If the query doesn't correctly select your categories, you'll need to adjust the query recipe to match your feed. See Step 7: Contents Recipe: Query Parameters for details.
Now look at the AcmeMediaContentsRecipe.json file (or whatever you named this file) again and examine the
matchListparameter. By default, the
matchListparameter looks like this:
"matchList": [ "title/#text@mTitle", "guid/#text@mId", "itunes:subtitle/#text@mDescription", "media:content/#attributes/url@mUrl", "media:content/media:thumbnail/#attributes/url@mCardImageUrl", "media:content/media:thumbnail/#attributes/url@mBackgroundImageUrl" ]
The syntax in the
matchListparameter doesn't use XPath expressions, but it's similar. Here's how this
matchListsyntax works.
matchListstarts with the result returned from the
queryparameter — in this case, the items in your feed. Thus, you don't need to use XPath syntax to target your items.
On the left of the ampersand (
@) you put the property you want to target (for example,
title). On the right of the ampersand (
@), you put the Fire App Builder model element you want to map the element to (for example,
mTitle).Special Notes about Mapping Syntax with the matchList Parameter
Note that the syntax in this
matchListparameter uses some special techniques for targeting text, attributes, and CDATA elements:
— To capture text inside an element, use
#text. (See "Targeting Text" on the XML tab on Step 8: Contents Recipe: Matchlist Parameters for more info.)
— To capture attributes specified in an element, use
#attributes. (See "Targeting Text" on the XML tab on Step 8: Contents Recipe: Matchlist Parameters for more info.)
— To capture text inside a
CDATAelement, use
#cdata-section. (See "Targeting Text" on the XML tab on Step 8: Contents Recipe: Matchlist Parameters for more info.)
— More details about these special selectors and other matching requirements are provided in Step 8: Contents Recipe: Matchlist Parameters.</li></ul>
Make sure that all the elements on the left of the
@appear in your feed's items (specifically, in the result returned from your Contents recipe query —
//item[./category='Lifestyle']). You should have at least the following elements in your items:
title,
guid,
itunes:subtitle,
media:contentwith
urlattribute, and
media:content/media:thumbnailwith
urlattribute. If these items don't exist or are named differently, fix the mapping here before going to the next step.Important: As noted earlier, the
urlin your feed element cannot point to a source on YouTube, Vimeo, or Dropbox. Your videos need to be on a host that allows your app to access the media directly, using a file extension (e.g., .mp4) and not requiring special authentication.
- Click the Run App button
. (If you need help running your app on a Fire TV device, see Connect to Fire TV Through ADB.)
If successful, your app should look similar to the sample TWIT Ham Nation app but with your own feed's content. The feed items are grouped into different categories based on the
category element in your feed. If the same item has multiple categories, that item will appear in each category group.
If you get a "Service Unavailable" message, Fire App Builder probably had trouble parsing your feed and mapping it to the UI. Check to see that all elements targeted in your category recipe and contents recipe are present in your feed. You might need to adjust the syntax a bit to target the right elements.
To identify the error, expand the Logcat tab at the bottom of Android Studio and filter on "Error." Look for a reason for the failure in the messages (such as "The provided query string is not valid for the given xml.")
For information on how to change the look and feel of the app, including how to change the logo, see Change the App Logo, Icon, and Splash Screen. | https://developer.amazon.com/it/docs/fire-app-builder/configure-mrss-feed.html | CC-MAIN-2021-17 | refinedweb | 2,096 | 56.45 |
table of contents
NAME¶cfg_t - Data structure holding information about a 'section'.
SYNOPSIS¶
#include <confuse.h>
Data Fields¶
cfg_flag_t flags
Any flags passed to cfg_init() char * name
The name of this section, the root section returned from cfg_init() is always named 'root'. cfg_opt_t * opts
Array of options. char * title
Optional title for this section, only set if CFGF_TITLE flag is set. char * filename
Name of the file being parsed. int line
Line number in the config file. cfg_errfunc_t errfunc
This function (if set with cfg_set_error_function) is called for any error message. cfg_searchpath_t * path
Linked list of directories to search.
Detailed Description¶Data structure holding information about a 'section'.
Sections can be nested. A section has a list of options (strings, numbers, booleans or other sections) grouped together.
Examples:
ftpconf.c, reread.c, and simple.c. | https://manpages.debian.org/testing/libconfuse-dev/cfg_t.3.en.html | CC-MAIN-2020-10 | refinedweb | 135 | 61.43 |
Python is said to be a pure object oriented programming language and almost everything you come across in Python is an object. A class can be defined as a user-defined type that, by having its own methods (functions) and property (variables), define what object will look like. An object is a single instance of a class. You can create many objects from the same class type.
Creating a class in Python
class keyword is used in Python to create a class, an example is shown below. We create a class named Books with a property named total_count:
class Books:
total_count = 5
Creating an object
class is just a blueprint. In order to use the class, we need to create an object. In below example, lets create an object called learn_python and using this we will print the value of total_count:
class Books:
total_count = 5
python_book = Books()
print(python_book.total_count)
The init() Function
Let’s look at an important member of the class. We are talking about init() function. Infact all classes have this function, which is always called an object of the class in being created. This function is called automatically so you dont have to specifically call this. We use the init() function to initialize values or properties that needs to be assigned to the object immediately when created. In the below example, we create a class Books and using the init() function, we have automatically assigning title and the cost to the object:
class Books:
def __init__(self, title, cost):
self.title = title
self.cost = cost
python_book = Books("Learn and Practice Python Programming", 136)
print(python_book.title)
print(python_book.cost)
Object Functions
A class will also have object functions or methods. Functions that are defined in objects, belong to object (and not to the class). It means that the objects will use these functions and the result returned will be specific to the objects. These are characterised by self keyword as first parameter being passed. Let’s add a function to our class Books which will print the title of the book. This is called object function because it knows which objects are referencing and the title value is linked to that object only.
Example:
class Books:
def __init__(self, title, cost):
self.title = title
self.cost = cost
def gettitle(self):
print("Title of the book is: "+self.title)
python_book = Books("Learn and Practice Python Programming", 136)
print(python_book.title)
print(python_book.cost)
python_book.gettitle()
The self parameter used in object functions is to show the reference to the current object associated to the class.
Please note, it does not have to be named self, we can use any name we like it but whatever name we choose, that has to be the first parameter of the object functions.
We will end our discussion here. We will develop a mini application using classes in next article. | https://callswapnil.medium.com/how-classes-and-objects-are-used-in-python-947b1c756979?source=post_internal_links---------1---------------------------- | CC-MAIN-2022-27 | refinedweb | 479 | 64.61 |
Hi there pythonistas. Today i am not going to write a lengthy tutorial about how to make your programs compatible with python 2 and 3 at the same time, but i am going to share a simple tip with you guys which will help you achieve this target. Just imagine that you have a very popular python module which is use by hundreds of people but not all of them have python 2 or 3. In that case you have two choices. The first one is to distribute 2 modules. One for python 2 and the other for python 3 and the other choice is to modify your current code so that it can be used with both python 2 and 3. I am going to talk about the second choice. First tell me how you import packages in your script ? Most of us do this :
import foo # or from foo import bar
Do you know that you can do something like this as well?
import foo as foo
I know it’s function is the same
Did you find something noteworthy in the above code ? So let me explain the above code a little. We are wrapping our importing code in a try except clause. Why are we doing that ? We are doing it because in python2 there is no urllib.request module and will result in an ImportError. The functionality of urllib.request is provided by urllib2 module in python2. So now when python2 try to import urllib.request and get an import error we tell it to import urllib2 instead. The final thing you need to know about is the
as keyword. It is mapping the imported module to urllib_request. So that now all of the Classes and methods of urllib2 are available to us by urllib_request.
So how did this help us in targeting python 2 and 3 at the same time ? Okay here is the trick. Once you have got a library that works in python 2 but is not available in python 3 then you have to find out it’s alternative in python 3 (most libraries have their alternatives for python 3 but some don’t). I know it’s trivial and that is why a lot of modules have still not been ported to python 3. After that you have to wrap your module importing code in a try-except clause with a common variable following the
as keyword. After that use the imported module. Here is a complete example which should work both in python 2 and 3:
try: import urllib.request as compat_urllib_request except ImportError: # Python 2 import urllib2 as compat_urllib_request html = compat_urllib_request.urlopen("") print html.headers['content-type'] 'text/html; charset=ISO-8859-1'
Another example which involves the json library:
try: import json except ImportError: import simplejson as json
I hope you liked today’s post. Stay tuned for the next one. If you have any suggestions then do post them in the comments below.
5 thoughts on “Targeting python 2 and 3 at the same time.”
Pingback: Making a url shortener in python | Bite Sized Python Tips
Pingback: *args and **kwargs in python explained | Bite Sized Python Tips
Pingback: Storing and Loading Data with JSON | Bite Sized Python Tips
Thank you and cool idea. 🙂
More of the serie please. I try to get fit with both Python versions. | https://pythontips.com/2013/07/30/make-your-programs-compatible-with-python-2-and-3-at-the-same-time/ | CC-MAIN-2017-22 | refinedweb | 561 | 82.34 |
11598
Summary:
Waiting on a SemaphoreSlim that was initialized with an initialCount of 0 and has not yet been released will use 100% CPU on one core.
Reproduction:
This example program will pause for 10 seconds with 100% CPU usage:
using System.Threading;
public static class Program
{
public static void Main(string[] args)
{
var sem = new SemaphoreSlim(0);
sem.Wait(10000);
}
}
Expected behaviour would be to pause for 10 seconds with negligible CPU usage.
This similar program will indeed pause for 10 seconds with negligible CPU usage:
public static class Program
{
public static void Main(string[] args)
{
var sem = new SemaphoreSlim(0);
sem.Release();
sem.Wait();
sem.Wait(10000);
}
}
I've observed this behaviour on Linux with Mono 2.8.10 and 3.0.1. I've observed it on OSX, but I'll need to check the Mono version number.
Analysis:
I believe this is a bug in SemaphoreSlim's constructor:
this.handle = new ManualResetEvent (initialCount == 0);
The event is initialized to be signalled if initialCount is 0 and not signalled if initialCount is greater than 0. This seems to be the wrong way round. If initialCount is 0 then a Wait cannot succeed and so the event should not be signalled. This means that the Wait spins furiously because every time it tries to block to wait for the event it finds that the event is signalled, but every time it checks to see if the semaphore's count is positive it finds that it isn't and decides to try to wait again.
After the semaphore has been released at least once, the event's state becomes consistent with the counter, so this only happens before the first release.
Fixed in
Can this be marked resolved? I think the fix is good, but it's still marked 'new'. | https://bugzilla.xamarin.com/11/11598/bug.html | CC-MAIN-2021-43 | refinedweb | 301 | 70.84 |
You left out the ~ character in your _FIELDNAME_START_CHAR production. That character tells
the grammar that it should take all the characters except the ones you specified (the complement).
Change:
| <#_FIELDNAME_START_CHAR: ( [ " ", "\t", "+", "-", "!", "(", ")", ":",
To:
| <#_FIELDNAME_START_CHAR: ( ~[ " ", "\t", "+", "-", "!", "(", ")", ":",
and it should probably work.
Eric
-----Original Message-----
From: Victor Hadianto [mailto:victorh@nuix.com.au]
Sent: Wednesday, July 09, 2003 4:53 AM
To: Lucene Users List
Subject: Re: '-' character not interpreted correctly in field names
Hi Erik and others,
I'm looking for a similar solution where I need QueryParser not to drop the
"-" characters from the field name. Hower outside the field I do want the -
I'm definitely not an expert in JavaCC and to be honest I only have a limited
idea about Erik's suggestion work,
Anyway I followed the suggestion and added the following:
| <#_WHITESPACE: ( " " | "\t" ) >
| <#_FIELDNAME_START_CHAR: ( [ " ", "\t", "+", "-", "!", "(", ")", ":",
| "^",
"[", "]", "\"", "{", "}", "~", "*", "?" ]
| <_ESCAPED_CHAR> ) >
| <#_FIELDNAME_CHAR: ( <_FIELDNAME_START_CHAR> | <_ESCAPED_CHAR> ) >
and again below I added:
| <TERM: <_TERM_START_CHAR> (<_TERM_CHAR>)* >
| <FIELDNAME: <_FIELDNAME_START_CHAR> (<_FIELDNAME_CHAR>)* >
And I changed:
LOOKAHEAD(2)
fieldToken=<TERM> <COLON> { field = fieldToken.image; }
to: ...
LOOKAHEAD(2)
fieldToken=<FIELDNAME> <COLON> { field = fieldToken.image; }
Well after doing all this mods all the query that involved field names cause
problem, for example if I searched for
fieldname:hello
The query is blank (yes blank, nothing in it)
and if the fieldname does contain a dash ("-") for example: field-name:hello
They query is: +field -name
hello is dropped.
Does anyone has any idea? Help and suggestions will be much appreciated. I
really need to get this dash working, changing the field name will be my last
resort which I won't explore until I really have to.
Thanks,
Victor
On Thu, 15 May 2003 04:54 am, Eric Isakson wrote:
> I think the query parser changes would not be too bad, I've outlined a
> couple of relavant lines you should look at so you don't have to try
> and comprehend the productions for the entire QueryParser. I do not
> think I would like to have to maintain one of those myself though.
> Your other unmentioned alternative is to choose field names that match
> the <TERM> production of QueryParser.jj without escapes.
>
> QueryParser.jj line 557:
> fieldToken=<TERM> <COLON> { field = fieldToken.image; }
>
> and earlier...
> <#_ESCAPED_CHAR: "\\" [ "\\", "+", "-", "!", "(", ")", ":", "^",
> "[", "]", "\"", "{", "}", "~", "*", "?" ] >
>
> | <#_TERM_START_CHAR: ( ~[ " ", "\t", "+", "-", "!", "(", ")", ":",
> | "^",
>
> "[", "]", "\"", "{", "}", "~", "*", "?" ]
>
> | <_ESCAPED_CHAR> ) >
> |
> | <#_TERM_CHAR: ( <_TERM_START_CHAR> | <_ESCAPED_CHAR> ) >
>
> ...
>
> <TERM: <_TERM_START_CHAR> (<_TERM_CHAR>)* >
>
> So the characters you need to avoid in your field names are the ones
> from _ESCAPED_CHAR, [ "\\", "+", "-", "!", "(", ")", ":", "^", "[",
> "]", "\"", "{", "}", "~", "*", "?" ]
>
> If you need to modify the parser, you will probably want to add a
> FIELDNAME token and other supporting productions that look really
> similar to these lines I've copied but modify the complement, ~[...],
> at the beginning of _FIELDNAME_START_CHAR (you would add this
> production) so it will match the "-" that you are using in your field
> names (and fix it to match any other characters you want to use in
> field names that it doesn't allow right now).
>
> Eric
>
> -----Original Message-----
> From: Jon Pipitone [mailto:jpipitone@mshri.on.ca]
> Sent: Wednesday, May 14, 2003 2:26 PM
> To: Lucene Users List
> Subject: Re: '-' character not interpreted correctly in field names
>
> Eric Isakson wrote:
> > I just looked at the QueryParser.jj code, your field names
> >
> > never get processed by the analyzer. It does look like the > query
> parser will honor escapes though. I haven't tried > this, but try a
> query like "foo\-bar:foo" and have
> >
> > a look at the QueryParser.jj file for how it handles field
> >
> > names when parsing your query.
>
> Hrm.. that's what I had found too. So, you're saying that, other than
> escaping dashes, I'd have to change QueryParser.. ?
>
> I'm not too familiar just yet with JavaCC syntax, so reading through
> QueryParser is a little tough going. Thanks Eric,
>
> jp
>
> > -----Original Message-----
> > From: Jon Pipitone [mailto:jpipitone@mshri.on.ca]
> > Sent: Monday, May 12, 2003 4:03 PM
> > To: Lucene Users List
> > Subject: Re: '-' character not interpreted correctly in field names
> >
> >
> > Hi Otis, Terry,
> >
> > >>>You can write a custom Analyzer that does not remove dashes from
> > >>>
> > >>>tokens, and use it for both indexing and searching. >>> >>>This
> >
> > is a frequent question and answer on this list.
> >
> > Sorry for the noise, but I haven't been able to find a solution in
> > the mailing list archives, or by writing my own analyzer:
> >
> > public class MyAnalyzer extends Analyzer {
> > public TokenStream tokenStream(String fieldName, Reader reader) {
> > return new CharTokenizer(reader) {
> > protected boolean isTokenChar(char c) {
> > return Character.isLetter(c) || c == '-';
> > }
> > };
> > }
> > }
> >
> > I parse a query like this:
> >
> > String queryString = "foo-bar:foo";
> > String queryResult =
> > QueryParser.parse(queryString, "body", new MyAnalyzer())
> >
> > With the output:
> > body:foo -bar:foo
> >
> > But I would expect the output:
> > foo-bar:foo
> >
> > If I print out the tokens that MyAnalyzer produces I do get
> > "foo-bar" and then "foo".
> >
> > Any pointers on what I'm doing wrong?
> >
> > jp
> >
> >>>>--- Jon Pipitone <jpipitone@mshri.on.ca> wrote:
> >>>>>Hi all,
> >>>>>
> >>>>>>I believe that the tokenizer treats a dash as a token
> >>>
> >>>separator.
> >>>
> >>>>>>Hence, the only way, as I recall, to eliminate this behavior
> >>>
> >>>is
> >>>
> >>>>>>to modify QueryParser.jj so it doesn't do this. However,
> >>>
> >>>doing
> >>>
> >>>>>>this can cause some other problems, like hyphenated words at
a
> >>>>>>line break and the like.
> >>>>>
> >>>>>I've recently started using lucene and I'm running into the same
> >>>>>issue with the query parser. I'd like to use queries that
> >>>>>contain
> >>>
> >>>dashes
> >>>
> >>>>>in
> >>>>>the field name, but as far as I can tell it seems that the
> >>>
> >>>current
> >>>
> >>>>>query
> >>>>>grammar treats field names as terms, and so, as Terry notes, a
> >>>
> >>>dash
> >>>
> >>>>>becomes a token seperator.
> >>>>>
> >>>>>Terry suggests modifying the QueryParser.jj -- I would suspect by
> >>>>>creating a seperate non-terminal for field names.
> >>>>>
> >>>>>Has anyone done any work on this already? Is modifying
> >>>>>QueryParser.jj the best approach?
> >>>>>
> >>>>>Thanks,
> >>>>>j | http://mail-archives.apache.org/mod_mbox/lucene-java-user/200307.mbox/%3C187D6D956106D84E9D8B280F6458FE14018D9B28@merc12.na.sas.com%3E | CC-MAIN-2016-18 | refinedweb | 943 | 62.98 |
Glu is really obsolete, Glu.Build2DMipmap is an exception?Posted Thursday, 11 February, 2010 - 10:14 by migueltk in
Hello, ...
As implemented "Glu.Build2DMipmap" without using Glu, I know how to do it. Does anyone know how to do it? ...
Programming using "OpenTK.dll is very easy but using both" OpenTK.Compatibility.dll "is a real problem, there are constantly name collisions.
OpenTK should be limited to the creation and support of the windows, mouse, keyboard, sound, and exclude the mathematical library. When you have your own mathematical library with the most common names "Vector3", "Matrix", there are constantly name collisions.
It is my opinion.
Regards, ...
Re: Glu is really obsolete, Glu.Build2DMipmap is an ...
Glu.Build2DMipmap is obsolete and has been obsolete for close to a decade:
Barring (bad, obsolete) tutorials, noone should be using Glu.Build2DMipmap nowadays.
You can avoid name collisions by being more frugal with namespace imports:
In retrospect, it was probably a mistake to move math structures to the OpenTK namespace. Oh well, live and learn, maybe this can be reevaluated for some future 2.0 release.
Re: Glu is really obsolete, Glu.Build2DMipmap is an ...
True "Glu.Build2DMipmap" is outdated and I had the solution in the book "OpenGL Superbible 2" Chapter 8, I've only had to replace the line
by the following code
thanks for your answer, every day you learn something new ...
Re: Glu is really obsolete, Glu.Build2DMipmap is an ...
Problem:
GL.GenerateMipmap();and
TextureParameterName.GenerateMipmapboth don't work on Ati Radeon X1400.
Only
Glu.Build2DMipmap()works. But with Glu method these lines don't work:
I use them to stop creating highest levels of mipmaps which would blend together different textures in texture atlas.
Probably the only solution is to create mipmaps manually. | http://www.opentk.com/node/1557 | CC-MAIN-2015-27 | refinedweb | 294 | 60.41 |
Flutter is a new mobile app SDK to help developers and designers build modern mobile apps for iOS and Android.
Flutter takes the approach of having a single code base for all platforms. Because flutter eschews OEM widgets[1], all of our visual elements and most of our implementation is written in Dart and magically compiled to native code for each platform.
Flutter's One Code Base to Rule Them All design makes it easy for us to quickly write apps that look good, have high performance, and do not have feature/bug fragmentation.
Flutter also uses event-driven, reactive style programming (among others) which makes me partial to it, as I spend my day job working in React.
If you'd like to learn more about flutter before jumping in to the tutorial, head over to the docs.
Getting Started
First things first, we need to install flutter. Head over to the official documentation for instructions on how to set up your development environment:
Once that is done, it's time to actually create our project.
We're going to build an Octal Clock for our app. For more information about how the Octal Clock works, you can read the README in the Pub:
Download
Visit the GitHub repository to clone the source. You'll want to do this because there are over 1100 lines of code in the final app (after all the parts), and we won't be going over every line of code, just the important ones.
This post uses the
step1 branch:
git clone git checkout step1
Create our project
This can be done using Android Studio 3.0+ but (as of this writing) there are some bugs with project creation, so we are going to use the command line flutter utilities. If you cloned the GitHub project, you can skip this step.
flutter create --org institute.flutter -i swift -a kotlin --description 'An Octal Clock implementation' octal_clock_app
Our five arguments do the following:
--orgsets the application prefix. On Android: appicationId and package. On iOS: PRODUCT_BUNDLE_IDENTIFIER.
-isets our iOS language to swift, because Objective-C is awful by comparison.
-asets our Android language to kotlin, because Java is awful by comparison.
--descriptionsets our package description in our
pubspec.yaml
octal_clock_appthe name of the application to create. The project is place in a folder by this same name.
Run it
We can now run the sample application that was created by this command. Start up an emulator or plug in your phone and
flutter run in your project's directory.
This can also be done in Android Studio by using the green play button.
Step 1
Update your local source checkout to the
step1 branch. We will go through all our structure and major changes.
Install Dependencies
We are going to use the Octal Clock Dart Package to do all of our time conversions between imperial time and octal time. As such, we need to add
octal_clock to our
pubspec.yaml file.
pubspec.yaml
dependencies: flutter: sdk: flutter octal_clock: "^0.0.2"
Now that we've declared them, we install them. From the project directory, run:
flutter packages get
And that's it, now we're ready to build our UI.
Creating our UI
All of our dart files are stored in the
lib directory. Our main entry point is
lib/main.dart. Currently, it has 4 things in it: the
main function and 3 widgets. It's not good to have everything in this same file, so we're going to break things up a bit.
We going to create a new folder to store all our application's Page widgets:
lib/src/pages. We need a page to display our clock, so create
lib/src/pages/clock_page.dart.
clock_page.dart
This page will need to do two things:
- Display the current octal time
- Update at least once a second so the time gets updated.
We need to import the
async package for our periodic updates, and our
octal_cock package for our time handling.
import 'dart:async'; import 'package:octal_clock/octal_clock.dart';
Next, we need to create our Widget and its State.
class ClockPage extends StatefulWidget { ClockPage({Key key}) : super(key: key); @override _ClockPageState createState() => new _ClockPageState(); } class _ClockPageState extends State<ClockPage> { // ...snip... @override Widget build(BuildContext context) { // ...snip... } }
Our widget doesn't do anything fancy because all the magic will happen in our state. We need state here to store our constantly mutating time information. Let's initialize our state variables and set up our timer.
class _ClockPageState extends State<ClockPage> { Timer _timer; // tracks our periodic updates OctalDateTime _time; // tracks our current octal time @override void initState() { super.initState(); // We start at the current time _time = new OctalDateTime.now(); // We want to update 4 times per second // so we can display millisecond values as well const duration = const Duration( milliseconds: OctalDuration.MILLISECONDS_PER_SECOND ~/ 4); // Our periodic timer for when to update our time _timer = new Timer.periodic(duration, _updateTime); } @override void dispose() { // Make sure to cancel the timer when we dispose the view _timer.cancel(); super.dispose(); } void _updateTime(Timer _) { // Update our state with the new time and force a redraw setState(() { _time = new OctalDateTime.now(); }); }
Now that we're keeping track of the time and updating it periodically, we just need to flesh out our build method:
@override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); // 0-padding for hours/minutes/seconds String twoDigits(int d) { if (d < 10) return '0$d'; return d.toString(); } // 0-padding for milliseconds String threeDigits(int d) { if (d < 10) return '00$d'; if (d < 100) return '0$d'; return d.toString(); } // Helper to make pretty time String formatTime(date) { return '${twoDigits(date.hour)}:${twoDigits(date.minute)}:${twoDigits( date.second)}.${threeDigits(date.millisecond)}'; } // Things we are going to display final String date = '${_time.year}-${_time.month}-${_time.day}'; final String time = formatTime(_time); return new Scaffold( appBar: new AppBar( leading: new Icon(Icons.watch_later), title: new Text('Octal Clock'), ), body: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text(date, style: themeData.textTheme.headline), new SizedBox(height: 10.0), // Padding new Text(time, style: themeData.textTheme.display1), ], ), ), ); }
The concept for the
twoDigits and
threeDigits methods above were shamelessly stolen
date_time.dart. Let's discuss our actual layout above.
return new Scaffold
This is our main material widget for the page. The
appBar looks like this (the "Slow Mode" text will disappear with a release build):
Our body is a centered
Column. Our column stretches the entire available height, and we center things vertically with our
mainAxisAlignment. We then put our formatted date and time into the app and we're done with the page!
Now we just need to tie this page into our main app.
main.dart
We don't want to use the example widgets, so go ahead and just delete
MyHomePage and
_MyHomePageState. We're also going to rename
MyApp to
OctalClockApp just for fun.
Now add the import for our clock_page at the top of the file:
import './src/pages/clock_page.dart';
Then we flesh out the
build method:
return new MaterialApp( title: 'Octal Clock', theme: new ThemeData( primarySwatch: Colors.blue, fontFamily: 'Fixed', ), home: new ClockPage(), );
And that's it! We define the
home property as our ClockPage and it gets built as a child of MaterialApp. We have our final app! A total of 105 lines of code and it works on both Android and iOS.
The true benefit of the Octal Clock isn't really apparent until we build an analog clock face for it. Head on over to Part 2 to check it out. | https://flutter.institute/creating-your-first-flutter-app/ | CC-MAIN-2019-18 | refinedweb | 1,269 | 65.42 |
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
int fstat(int fildes, struct stat *buf);
int lstat(const char *pathname, struct stat *buf);
int stat(const char *pathname, struct stat *buf);
int fstat64(int fildes, struct stat64 *buf);
int lstat64(const char *pathname, struct stat64 *buf);
int stat64(const char *pathname, struct stat64 *buf);
DESCRIPTION
The
The
The
The
PARAMETERS
- pathname
Points to a path name that names a file. The calling process must have at least search permissions on pathname.
- fildes
Is a file descriptor referring to a file for which status is returned.
- buf
Points to a stat or stat64 structure where status information about the file is to be placed.
RETURN VALUES
If successful, these functions return a value of zero. On failure, they return -1 and set errno to one of the following values:
- EACCES
The permissions that a mode specified are denied or search permission is denied on a component of the path name prefix.
- EBADF
fildes is not a valid open file descriptor.
- EFAULT
buf or pathname is an invalid pointer.
- EINTR
A signal interrupted the call.
- EINVAL
The file time returned by the system cannot be represented.
- ENAMETOOLONG
The length of the pathname parameter exceeds PATH_MAX or a path name component is longer than NAME_MAX.
- ENOENT
pathname points to an empty string or to the name of a file that does not exist.
- ENOTDIR
A component of the path name prefix is not a directory.
- EOVERFLOW
The file size, in bytes or the number of blocks allocated to the file, or the file serial number cannot be represented correctly in the structure pointed to by buf.
CONFORMANCE
MULTITHREAD SAFETY LEVEL
PORTING ISSUES
There are differences in how the NuTCRACKER Platform fills in the stat structure, compared to the referenced standard. Refer to the struct stat page, and to File Management in the Windows Concepts chapter of the MKS Toolkit UNIX to Windows Porting Guide.
AVAILABILITY
MKS Toolkit for Professional Developers
MKS Toolkit for Enterprise Developers
MKS Toolkit for Enterprise Developers 64-Bit Edition
SEE ALSO
- Functions:
_NutFastStat(), chmod(), chown(), creat(), link(), open(), read(), readlink(), symlink(), unlink(), utime(), write()
- Miscellaneous:
- lf64, struct stat
MKS Toolkit 9.2 Documentation Build 16. | http://www.mkssoftware.com/docs/man3/stat.3.asp | crawl-001 | refinedweb | 367 | 61.87 |
This action might not be possible to undo. Are you sure you want to continue?
Is More Than Just A Seven Letter Word
a book by Veronica: of the Chapman family forum.FMOTL.com
as in
FreeMan-On-The-Land
First Edition: September 2009
T
his book is all about freedom. I think it will surprise you how much you actually do not know about that subject. And how very little, in essence, you really need to know in order to attain it. I. After having read the Chapters on Taking and Money, you may be wondering why you paid a price for a copy of this book. The answer is pretty obvious. The Monetary Belief System is still 'king', however much one would wish it away. Suffice to say, the majority of that price was the production, printing and any postage costs. As the Author, my royalty has been reduced to the barest minimum, in order to keep down the overall cost. Consequently, in that respect, it forms a labour of love on my part. What is worth more than all the gold in the world is your appreciation that, having read this book, you have become empowered in the way you always should have been - had you been educated, rather than indoctrinated - during your childhood. I apologise, up front, for the use of word-stressing in the text of this book. I'm compelled to do that in order to attempt to overcome the ingrained indoctrination to which we have all been subject throughout our lives. And the lives of our ancestors living or now deceased. I only have 'the printed word' (in its various forms) at my disposal. Please also note that, if you wish, you may quote any part of this book under one restriction only: That you quote exactly as is and within context ... because I cannot be held responsible if you should misquote me. One final thing. Please don’t worry about the grammar or
3
Freedom Is More Than Just A Seven-Letter Word the style. It’s written exactly the way the Author wanted it written. I know that, because I’m that Author. Veronica: of the Chapman family, September 2009, Feltham, UK.
4
I dedicate this book to everyone in the Freedom Movement, without whom (and without whose support) writing it would not have been possible. You are heroes. You are heroines. And you know who you are. “Reason is the life of the law; nay, the common law itself is nothing else but reason. The law which is perfection of reason” Sir Edward Coke, Lord Chief Justice of England 1552-1634. “Corruption is not the problem. It’s the acceptance of corruption that’s problem” Patrick Rattigan ND. “I just say what I say because everyone is entitled to my opinion” Saffire: of the Elder family (aged 7). I write this book for Yana, and Saffire, and all the little ones like
5
Freedom Is More Than Just A Seven-Letter Word
them. And I thank Yana’s mother for the cover design.
6
7
Freedom Is More Than Just A Seven-Letter Word
Contents
Foreword Chapter 1: Taking Chapter 2: Money Chapter 3: Legalese Chapter 4: Religion Chapter 5: Global Elite/Psychopaths Chapter 6: Promises & Contracts Chapter 7: Honour, Dishonour & Noticing Chapter 8: Societies & Statutes 10 13 16 29 35 38 46 52 55
Chapter 9: Common Law, The Law-of-the-Land 60 Chapter 10: Notices, Invitations & Summonses 64 Chapter 11: Legal Fiction Person Chapter 12: Solicitors, Lawyers & Notaries 66 70
Chapter 13: Veronica's Very Cunning 2-Step Plan for Freedom 73 Chapter 14: The Principles of the Application of Common Law 76 Chapter 15: Fundamental Established Axioms Chapter 16: Signatures Chapter 17: Courts & Proceedings 78 87 88
Chapter 18: Liability & The Ultimate Sanctions 102
8
Chapter 19: The Law-of-Waters Chapter 20: Names Chapter 21: Orders Chapter 22: Laws, Regulations, Guidelines & Sovereignty Chapter 23: The Hive Mind Chapter 24: Without Prejudice
105 111 114 115 119 121
Chapter 25: Mass Mind Control & Enslavement 123 Epilogue Appendix A: Templates & Usage Disclaimer 134 137
Appendix B: Freedom of Information interactions with HM Treasury 151 Appendix C: Magna Carta 1215 182
Appendix D: Notice of Understanding and Intent and Claim of Right 199 Appendix E: Summary of Freeman Principles 220
9
Freedom Is More Than Just A Seven-Letter Word
Foreword
I
am not a Solicitor. I am not a Lawyer. I am not an Accountant. I am not an Economist. I am not, in any way 'legally-trained', nor am I qualified to pontificate on 'monetary or economic policy'. It is hoped that, if you read this book all the way through, you will be very glad I am none of those things. So, what are my qualifications? Well, I have some academic ones (in engineering), but they are not directly relevant to the fundamental messages contained in these pages. They do provide me with a background in 'working things out', but that’s all. My fundamental qualification for writing this book, my primary one, is that I am a Human Being. Blessed with a living soul. Just like you. And that’s the only qualification I need for writing this book, and the only qualification you need for reading it. And, I hope, for understanding it. I believe I have Common Sense. I believe you do, as well. I believe that’s all that’s actually necessary. I believe that, by simply tapping into your Common Sense, we will end up in complete agreement. I certainly hope so. Everything stated in this book is either based on my own personal experiences, or on the experiences of people I know and trust. And it’s all based on Common Sense anyway. It really is just the practical application of Common Sense, as you will see. So where do we start? Well, first of all I’d like to quote Mahatma Gandhi when he said: “There is no path to peace … peace IS the path”. Is it, therefore, OK if I say: “There is no path to freedom … freedom IS the path”? I reckon it’s OK to say that. Because it’s true. Whoa! What does that mean? Well it means that to be free - you have to be free. And nothing else will do.
10
Foreword I have devised a Very Cunning 2-Step Plan to achieve freedom. I expand on this in more detail, in a Chapter all of its own. But, fundamentally, the two steps are: 1. You are free because you say you are free. Because no-one else will say it for you. 2. The second step is to make sure everyone you encounter recognises Step One. It sounds easy, but obviously it isn’t. In fact even Step One is extremely hard because it takes a constant effort to hold the line. This line has to be held 24/7. For example, most people in the British Isles, will say: “Of course I’m free! I live in a democracy, don’t I? I have freedom of speech, don’t I?” Well, the straight answers to that are: “No”, “No” and: “No”. I’ll add one more quotation, from 18th/19th century philosopher Johann Wolfgang von Goethe: “Those most hopelessly enslaved are those who falsely believe they are free”. And that’s the nub. Or maybe you could say, the rub. Is one’s belief in one’s freedom false or true? Is one really free, or hopelessly enslaved? There’s a pretty simple test. Do you think something… something that happens (or has happened) to you, is (or was) unfair? And you can’t see how to put it right? It doesn’t matter what it is … but: “Did it happen to you, was it unfair, and was there very little you could do about it”? If the answer to that question is: “Yes”, then you are hopelessly enslaved. Hey! Don’t worry! Plenty of that has happened to me! However, by the time you’ve read this book, I hope you will be in the position of knowing 'how to put it right'. (Not necessarily how you can right wrongs done to you in the past, but how to prevent wrongs happening to you & your loved ones in the future). Because, generally speaking, we all understand the difference between right and wrong. We are built that way. It’s called Common Sense. We just feel it, more
11
Freedom Is More Than Just A Seven-Letter Word often than not. But, just because we are only feeling it, doesn’t mean that we can, or should, ignore such feelings. Because within them lies the truth. Listen: I’m anxious to get on with what I plan to say. And I’m sure you feel the same way. All fired up and raring to go! So, having laid just a little bit of groundwork, let’s quickly move on to the first Chapter. How does that sound? OK, well just a couple of final things before we can do that, because I just need to say, in order to fully comprehend the purpose behind this book, the Reader needs to be familiar with the works of other writers, such as David Icke, Jordan Maxwell, (the late, great) William Cooper, Eustace Mullins and G. Edward Griffin etc. If you are not, then I suggest you make up for it as soon as you possibly can. Nevertheless it is assumed that you know, deep down in your soul, that: “Something is wrong with the set-up” into which you were born. Writers such as David & Jordan & others explain what those 'somethings' are in very great detail. And, if you know what those 'somethings' are, then you’ll fully understand why I’m writing this book. However, if you don’t know what those 'somethings' are, then we will just have to soldier on as best we can. Regardless. And simply rely on your 'basic, gut, feelings'. (I think it will all work out in the end). Perhaps the very first thing to do is to start at the beginning (always a good place, I’ve discovered!). It will probably be a little bit of a surprise, but the first thing I do is to analyse the word: “Take” (including its derivatives). And the reason for that, as you will see, is that it all starts from there.
12
Taking
Chapter 1: Taking
H
uh? Just 'taking' is wrong, isn’t it? Taking is 'greedy', isn’t it? People are wrong to just take! Scroungers, tax dodgers … the lot of ‘em! I can’t stand people who think it is OK to just take! What right do they think they have to do that? Fair’s fair! And just taking isn’t fair! I worked hard for what I have! Errr … 'scuse me. Just a moment. Can I interrupt, just one moment? Please? Pretty please? Thanks. What was the first thing you did when you were born? Most people will say: “I screamed my head off, so my mother said!” Well, no way, I’m afraid. Before you could scream you must have taken a breath. And, what’s more, you continue to take breaths throughout your entire life. Does the atmosphere ever send you a bill? Such that you pay it - for all the breaths you take? It would be a bit of a nuisance if it did that, wouldn’t it? Do you drink water? Where does it come from? Do you expect to pay back the sky, for all the rainfall you took – and drank? Where does the light & heat come from? Do you expect the Sun to be paid back for all the light and heat you took from it, throughout your life? Do you expect an invoice, from the Sun, to land on your doormat one fine day? Where do you get your minerals from? Oh! The Earth! Yes, of course! Does The Earth send out invoices, asking for payment for all the minerals taken from it (in your name)? Well, no. People and Companies send invoices, but the atmosphere, the Sun & the Earth don’t bother doing such an absurd thing.
13
Freedom Is More Than Just A Seven-Letter Word We take everything. We have to. There is no other way. The alternative is death. And we are not alone in this. Every single life form – from the lowliest amoeba to the grandest specimen of Homo Sapiens (i.e. you), does the same thing. That includes all animals, fish, reptiles, plants … everything organic. What, in point of fact, do we (life forms) give back? Waste. Sewage. Pollution. (I can’t think of anything else, on the physical level. With the exception of pollution, we do, after taking, actually contribute to the Life Cycle of the planet, in terms of the carbon dioxide we exhale, the organic waste we excrete, and the waste materials we leave behind when we die. However the point is that we have to take, in the first place, in order to live). There is no dishonour whatsoever in 'taking', provided you do not take more than your fair share. The dishonour comes – or at least came – when certain families (historically) elbowed their way to the front of the queue, thrusting all others out of their way, and said: “THIS IS ALL MINE! Everyone else sod off!” That’s dishonour. Taking just what you need, no more, no less, is fair, reasonable, right, just and honourable. Because your only other option is death. Scroungers, eh? Well scroungers actually ask permission, generally speaking: “’Ere, mate, gissacupla quid, will ya?” …. “Cor, fanks, mate! You’re a bloody diamond!” Now, sit back and imagine something. Imagine a world in which everyone (that’s everyone!) just took. Just took what they needed, whenever they needed it. Just what they needed, no more, no less. No, don’t laugh. Try to imagine it. It’s really important. It is what is going to set us free. Here’s a quick example. The Farmer grows wheat. The Miller just takes the wheat, and grinds it into flour. The Baker just takes the flour, and bakes it into bread. The
14
Taking Farmer and the Miller just take the bread and eat it. The Baker eats his own bread. All three survive. Now that was a very simplistic example, just to make the point. Obviously one has to expand that example to encompass all walks of life, but that can be done. However, certain 'walks of life' – those that are not in any way productive, would disappear. They would become obvious under a 'moneyless' paradigm. (Basically it would be everyone who you currently accept, grudgingly, as: “Well, I suppose they are just doing their job”) The fundamental point is: That example is precisely what is happening already. The only factor left out of that example was 'money'. Or should I say 'methods of payment'? So, how would that work without 'money/payments'? Well it would, I can assure you. Once again, I’m having to leave the detail until later, because I don’t want to overload your Common Sense at this point. Just keep reading. This whole book. All will be explained. All I want to achieve, at this point, is that Common Sense tells you there is no dishonour, nothing to be ashamed of, in taking whatever you need, because you have no alternative. That nature provides for everything you need, and there is no alternative to nature. And Common Sense tells you that the Farmer, Miller & Baker would survive in that example. So I guess the next stage, in order to flesh out the situation in which we find ourselves, is to recognise three very powerful Grand Deceptions, which have together suppressed many people’s ability to listen to their own Common Sense. So, let’s make a start with … with what? Well, we have three choices: 'Money', 'Legalese' and 'Religion'. They are all Grand Deceptions, so let’s start with Money.
15
Freedom Is More Than Just A Seven-Letter Word
Chapter 2: Money
T
he first Grand Deception is 'money'. It's an illusion. But, my goodness, a powerful one! This is probably the hardest part to understand. So I am going to have to explain as carefully as I can. Well, what is 'money'? Most people will think of a £10 or £20 note, and say: “That's money of course!” And the problem is: That's not money, of course. They are just pieces of paper, with a design printed on them, and a splash of silver-coloured ink. Fundamentally people know that, coinage is not 'worth' the 'value' stamped on it i.e. coins cost peanuts to make. And banknotes the same. Surely no-one really believes it actually costs £5 to create a fiver? Or £10 to make a tenner? And so on? I plead to your Common Sense! I prostrate myself, and grovel, at the feet of your Common Sense! So, if 'money' is 'not worth the paper it is printed on', what, exactly, is it worth? Perhaps one answer to that can be gained by defining it. What is the definition of ‘money’? Here's Chambers Online: money: noun (plural in sense 1b and 4 monies or moneys) 1 a coins or banknotes used as a means of buying things; b any currency used as legal tender. 2 wealth in general. Wrong! Let's see if a Law Dictionary can be of more help. Here's Black's 8th edition: money: 1. The medium of exchange authorised or adopted by a government as part of its currency; esp. domestic currency <coins and currency are money> UCC1-201 (b) (24) 2. Assets that can be easily converted into cash <demand deposits are money> 3. Capital that is invested or
16
Money traded as a commodity <the money market> 4. Funds; sums of money <investment monies> Wrong! And, not only that, I love the way (4) defines money as 'sums of money'. That's known as a Circular Definition. These are wrong because they define 'cash', not 'money'. That's the same thing, is it? Well then, how come there is always talk about: “... heading for a cashless society”? And the benefits of it? I've never heard any mention of: “... heading for a moneyless society” in the Mainstream Media. As you will see, if you read on, the 'moneyless society' is the one we need, and (I believe) we are going to get - for the simple reason that we can't go on for much longer under the absurd and preposterous illusion of money. And far too many people are waking up to that. There are a number of very serious proposals for working 'moneyless societies', such as the Resource-based Economy proposed by The Venus Project and Zeitgeist Movement (Google them for more information). My definition of 'money' is, I think you will find, a lot more accurate. Here's me: money: Conveniently transportable tokens of Credit. Isn't that the same thing, then? Absolutely not! Let's examine my definition. Well, first of all, 'conveniently' and 'transportable' are adjectives. Therefore all they do is to limit the scope of the subject of the definition. Take 'red' as an example. If I said: “All cars”, then I would mean every single car on the planet. If I added the adjective 'red' as: “All red cars”, I would not be talking about cars of a different colour, I would only be referring to the red ones. But I would still be talking about 'cars'. So, the adjectives do nothing more than limit the scope of the subject, which, in the case of 'money', is: 'tokens of Credit'.
17
Freedom Is More Than Just A Seven-Letter Word Yes, 'cash' is nothing more than tokens. We have already seen, by Common Sense, that the coins and banknotes - the cash - is fundamentally worthless. It has no more value, in reality, than tokens for a Fruit Machine. Or Green Shield Stamps (if you can remember those). Perhaps Supermarket Vouchers is a more up-todate example? What is a 'token'? A token is something real, something substantial in this 5-sense reality, something that can be touched, held, felt … that stands in place of in other words represents - something that cannot represent itself. A table does not need a token to represent it. A table is real, and can represent itself. A chair likewise. And so on. The thing that cannot represent itself is 'credit'. Because 'credit' is nothing more than an idea. A concept. Imaginary. A belief. A belief that a Shopkeeper has, such that if he swaps some goods for a £10 note, then he can use that £10 note at a later date, to make a swap with someone else. But this mechanism only works because everyone concerned believes it. (And only because of that) I say again: Because they believe it. And where are beliefs kept? Yes, in your head. In your brain. In your imagination. And that's the only place beliefs are kept. So the idea that 'money' is real … is an illusion. A Monetary System is nothing more than a Belief System. That's why, throughout the world, Belief Systems can be different. There was a time, not so long ago, when the Germans believed in deutschmarks, and the French believed in francs, and the British believed in pounds sterling. At the time of writing the British still believe in pounds sterling, while the French and Germans now believe in Euros. This is only possible with a Belief System.
18
Money The British, French, Germans, Dutch, Italians, etc. all still know that a table is a table, and a chair is always a chair. And what to do with them. We don't need to believe in tables & chairs for that to be the case. So, what is a banknote, or a coin? Well British banknotes give the game away, because they actually contain a printed promise. It goes like this: "I PROMISE TO PAY THE BEARER ON DEMAND THE SUM OF …"… and then followed by the amount written numerically (known as the 'denomination' of the note, £5, £10, £20 for example). (There is obviously not enough space for similar inscriptions on coinage). What does this mean? It's a promise. Thus a banknote is a Promissory Note. A piece of paper containing a promise. And bearing the signature of whomsoever is making the promise. Anyone in their right mind would call it an IOU! So, the British are passing around IOUs, from the Bank of England, 24/7! Do we ever expect the Bank of England to pay up, to make good, on their promise? Actually, at least one person I know about, did try. The Bank of England quickly showed her the door (and called the Police!). Someone else I know tried the same thing at Barclay's. Once again she was also shown the door (which, by the way, was locked and bolted immediately after she left!) Well, if you think the Bank of England will make good on their promise, then feel free to try. I very much doubt you will succeed where others have failed, for the simple reason that the Bank of England cannot fulfill on a Belief System. The Promissory Notes the British move around 24/7 are nothing more than empty, meaningless, IOUs. And they call it 'money'. And wars are fought over it. People die, and are subjected to atrocities for it. People
19
Freedom Is More Than Just A Seven-Letter Word commit suicide over it. In point of fact just about every ‘cide’ (genocide, patricide, homicide, suicide, etc.) is committed in the name of empty, meaningless, promises. IOUs by any other name. This would all stop on the day that what I've written herein is recognised as the truth, and Common Sense. Is it such a large step, by the way, to see how these empty, meaningless, promises can be converted to numbers in computer databases, and implants on plastic cards? Furthermore is it such a large step to imagine that we could run a world quite well, without the need to sling empty, meaningless, promises all over the shop? After all, the Euro notes don't even bother to make the promise, because the whole thing is so utterly worthless and superfluous. I'm fairly sure that, if the Bank Of England's notes said: “I PROMISE TO PAY THE BEARER ON DEMAND 5 UNICORNS”, and so on, people would start to cotton on. By saying: “'Scuse me, but what the hell is the good of 5 mythical creatures?” Well, of course, the Bank of England's current promises are actually mythical creatures. People say: “Without money, there would be no incentive for anyone to do anything”. What a terribly myopic thought!? Try sitting around, doing nothing, for any period of time. I submit you would be climbing the walls looking for something to do. Something constructive to do. Well, you need to eat, don't you? So, at the very least you would need to: “Get up off your bum, and go get some food”. And the same for your children, etc. That may not be overly constructive to the good of the community in general, but it is an incentive. And it is an incentive that does not need to be triggered by money. (It's triggered by hunger) Just about every example one can think of can be thought through rationally, in much the same way. It just
20
Money needs to be thought about carefully, that's all. It is no good half-thinking. Only whole-thinking will return the correct conclusions. Go back to the example of the Farmer, Miller & Baker. Why does that example need to include the necessity to hand around empty, meaningless, IOUs from the Bank of England, for that example to work? When all they actually need to do, is to say: “Sod it. We'll just do it!” I think you’ll find the reason is pretty obvious. The Farmer, Miller & Baker are in a real situation. Adding a component called 'method of payments' is only adding beliefs to that reality. This belief contributes nothing whatsoever to the actions taken by the Farmer, Miller & Baker. They could farm, mill & bake without any knowledge … other than farming, milling & baking. Subtracting the beliefs from the reality is subtracting zero from the overall equation. Subtracting zero from either side of an equation leaves the resulting balance unchanged. What's the difference between: “I know it works. I can see it works. I think/believe it works this way”, and: “I know it works. I can see it works”? Answer: “Nothing. Both say exactly the same thing, in fact”. It's just that, in the former case, the added belief may - or may not be correct. But that doesn’t matter, because it’s only a belief, anyway … and therefore totally discardable. Duh! You don't need to barter, baby, you just need to 'do it' (honourably contribute)! Sheesh! What right does some private banking cartel (the Bank of England) have to say only its empty, meaningless, promises are the ones to use? Why are its empty, meaningless, promises so much better than some empty, meaningless, promise of yours? Or better than those real promises the Farmer, Miller and Baker make to each other? If the Farmer suddenly ups and says: “No, you can't have any more wheat”, then the Miller can say: “In that case I can't make any flour, and the Baker can't make any bread, and therefore you won't have any bread to
21
Freedom Is More Than Just A Seven-Letter Word eat”. That would not happen because it would be so blindingly obvious. Common Sense. Money is an illusion. Based on empty, meaningless, promises from the Bank of England in the UK, and the Federal Reserve (yet another private banking cartel) in the US. (If you are reading this somewhere else in the world, don't worry … it's exactly the same where you are located. The Grand Deception, the illusion of 'money', is the same throughout the world). Who says so? Her Majesty's Treasury say so. In reply to a Freedom of Information Request I made. (See an Appendix for details). I’ll be returning to this subject later, when I discuss Mind Control and Enslavement. Because the Monetary System is one of the primary mechanisms for Mass Mind Control and Enslavement. However, in the meanwhile, here are a few things to consider in odd moments, as you may read on in this book. Think about this. Light. Where does it come from? It doesn’t take much imagination to know that daylight comes from the Sun. So, without going into to the deep science of the situation, we can freely say that: “The Sun is the source of all our daylight”. Heat. We can say a similar thing for heat that warms our planet. It comes from the Sun. Water. That comes from the sky, drops as rain, and eventually evaporates back into the sky again. In a cycle. But where did the original water come from? Once again, no real science is involved in the answer. It has been there since the planet was formed. The point of this explanation is: “These things have an ultimate source … for practical purposes, anyway”.
22
Money And a little thought says that everything must come from somewhere. Everything has to have an ultimate source, for practical purposes. And so it must be that money has an ultimate source, does it not? If so, what is that ultimate source? Have you ever thought about it? Does it grow on trees? Does it come from the Sun? Does it drop like rainfall? Well, no, it doesn’t. Everyone understands that. So where does it come from, then? Ask anyone where their money comes from, and they will generally reply: “I work, to earn it”. So you can then ask: “But who gives it to you?” and they will say: “The Company I work for, of course!” Then you can ask: “Where does the Company you work for get it from, so that it has some to pay over to you?” and they will say: “Well, they sell goods to Consumers, or they provide services to Consumers … and they charge for it. So that’s how they get their money”. And so you can say: “Well, where do these Consumers get their money from, so as to pay for these goods & services?” and the answer will come back: “Well, they work for other Companies … who pay them for the work they do! Cor! Are you daft, or something?” So now we are just going round and round, aren’t we? We have still not established the ultimate source of where money comes from, in the first place. Probing a little deeper, an answer might be: “My Company gets it from a Bank, I suppose”. So then it is possible to ask: “Well, where does the Bank get it from, then?” And then you’ll possibly get: “Well, I suppose the Banks must make it … I don’t know!” So you can then say: “Well, if the Banks make it, then why do they expect you – if you take out a loan – to pay
23
Freedom Is More Than Just A Seven-Letter Word them back? I mean, if they can just make it anyway? And why did they need a bailout of it, in late 2008? And why did Banks go out of business, if they can just make money?” And you are very likely to end up with the retort: “Well, I don’t know! Ask them!” To which the obvious rejoinder is: “Well, do you not think it would help you to know? Because, if you did – know where it came from, I mean – then maybe – just maybe – you could go and get some … to help you over any money problems you might have? Have you never had any money problems? Most people have. Do you not think that knowing where money actually comes from, in the first place, might help you?” The response will probably be: “I dunno”. And that’s the point. Who, precisely, knows where money actually comes from? In the first place? Who knows how it gets into circulation? So let’s look around for the possible sources. My next door neighbour? No … he’s in the same trouble as I am. My employer? No … we’ve already been through that. The Banks? Well, no … at least not most of them … but there is the Bank of England, and that doesn’t go out of business, did not need a bailout, and its name is printed on every banknote. So they are a distinct possibility. Let’s keep them in mind. What about HM Revenue & Customs? No … they want money, so they can’t be the source of it. The DVLA? No … they also want money, so they can’t be the source. The Local Councils? No … they also want money. The Government? Well, yes this is possible. But one of the Government Agencies is called HM Revenue & Customs, and they want money. So that’s a bit strange, isn’t it? Let’s also keep that in mind.
24
Money Now there is a Government Agency that never asks for money. I wonder if there is something in that? The Agency in question is located in Horse Guards Road, London. It is called HM Treasury. Have you ever received a demand from HM Treasury? I haven’t, in my entire life. So how does HM Treasury operate, without demanding money with menaces? That’s a question, surely? And it can be shown that the Bank of England is also a private Bank, just like RBS, HSBC, Barclay's, etc. So they should be in the same position, needing a bailout. But, what the privately-owned Bank of England has, in its favour – which none of the others have – is the ability to print money. A privately-owned Bank, with the ability to print money. That's an interesting situation to be in, of course. But that’s only printing it. It still doesn’t explain how these printed notes, and minted coins, actually get into circulation. We know that someone does not stand in Threadneedle Street, with a bucketful of it, and hand it out to passers-by. We also know that they don’t hire an aircraft and bail it out, letting it float down to whomsoever can catch it. But we also know that we never receive demands from HM Treasury, the Bank of England, nor the Royal Mint. And we also know that we do receive demands from just about everyone else. So, I think, we have some clues to suggest that money is created by HM Treasury, printed by the Bank of England in accordance with instructions from HM Treasury, and minted by the Royal Mint under similar instructions from HM Treasury. And that it is released into circulation via a mechanism we have not been told about (as yet).
25
Freedom Is More Than Just A Seven-Letter Word Does anyone have a better idea? Because money must come from somewhere, and I think I have eliminated most of the other possibilities. So now lets turn to the ‘strangeness’ of HM Revenue & Customs. In conjunction with HM Treasury. They are both 'HM's, which stands for 'Her Majesty’s', of course. So, even if HM Treasury is not the ultimate source of money, some 'HM' must be. Let’s assume it is HM Treasury. (After all, what else is their job, then?). So we would have HM Treasury making money, and HM Revenue & Customs wanting money. So why can’t these two 'HM's just get together … and leave us all alone? Well, that’s another question, isn’t it? And then we can add that one of the jobs of the US Treasury, embodied in the Act creating it, was to 'issue warrants for monies'. Or, to put it another way, to provide authority for the creation of US currency. And then, add to that, the UK Currency Act defines the weights and measures for coins, and also provides for the Chancellor of the Exchequer to apply an upper limit as to how much currency can be authorised into circulation. The biggest problem is that HM Treasury will not admit to any substantial role in respect to the 'creation of money'. However, when asked point blank, HM Treasury will not go on the record denying it. So that's interesting as well, isn't it? Why would they be so coy? Listen: I’m sorry to bat on about this, but some Government Agency must be creating 'money'. Thus, if 'money' is required to pay for the (say) maintenance of roads, then surely there is nothing to stop the appropriate agency that creates ‘money’ from creating
26
Money the 'money' to pay for the maintenance of roads. Is there? I’m really sorry, but why bother you & I? It's not a Government Agency creating 'money', you say? OK, well, that still doesn’t alter the essential point: If 'money' is required, for the maintenance of roads, then whoever is maintaining the roads should obtain the 'money' from whoever creates 'money'. For crying out loud, there is still no need at all to bother you & I. Is there? It doesn't work like that? OK ... how DOES it work then? Why do I need to get involved with Road Tax? Pedestrians & cyclists use to roads all day and every day. They are not bothered with these things. How many more ways can I say the same thing? How many more examples do I need to offer? Did you elect your Government to look after the roads, or did you elect it to make absurd and unrealistic demands on you? Did you elect it to make the ‘money’, and then ask you for it? Honey, they make the ‘money’! Why do they want it back in Road Tax, Sales Tax, Council Tax, Inheritance Tax or TV Licencing, etc? Unless … unless … gosh-an'golly-gee … are YOU the one who makes all the 'money'? 'Coz that means everything in this little book is complete rubbish! But never mind … listen, darling, if that’s the case: Can I have your address, please … because: “DAAARLING! Where HAVE you been all my life? Yes, of course I love you. Yes, of course I mean it! You are tall, dark, handsome, debonair … you remind me of my father, and all that. No, the money has nothing to do with it … don’t be silly!” On the other hand, on the off chance it's not you who is making all the 'money', then (Oh … poo! I thought I was on to something there!) we are back to square one, aren't we? And so, as a final rant in this Chapter, it might be interesting to consider 'what goes away' when 'the Belief System, the Illusion of Money, the totally unnecessary Utter Absurdity of Money, goes away'.
27
Freedom Is More Than Just A Seven-Letter Word What does it take with it? Stealing is the first thing. There is nothing to steal. Hoarding is another thing. There is no point in hoarding, any more than there is any point in stealing anything. ‘Sell’, ‘buy’, ‘value’, ‘commerce’, ‘exchange’, ‘barter’, ‘interest’, ‘wages’, ‘salary’, ‘debt’ no longer have any meaning. And so on. The Global Elite (see their own Chapter) are now seen to be as worthless as they - in point of fact - always were. Their Swiss Bank Accounts now count for nothing whatsoever. Goodbye to the Stock Markets. Goodbye to the Banks. Goodbye to the Loan Sharks. Goodbye to the Debt Collectors. Goodbye to the Bailiffs, and the Accountants. And the Economists. “Services no longer required”. And so on. 'Rich' now becomes 'rich in good friends'. 'Rich in honour'. 'Rich in integrity'. And so on. Just like it always should have been. Just the way Common Law dictates. All these imponderables are wrapped up, ‘i’s dotted, ‘t’s crossed, in the final Chapter Mass Mind Control & Enslavement. But please don’t skip to it. There’s a lot more in between. By the time you have read this book all the way through, I think you will be in possession of a complete set of the most probable answers to all these questions. Answers that fit, what we all know to be true, like the pieces of a perfect jigsaw puzzle. Including the mechanism for releasing money into circulation in a controlled manner, and why everyone concerned would be so coy about the roles they play.
28
Legalese
Chapter 3: Legalese
I
'm going to discuss the English version of Legalese. Every nation on the planet will have its own version. (For reasons which, I hope, will become obvious). The same discussion and comments will apply. Because there is no other way. Legalese is the language of Statutes. It is assumed that Statutes are 'the Law'. They are not, as you will see if you keep reading. Statutes are discussed within their own Chapter. For now, I simply want to confine the discussion to Legalese itself. To show that it is an illusion. Another arm of the Grand Deception. There is an old Roman Law maxim that states: “Let he who will be deceived, be deceived”. That is so, so true. What, exactly, is Legalese? Well, first of all it is a language. It looks like English (in the British Isles), but it is no more 'English' than is any Foreign Language. French, for example. Or German. Or Croatian. It is written by those who draw up Bills for Parliament (and Congress). It is assessed by Committees. It is voted on by Members of Parliament (or Congress). If agreed it becomes an Act of Parliament (or Congress). It becomes so-called 'law' when it receives the Royal (or Presidential) Assent. At that point it becomes a Statute. A Statute written in Legalese. A Statute written in a Foreign Language. Now, you may be forgiven for asking: “How can I be expected to obey a rule written in a Foreign Language? How can I even be expected to understand what I am supposed to obey as an upright, law-abiding, citizen?” I, personally, would forgive you for asking that. Those who won't, are Members of your Government, the Judiciary - in terms of Judges, Clerks, Solicitors, Lawyers,
29
Freedom Is More Than Just A Seven-Letter Word Barristers, and Policemen. And the vast majority of your fellow Countrymen, quite probably including your own family & friends. And also including the Media. But I would forgive you, because you would be exactly right. And so, I think, would any other sane, rational, honest, honourable and decent Human Being. Really anyone still capable of using even just a grain of Common Sense. Apart from being a Foreign Language (I'll explain why), it also comprises a number of fictions. As we all know 'fiction' is not the truth. 'Fiction' is not the reality (I'll explain this, as well) Legalese is a Foreign Language because it re-defines or expands the meanings of certain words. English words. It does this for its own convenience (not yours, that's for sure!). One good example (I'll give you a better example in a minute) is the word 'understand'. Legalese expands this to mean 'stand under' - specifically (as we will see): “Stand under, i.e. consent to, Legalese”. So what does this mean? It means that if a Policeman, or anyone in a Court, asks you: “Do you understand?”, and you say: “Yes”, then you are agreeing to consent to the application of Statutes drafted in a Foreign Language. (Legalese is nothing if not thoroughly incestuous!). Here's the real dooley: In Legalese the word 'person' is re-defined by expansion. The word 'person' still means what you and I would expect it to mean viz: a Human Being; But in Legalese it is expanded to mean: '... any grouping of people, any Partnership, any Company/Corporation'. (I think those who drafted this standard for their own convenience, were assuming that they could move a word defining a singular, into a plural … taking their cue from the fact that some English words are like that. 'Sheep' and 'fish' are obvious examples. However, I'm only guessing, and why they thought they could get away with it doesn't matter anyway). The idea was, of course, to give Corporations, Companies & Societies the same or similar 'rights &
30
Legalese duties' as a Human Being. An utterly stupid idea, as I hope you will appreciate, by the time you have read and fully-comprehended this book. So, let's use some Common Sense to look into the sanity of expanding the definition of the word 'person'. A Human Being has a head within which there is a brain, within which there is - what we would call - a Mind. And a Human Being is 'aware', is conscious, and has a soul. A Human Being also has eyes, and ears, and limbs. And so on. A group of people, taken as a group, has none of these things. The individuals that form the group do (of course), but not the group - of itself i.e. when taken as a ‘legal entity’ in it’s own right. It does not matter how much Legalese would like to grow arms & legs on a group, it cannot happen. It is physically impossible. A simple example is 'deciding to do something'. A Human Being can work out what to do (using the brain), and do it, using its limbs. A Corporation has to firstly, go through the motions of making a collective decision, and then get/persuade/task a Human Being (e.g. an Authorised Company Representative) to actually do whatever has been decided. More specifically, signing a document. A Human Being has limbs with which to grasp a pen, and a brain to control the necessary hand movements, in order to make his or her unique 'mark'. A Company has to fall back on tasking a representative to make a 'mark' … on behalf of the Company. When it comes to liability for actions taken, a Human Being can be fairly and squarely placed in the frame. In the case of a Company, buck-passing is the order of the day. Don't expect any Human Being, who is a part of any Company, to own up to anything! Consequently, by no stretch, would any sane individual consider a single Human Being to be equivalent to a Group.
31
Freedom Is More Than Just A Seven-Letter Word And that's where Legalese starts. It starts with insanity and irrationality … and then steadily gets worse. It layers fiction (calling a Company as 'person') upon fiction. It creates what is known as a Legal Fiction Person from each and every Human Being. It does this in order to be able to fictionally equate a Human Being to a ‘singleindividual-partnership-or-CORPORATION’ for ‘legal purposes’. This is done so that any adjudication in a Court de facto (what that means is explained later) is One CORPORATION .vs. Another CORPORATION. Very simply because it is perfectly obvious that no adjudication is possible between the reality of a Human being and the fiction of a CORPORATION. How can anyone ever adjudicate between a reality & and an illusion? The reality, the Truth, would always win against the fiction, the Untruth, hands down! A Chapter in this book is devoted to Legal Fiction Persons. It is also interesting to note that there is an excellent video available, called The Corporation. This video not only explains how and why CORPORATIONs all came about, but goes further to compare the actions of any CORPORATION to that of the real Human Being it purports to impersonate. The video goes into massive detail in order to explore this concept. And, for that reason, it is highly recommended viewing. And what does it conclude? It concludes that, if a CORPORATION (any CORPORATION) were a real person, it would be a psychopath. And, furthermore, the definitions change from time to time. That's why Black's Law Dictionary is now in its 8th Edition (at the time of writing). Its 8th Edition of pure fantasy and absurdity. You want some more? I’m reliably informed that if you look up ‘Human Being’ the 4th Edition of Black’s Law Dictionary, it says: “See ‘monster’”. Not so, by the
32
Legalese time we get to the 8th Edition, of course. It’s a moving carpet. Of course it is perfectly possible to step back and use a bit of Common Sense. The very fact that Law Dictionaries are necessary, gives the biggest hint. In English we already have dictionaries to define our language, in terms of normal parlance. The Oxford English is probably the best known, but there are many others. They do not define the word 'person' as a Corporation. Because Legalese is a Foreign Language it needs its own dictionary. If it were not a Foreign Language it would not. Languages always need a dictionary. If we could always rely on Oxford English then we would, would we not? What would be the point of Oxford English otherwise? Legalese is an illusion. A fictional world created for the benefit of mind control and enslavement. It is an English look-alike, and no more than that. Because it 'looks like English', no-one complains. But we should. We should all complain. We should all say: “This is bloody ridiculous! How dare you impose rules to be obeyed when they are written in a Foreign language? Get outta here!” As you will see later, in the Chapter discussing Promises & Contracts, the vast majority of the so-called 'Legal Profession' have not the slightest clue about all this. Which means that if you understand the illusion of Legalese, then you can run rings around them. I’ve got an idea! Let’s dump Legalese on the Rubbish Tip of History, and stick to Oxford English, shall we? Then we’d all know where we stood, wouldn’t we? I have seen many examples of letters from Solicitors, Lawyers, and so-called 'Legal Scholars', which are a complete mass of double-think. Under careful and critical scrutiny just about anything they write can be shown to be totally contradictory, and thoroughly irrational. The reason for this is because they live in a fictional world, and are always attempting to replace
33
Freedom Is More Than Just A Seven-Letter Word Common Sense with fiction. They achieve little other than disappearing up their own hindquarters. The benefit to you is that you can write plain commonsense, and they will not understand! They will not understand because Common Sense does not compute in their fictional, illusory, world. Because they do not understand they will resort to ignoring what you said, and reply to the-question-theywanted-you-to-ask. And they will reply in their own way. (How often do Politicians do that? How about like: “Always”? It's the same old smoke & mirrors). What this means is that they have 'not responded in substance' to the points you made. They could not 'respond in substance' because that would not compute with their illusion. Since they have 'not responded in substance', they have dishonoured, and you have not. In Law: “He who dishonours, loses”. Generally speaking, when it comes down to brass tacks, we have found that - for all their huffing & puffing - they never actually go to Court. Primarily (we think) this is because - at the end of the day - they know, deep down, that your Common Sense trumps their Legalese. Hands down. One of the biggest questions to arise is: “What’s the difference between ‘legal’ and ‘lawful’?” Well here is one big clue. 'Legal' refers to the illusory world of Legalese. 'Lawful' means truly bound by Law (long established customs & traditions), in the real, Common Sense, world. The Law established over centuries, by consent (Consensus facit legem in Latin – Consent makes Law in English). There is much more about this later. “Let he who will be deceived, be deceived”. Don't be deceived.
34
Religion
Chapter 4: Religion
R
eligion is the third of the illusory triumvirate. People wrongly equate 'spiritual' with 'religious'. Whereas 'religion' is no such thing. Religion comprises dogma. For example to tell you that you need to be 'saved'. And how to be saved. When, in point of fact, you need to be saved from three things only: 'Money', 'Legalese', and 'Religion'. The imposition of religious dogma is designed to suppress your ability to use Common Sense. No? Well it does. In order to follow a religion - any religion - you have to be prepared to double-think, to a greater or lesser degree. Double-thinking is the antithesis of Common Sense, and any critical thought processes based on Common Sense. 'Religion' is the third arm of the mind control and enslavement paradigm. Be as religious as you want. But don't forget that freedom is freedom. Even if you become free, with the help of later material in this book, is there any point in then surrendering any of your gains to any religion? Once you know what you are, you don’t need anyone else to tell you. If religion is so empowering, why has no religious person (to the best of my knowledge) ever written this book? Or anything like it? Are you suggesting that plain unvarnished Truths, contained within plain old Common Sense, aren’t worth preaching loud & clear from every pulpit? Gosh, no. Religious dogma is far more important, isn’t it? You have all the power necessary to save yourself & your loved ones. But no ... don’t do that ... let Jesus do it.
35
Freedom Is More Than Just A Seven-Letter Word Reading Zecharia Sitchin's book The 12th Planet explains exactly how we all came to be here, and what 'God' is. Sitchin is an expert on the Biblical Old Testament, is fluent in Hebrew, and can read the original Hebrew versions of Ancient Texts. He explains how 'God' occasionally moves into the plural – i.e. 'Gods' – by referring to 'we' and 'our', etc. These are possibly transcription mistakes from the Truth contained in the Ancient Sumerian Tablets. Or they could very well be deliberate mistakes, left in by the Ancient Scribes (who were quite probably re-writing history at sword-point), and left in by design, in order to give later readers ‘a clue that all was not exactly as transcribed’. One does not know. One cannot know. But Sitchin has picked them all up, and we all owe him a debt of gratitude for that. In the Chapter on Mass Mind Control & Enslavement I explain the results of being created by these 'Gods' (the Biblical Nefilim). And how we would have taken their word for the way to live, and why we would have emulated them in all respects. Yes, I know Sitchin has been ‘outed’ as one of the Reptilians. (The shape-shifters). In fact the information in his books, known collectively as The Earth Chronicles, could surely have only come from that kind of deep knowledge. The information, the insights and the critical thinking behind them, are far and away too consistent to be purely intuitive. His ideas are imparted with mathematical precision. Sitchin is undoubtedly (in my mind at least) one of the few who are on Humanity’s side. According to the Ancient Sumerian Tablets, 'taxation' was rife in Ancient Sumer. 6,000 years ago. Jesus (if he existed): “Threw the moneylenders out of the Temple”. According to the Bible he was once asked about taxation. His reply was: “Render unto Caesar that which is Caesar's, and to the Lord that which is the Lord's”.
36
Religion It's a pity none of these people ever used a modicum of Common Sense, pointing out that 'money' is an illusion. So it's now time to stand up and see how we have all been deceived for some 300,000 years. And claim our Humanity.
37
Freedom Is More Than Just A Seven-Letter Word
Chapter 5: Global Elite/Psychopaths
S
o we have three major illusions: Money, Legalese and Religion. All three deliberately designed for mass mind control and mass enslavement. So who is running this show? Well, the best answer anyone has yet come up with is: The Global Elite. The Banksters. (But they also own everything else, including all the 'big' Corporations, and Governments, the media, and legal systems, etc). Referring back to what was said earlier, details of all of this have been exposed for at least 20 years by researching writers such as David Icke, Jordan Maxwell, William Cooper, and others. Others include Myron Fagan, Benjamin Friedman, and Jack Bernstein, going back as far as the 1960s. Even Charlie Chaplin could see ‘something was very wrong’. It is apparent to me that, while there has been much discussion on just who, exactly, the Global Elite are naming names such as the Rothschilds, Rockefellers, Brofmans, Webbs, Windsors, etc. - it seems it has yet to be explained just, exactly, what the Global Elite are, in terms of their obvious 'lack of humanity'. And what, and why, that is. David Icke has referred to them as: “Having no empathy”. Which is true. They would not have created these Grand Deceptions if they had been 'nice people to do business with'. Now, you'll probably resent knowing this, but you exist in a prison-without-bars. A prison that has been carefully constructed, over centuries, by those 'not very nice people to do business with'. Unlike a real prison - where you see the bars - you'll firmly believe you are - basically - free. But, unfortunately, you are not. As each day goes by, your freedoms - many of which are essential for a decent and
38
Global Elite/Psychopaths reasonable life - are being taken away from you by very subtle stealth. And this has been going on for a very long time. Hopefully, when you have read to the end of this book, you'll understand the prison, and will be able to see the bars, and be in the position of breaking out of them, using the enormous power you possess. Power you do not realise you actually have. In his book 1984 George Orwell said: “He who controls the present, controls the past. He who controls the past, controls the future”. To understand today, one must understand a certain amount of history. To understand the possibilities for future, one must understand today. George Orwell also said: “Omission is the biggest form of a lie”. (One could, in point of fact, quote Orwell almost constantly. For the very simple reason that, in the 1940s, he actually gave us an amazing number of clues, through that book and his other masterpiece, Animal Farm) 'The past' means 'history'. How far back in history do we need to go? Well, in point of fact you can go back as far as you wish. For the very simple reason that 'human nature' has always been with us. And the lessons we must learn derive from what happens when human nature is up against a 'less-than-human nature'. What do I mean by that? I'll simply quote ONE, verifiable, medical/genetic statistic: "One in every 25 people are born psychopathic". That's a quote from the studious works of Psychologist Andrew M. Lobaczewski. See his book Political Ponerology: A Science on the Nature of Evil Adjusted for Political Purposes (1998). Since there are 4 x 25s in every hundred, this means 4 people in every hundred, or 4% of the total population are psychopathic. According to my arithmetic, and taking the population of the United Kingdom as 60
39
Freedom Is More Than Just A Seven-Letter Word million people, that means there are 2,400,000 psychopaths out there. Do you think it might be a good idea to know this? Does that mean 2.4 million 'axe murderers'? Well no, not exactly, as you will see, but it does mean that there is the potential for 2.4 million 'axe murderers'. Psychopaths-in-society tend to be much more subtle. (And get a heck of a lot further than axe murderers, as we will see). It all comes down to what a psychopath actually is. Put simply it is a person who has no conscience. No compassion toward others. No empathy towards others. Unable to feel guilt, or shame. How does this occur? It occurs because of the lack of a gene in such a person's DNA. The gene that creates 'feelings towards others'. But a psychopath retains 'feelings towards themselves'. Although they don't feel guilt for any action they may take, they do feel 'fear'. And they know what would happen to them if they get caught. So they are afraid of getting caught. 'Fear of getting caught' is, in fact, the only thing that actually keeps them in check. So, if the possibility of 'getting caught' can be eliminated, then the psycho has free rein. And that, fundamentally, is what has happened. How has the possibility of getting caught been eliminated? Money and blackmail. If you have enough money, you can do anything. You can buy people off. You can arrange circumstances that create the possibilities for blackmail. You can arrange for 'character assassination' in the media (because you own the media!). You can arrange for actual assassinations. With sufficient money behind you, you can do anything. Back in the 18th century, Amshel Rothschild said: “Give me control of a nation's money supply, and I care not who makes the laws”. Yes, the thing about these psychos is they catch on a lot quicker than most of us. Most people find the idea of a psycho hard to grasp at
40
Global Elite/Psychopaths first sight. So it might be an idea to think about it in a little depth. A baby is born. The baby looks like all others i.e. Winston Churchill. The baby learns to crawl, talk a bit, and to toddle. There is very little to distinguish this small person from any other. It is only when this person becomes what we would call 'a child' that any symptoms might be detectable. And only then if we knew what we were looking for, and that is far from easy (in fact may not be possible), because all children can be naughty. Picture a school playground. A child falls, or is knocked, over. Other children rush up, and say: “Are you all right?” or: “Can I help you up?”, and so on. The psychopathic child sees this, and thinks: “I don't know why they do that. They aren't hurt. Why should they care? I'm not hurt. I don't care”. But, on the other hand, not to be seen as the odd one out, the psychopathic child learns to do the same. Not because they care, but just because they don't want to be seen as odd. In short, a psycho learns 'how to emulate a conscience' - by observing the reactions of others. During teenage years, as knowledge accumulates, and as situations come and go, the psycho could well be tempted to say (to themselves): “You know, most people are stupid. They have a problem. They are forever looking out for others, when they should be looking out for themselves. Yes, they have a problem. I don't have that problem, I'm glad to say. I think they are inferior. I think I was born 'superior'. Perhaps I'm one of that 'master race' they told me about in school. The ones the Germans believed to exist, and fought WWII over”. And, gradually, it dawns on them: “I can use this to my advantage! I know how to pretend, I've done that OK so far. So if I carry on pretending to care, no-one will realise that I can use my advantage, my superiority”. Consequent to all of this, they will generate - within themselves - a burning ambition to 'get to the top of the
41
Freedom Is More Than Just A Seven-Letter Word tree, by hook or by crook'. Letting nothing stand in their way. Before long they will consider it their 'destiny'. And they will justify this by saying to themselves: “Hey, taking these people for a ride is good, because they leave themselves open to it. They actually ASK for it! They actually deserve it!” In business, when up for promotion, they will use every trick in the book - as long as they don't get caught - to get the job on offer. If other people's lives are ruined in the process … so what? And so on. Surely I've said enough to paint the overall picture? Once in a position of 'power', it is then possible to promote psychos to staff the hierarchy below. And conjoin them, by various forms of blackmail, to provide protection from 'getting caught'. This could be the simple blackmail of: “You rely on me for your job, never forget that”. (That's very simple, but very powerful, blackmail … is it not?). Is it possible that such phrases as: “It's dog eat dog out there” or: “There's no sentiment in business” and: “If I didn't do it, someone else would” (and so on) could come straight out of the mouths of such people? Is it possible that such people could send thousands to fight, kill, maim, bomb innocent men, women, children and babies - in some foreign country - and they, themselves, still get a good night's sleep? No shame. No guilt. No responsibility for their actions. 'Justified' by their 'ability to take the hard decisions'? Even to be caught endlessly lying, and yet still smile and carry on regardless? No shame. No guilt. (No resignation). Does anyone see a connection here, between what I've said and British Prime Ministers? And US Presidents? And French Presidents? And German Chancellors? And UN Secretary-Generals? And EU Commissioners? Russian Presidents? In point of fact the 'leaders' of every nation on Earth? Or am I just plain old paranoid?
42
Global Elite/Psychopaths Here is a quote from a Psychologist who fully admits to never actually interviewing Tony B Liar, having just had the (unpleasant) experience of analysing him via the TV screen (this quote dates from about 2004, when I received it in an e-mail): “I have worked with a lot of psychopaths, and the one thing about them that is consistent is that whatever they are doing, their eyes rarely change. There is just a coldness there. You know, when a healthy person smiles their eyes 'light up' or conversely 'blaze' with anger. In all the pictures and TV broadcasts I've seen of Tony B-Liar [sic.], his eyes are always fixed - even when he's smiling as in the 'pictures of the God' comment. When a person starts saying that he consulted God about starting a war that led to the killing of innocent people as well as our own young servicemen, it's a sure sign he is suffering from psychopathy. Unfortunately it's not considered treatable under the Mental Health Act! Blair must be locked up in a Special Hospital forthwith. But some tribunal will probably let him out to kill again!” Note what was said by the Psychologist. 'Psychopathy' is the one major mental state for which the rest of society cannot be protected under the Mental Health Act. Why did Tony B Liar make it so easy to collect your DNA at every possible opportunity? It goes back to the DNA, remember? DNA analysis can detect whether you are a psycho like Tony, or not. DNA has nothing whatsoever to do with catching criminals, and Tony knew there are no terrorists to speak of - apart from himself and his gang of psychos. Your DNA is in your hair. Pick a stray hair from someone's jacket - in a restaurant - and you have something that can be left at a crime scene for the police to find. How can that situation possibly work? It can't. Now let's summarise. Psychopaths have been around since the dawn of time. Their 'condition' gives themselves a driving ambition, to 'get to the top by hook
43
Freedom Is More Than Just A Seven-Letter Word or by crook'. But what's the point of getting to the top? There is only one point: To dominate. There is no point in having 'power' over others unless it is wielded, which provides the fuel for massive ego-massaging. Quite why one should feel the driving desire to control others is something I don't, personally, understand. I don't understand the logic and rationale of their mindset. I don't see the point of their mindset. I don't see any ultimate point. I don't see how it can ever have any ultimate point. But I fully understand that they have that mindset. Personally speaking, I think you should do your thing, and I do my thing, and we just all get along amicably without me dominating you, or you dominating me. I can see that idea stretching into infinity without introducing rancour - rancour that would eventually generate revolution and bloodshed. Consequently the psychopathic mindset is utterly myopic, in my humble opinion. But that has never stopped them from being clever. Fiendishly clever, in point of fact. And that did not stop them from playing a very, very, long term game. A game that the initiating psychos never expected to see the results of, but they thought their descendents would. This attitude is the source of the 'Divine Right of Kings'. Which translates as: “We are superior because we are uninhibited. We can make uninhibited, dispassionate, decisions with your life and limb”. (Back in olden times of course the King also risked his own life and limb. But that all goes away as soon as a woman takes the throne i.e. Queen Elizabeth I, or Queens Anne, Victoria, Elizabeth II. And nowadays the Monarch only 'risks their children'. But that's only to some extent. By pulling strings, the 'risks' are minimised to almost nothing) But, remember, it's all in the DNA. The 'compassion gene' could return, to the bloodline, if marriages are not very carefully arranged. Now do you understand why these bloodlines are kept 'pure'? It is to ensure that this
44
Global Elite/Psychopaths pesky gene doesn't return so as to interfere with the 'Divine Right of Kings'. We know what happens if that pesky gene returns. If someone from a psychopathic family, but in possession of a 'better nature', makes it to 'the top', then they are assassinated (JFK). And so is their brother (RFK). And their son (JFK Jr.). And so that pesky gene is eliminated. This also happens if a non-psychopathic Pope attains that position. After 33 days, they are poisoned. Got to keep that pesky gene under control! So that's what we are dealing with. Does it all make a lot more sense now? Does it explain why demonstrations, letter-writing campaigns, petitions and so forth - and elections - make not the slightest difference? Because all of these are appealing to the 'better nature' of creatures that do not possess a 'better nature'! As you will see, if you read on, your only defence is to know your enemy, and put your foot down. Using the immense power you possess. Power you do not realise you have. The power to make decisions based on Common Sense, and to put those decisions into effect.
45
Freedom Is More Than Just A Seven-Letter Word
Chapter 6: Promises & Contracts
I
f Human A makes a promise to Human B, is Human C bound to honour that promise? We know this sort of thing happens, certainly within a family. Mum promises next-door neighbour that her son will come round tomorrow and fix the leaking guttering. Meanwhile her son has arranged something for himself for tomorrow. Get the picture? “Oh … Mum! I promised Steffie I would take her out tomorrow! Shit! You always do this to me!” It doesn't work, does it? No … you can't go around making other people's promises. You can only make your own promises. Common Sense. So, what right does any Government have - to make promises on your behalf? Well … none really. But there are exceptions. And I'll explain an obvious one by example. (Please do not accuse me of chauvinism. I write this example in the simplest way, so as to make the situation clear. You can substitute sexes as much as you wish. The result, the analogy, is precisely the same) A secretary will run an Appointments Book for her boss. She will know his business inside and out, and will take calls on his behalf. And, when clients call, she will make appointments for him, and he will fulfill those appointments. Because he trusts her, and she trusts him. The essence of this equitable situation is that little word 'trust'. And, more importantly, this entire arrangement exists because both the secretary and the boss have
46
Promises & Contracts 'consented' to it in the first place. He offered her the job, and she consented to accept it. 'Consent' and 'trust' are essential for a situation where one can make promises on behalf of someone else. 'Consent' and 'trust' are essential for equitable arrangements. Otherwise it is not possible to make promises on behalf of someone else. Common Sense? If you don't trust your Government, then it has no right to make promises on your behalf. Common Sense? If the Government makes treaties with the European Union, then the Government is making promises with the European Union. Not you. You are making no promises. And you cannot be held responsible and lawfully bound by any promises the Government may make. Only the Government is bound by the promises it makes. Unless you consent to it, no-one has the right to make promises on your behalf. No-one (unless you consent!) You really need to understand this. It's just plain Common Sense. Don't moan you never got a Referendum. You always have a Referendum! It's called Lawful Rebellion, as we will see. (And you can do 90% of it from the comfort of your armchair). But we will come to that. Let's keep on track, and put promises into context. A Contract is: “A promise the Law will enforce”. That's the basic definition. But you may notice that is singular. Which refers, therefore to a singular Contract. There are such things but, for our purposes, they are not worth dwelling upon. For our purposes, the Contracts that are important are those between two Parties - generally you and someone, or something, else.
47
Freedom Is More Than Just A Seven-Letter Word Therefore I will explain the Contract as: “A pair of interdependent mutually exchanged promises the Law will enforce”, being the basic definition to examine. For a Contract to be enforceable in Law, it must fulfill certain commonsense criteria. There are four of them, and they are designed to make sure the promises are sufficiently explicit, such that neither Party can later claim: “I wasn't told about that bit!” These components are: 1. Full Disclosure: Which means that each Party writes down exactly what their promise comprises, and all the relevant circumstances, so as to put it into the context they consider applicable. If one has any sense, any necessary 'get outs' should be included within the Full Disclosure. 2. Equal Considerations: A Contractual Consideration is an ‘item of value’. It may be money, or it may be an item. Both Parties must consider the exchange to be equal in value. (As we have already seen, ‘money’ is an illusion, and is nothing more than an empty, meaningless IOU. Consequently most Contracts can be shown to fail in this respect, if one has the will to do that. This is explained later. One argument, when receiving a demand for money is: “What do you want me to pay you with? Meaningless, empty-promise, worthless Debt Notes? Or do you want something of value, in which case you need to ask for it”). Obviously for Considerations to be equal they cannot change, once agreed. Thus any Contract employing variable Interest Rates is null & void in Law. Accepting the validity of variable Considerations, and not standing up against them, is precisely how so many people embroil themselves in debt. And, in any case – as we will see when we re-consider 'money' in the Chapter on Mass Mind Control & Enslavement, the funds to create 'Interest' forms no part of our Monetary Belief System. Or, to put this another way, 'Interest' is nowhere created, and consequently it is
48
Promises & Contracts impossible to pay off all loans, and impossible for everyone to stay out of bankruptcy. Those who stay out of bankruptcy are doing so purely on the backs of those who enter bankruptcy – purely because they were simply the first to grab whatever was available. (Whether they realise this or not). Oh! And did I mention the real dooley? A lawful Contractual Consideration must come entirely from each Party’s own resources. This is where just about every ‘supposed’ Contract breaks down. For example, a loan or mortgage will not have come from whoever issued it. It will have come from thin air. This can be shown to be the case by demanding the full accounting, showing where the ‘money’ actually came from. The answer will be: “Nowhere but keystrokes. The bank just typed a few numbers into one of their computers”. The ‘Banking’, ‘Loaning’ and ‘Credit’ Systems are totally illegitimate, in reality. They depend entirely for their legitimacy on Governments saying: “This is OK for banks to do, but for anyone else it is fraud/deception/counterfeiting”. And the reasons for this attitude are known, in the vernacular, as ‘kick-backs’. “You didn’t give a kick-back? Oh, then creating ‘money’ out of thin air is fraud! Counterfeiting! You did give a kick-back? You gave us the ability to just print ‘money’? Oh, creating ‘money’ out of nothing is perfectly legal, then!” That’s the way it works. But ‘demanding the full accounting’ does tend to cause just a few little problems with that mechanism. Simply because the full accounting doesn’t, actually, exist. 3. Lawful Terms and Conditions: Which, fundamentally, means that there should be no mischief in the proposed agreements. 4. Mutual Intent: Which means 'some manifestation that each Party intended to Contract'. This could be hand-written signature 'marks', or can be 'conduct'. In other words if at least one of the Parties starts to do what was promised. This is sometimes expressed as 'performance' - or, at least, 'the start of performance'.
49
Freedom Is More Than Just A Seven-Letter Word You have, probably without realising it, entered into many Contracts in your life. And, as we shall see, most of them are null and void in Law, because (even allowing for the small print) they fail on at least one of the components 1, 2, 3 or 4. The most important thing to realise is that no ‘small print’ can override the fundamental aspects a Contract must fulfill in order to be lawful, and therefore enforceable. ‘Invalid small print’ does not actually nullify a Contract, but its provisions are irrelevant because they are unenforceable in Law. Therefore any Contract that relies upon unenforceable small print (for example variable Interest Rates) is – to all intents and purposes – null & void. But you have to say so. A Court will not say it for you. And this provides the necessary 'get-outs'. Ultimately, at any rate. However, as we shall see, you have many more get-outs before resorting to nullifying Contractual Obligations. Nevertheless it is always a good idea to keep these points in mind, and not to forget them. For the simple reason that you will gain confidence by knowing that - at the end of the day - you can actually win any-which-way. Previously I referred to your immense power. Part of your power is this knowledge. And the fact that those you deal with (I call them the Organic Robots) have absolutely no understanding of this at all. They just operate 'by rote'. And this includes the vast majority of the so-called 'Legal Profession'. This enables you to run rings around them. There are a number of other points. One of the main ones being that: “Adding something to the Contract once it has started is not allowed”. There are many instances where this happens. A prime example of this is 'upping the Interest Rate'. No! No! No! That's a breach of Contract, matey! You can't adjust the Considerations once they have been agreed! Once agreed, they are fixed. And it's no good writing them into the Contract in the first place. If you write unlawful Conditions into a
50
Promises & Contracts Contract, then those provisions are not enforceable. Only the lawful Conditions are enforceable in Law. But you have to say so. Otherwise they will walk all over you. But there are some very subtle ones as well. If, when you buy something, the Terms & Conditions are inside the box, then they are null & void. The Contract started when you handed over the money to purchase the item. At that point, if the Terms & Conditions were not made absolutely clear to you (before you handed over the money), then appraising you of them, in a booklet, inside the box, is: “Too bloody late, mate!”. This is all absolute Common Sense, if you think about it. Anything else defines a moving target, a rug that can be pulled away from under you. Human Beings cannot interact reasonably, sensibly and peacefully on that sort of basis, can they? No-one would know where they stood, would they? And, that's the point. That's precisely why you never know where you really stand. Because you don't know the basics of how Contracts work. You assume you must do what you are told. And you do. And that results in not knowing where you stand. If your Common Sense tells you something is wrong, then it is telling you the truth. Something is wrong (very wrong!). Hopefully (as I keep saying) by the time you have read this book, you will know exactly what to do about it.
51
Freedom Is More Than Just A Seven-Letter Word
Chapter 7: Honour, Dishonour & Noticing
I
t all comes down to this. In the Chapter on Taking I explained that there is no dishonour in doing that in order to survive in reasonable comfort. Dishonour comes from just being thoroughly greedy. On a day-to-day basis there is more than that, if you decide you want to do something, as most people are doing all the time. If you feel that what you want to do affects no-one else at all, then you just do it. I feel like making a cup of tea. So I just do it. I don't ask anyone else. But there are many things that could easily affect someone else. And, I would guess, we would all think it reasonable to be a little bit more cautious in those circumstances. After all, we don't want repercussions, do we? So how do you go about that? How do you do something honourably? The answer is to give anyone who may be affected some notice. In other words you send them a Notice. (You 'Notice' them). Well, that's OK so far. You can write down what you plan to do, explaining it in a letter. And send it to whomsoever you feel may be affected by your plan. And you tell them, in your letter: “Please let me know if you object, giving me your reasons. Thank you very much”. And then, if you receive objections, you negotiate amicably, to arrive at an arrangement that is acceptable to all. Well, that's easy enough, isn't it? No? It's not that easy? What happens if - as normal they ignore you? So you don't receive any objections, and you just go ahead, and then they object!?
52
Honour, Dishonour & Noticing Ahh! Problem! Well, this can be taken care of, with honour. What you do, within the Notice you send, is to explain that you are going to assume a reasonable time to receive objections. Quite often this is 14 days, but it can be longer or shorter depending on how you feel. You can choose the period, of course, but it is only honourable to be reasonable. You say that, if you don't hear back after the time period has elapsed, then you have the Right to assume they don't object. As a Human Being you do have that Natural, Inalienable, Right. If you do not get any response to your Notice, within the time period you have stated, then you have the right to assume 'acquiescence'. In other words 'tacit consent' to your plan. (It is always a good idea to send your Notice by Registered Post, although the so-called 'Legal Profession', and most Officious Bodies, employ a rule that says: “A letter sent with a First Class stamp affixed is good enough for service to be assumed”. Quite how they think they can get away with that is totally beyond me. But then, as I said in the Chapter discussing Legalese, the 'legal world' is an illusory world, devoid of any rationality at all). You can also send a reminder, giving a time period extension. This would be looked upon more favourably as more honourable, however (in my experience) a response is still unlikely, if you didn't get one from the original Notice. This is generally because most people don't understand what 'being honourable' is all about. The assumption is that, if they need to object, they can do that if you go ahead. Wrong! Once you have Noticed them lawfully, they no longer have any power of objection. Of course, you need to know that yourself, and to stand on it. You may receive very intimidating letters from someone's
53
Freedom Is More Than Just A Seven-Letter Word Solicitors. You simply need to write the appropriate reply. The reply should point out that you have acted honourably, and supplied due Notice. (You would send them a copy of your original Notice). You point out that you allowed for objections, and received none in the set timescale. You then point out that you have obtained, by these honourable actions on your part: “Permanent and irrevocable lawful estoppel by acquiescence”. That shuts them up. (Well, it would shut most people up, wouldn't it? Well, I think it would make anyone blink quite a few times, and take a few sharp intakes of breath, at the very least). Bear in mind a Solicitor will know what 'estoppel' means. He or she won't know very much, but they will know that. It is a lawful 'gag'. An injunction if you will. One that you can create for yourself. It is designed to say: “Look! Enough is enough! This cannot go on forever. There has to be a cut-off, and this is it! The toing and fro-ing stops here. The buck stops here. No more! Cease! Desist! I have acted honourably, and you/your Client have not. The Law says so. So you can sod off, and you know you can”. Yes, it shuts them up all right. And. They. Do. Not. Like. It. Up 'em! As a sting in the tail, you can Notice the Solicitor that further correspondence with him or her in the matter will be charged at £500 (or £500,000 if you like … anything you like … you set the rate) per letter. They do that, and so can you. You can do this to anyone. (Debt Collecting Agencies are good ones to be on the receiving end of this sort of thing, as we will see later) It's all just Common Sense; So don't be surprised if 'the line suddenly goes dead'. Long Live Lawful Rebellion!
54
Societies & Statutes
Chapter 8: Societies & Statutes
I
referred to Statutes in the Chapter on Legalese. Now I come to explain them in more detail. We are told we live in a society. I stress: “We are told that”. And noone argues because they assume they know what it means. But - just a minute! Hold on there! There are things called 'societies' that you don't live in. The Law Society, for example. Do you live in The Law Society? I doubt it. Really 'live in' should be: “Am an accredited Member of”, because Societies have Memberships, don't they? Well, yes they do. Societies are actually defined in a number of ways. Firstly a Name, secondly a Mission Statement, thirdly a Set of Society Rules, and lastly a Membership. Here's Chambers Online (wrong again!): society noun (societies) 1 humankind as a whole, or a part of it such as one nation, considered as a single community. 2 a division of humankind with common characteristics, eg of nationality, race or religion. 3 an organized group or association, meeting to share a common interest or activity o I'm a member of the gliding society. 4 a the rich and fashionable section of the upper class; b the social scene of this class section; c as adj o a society wedding. 5 formal company o He prefers the society of women. 6 ecol a small plant community within a larger group. (1) & (2) conflict, logically, with (3), (4), (5) and (6). That's why it's wrong. (3) is basically what 'a Society' is, in fact. The essential point being the Membership aspect. Societies need to be joined. Members have to apply for Membership, and be accepted as Members.
55
Freedom Is More Than Just A Seven-Letter Word Get the idea? When did you apply for Membership of the Human Species? No, the Human Species is not 'a Society'. It is 'Mankind', or 'the Human Species' or 'Homo Sapiens' … make your choice … but 'a Society' it is not! And don't let them fool you that it is. Even if they manage to do that, don't forget the other thing about Societies. You apply for Membership because you feel the Mission Statement is something you support. And you want to help. But - if the Society starts off down a road you don't agree with - you can always resign! If the Human Species is 'a Society' … how can you resign? Death is the only obvious resignation, but I think that's just a little drastic, myself. Personally I go for: “'Scuse me! I was never asked whether or not I wanted to join. I don't, therefore, consider I have joined … whatever anyone else may think. I consider I have been thoroughly deceived, throughout my entire life. I don't need to submit my resignation, because I was only joined as a Member on someone else's assumption in the first place. And that doesn't count, as far as I'm concerned”. Now, a Statute is defined as 'A legislated rule of a Society'. So how can a Statute apply to you, if you are not a Member of the Society? Answer: It can't. What is happening here resonates back with the business of 'someone making promises on someone else's behalf'. No can do. No way, Jose! You might be finding this all a bit tricky, but hold on tight. An explanation is looming on the horizon. In fact it is getting closer as you read. It might, just might, make you stand up, rush to the door, open it, run into the middle of the road, and shout (at the top of your voice): “Halley-bloody-loo-yah!”
56
Societies & Statutes This is the missing piece of the jigsaw: The United Kingdom is a Society. So is the united States of America. And so are most of (what we call) 'countries' on this planet. We call them Countries. Because we never knew any different. However a very long time ago, the Countries, the Nations, were re-organised into CORPORATIONS, for the convenience of the Global Elite. They are listed on Dun & Bradstreet. On said website you can obtain Credit Reports on them. Everything is CORPORATONS. The Ministry of Justice is a CORPORATION, HM Treasury is a CORPORATION. The Police Force is a CORPORATION. (The UK Police have no more authority than Securicor. Or Group4). When the Police make an arrest, it has the authority of a Citizen’s Arrest. And nothing more. A Citizen’s Arrest backed up with ‘numbers’, ‘muscle’ and ‘technology’. But a Citizen’s Arrest, all the same. We pay them to protect us, using ‘numbers’, ‘muscle’ and ‘technology’, to make Citizen’s Arrests. That’s their job. That’s what they swear to do by their Oaths of Service. That’s all one set of Human Beings could do … to other Human Beings. If ‘all are equal’ (under the Law), what else could there ever be? Even the British Labour Party is the Trading Name of a CORPORATION called 'ALASTAIR DARLING, MP' (at the time of writing). Also note that there is another CORPORATION, called 'MEMBERS OF PARLIAMENT', and yet another called 'HM QUEEN ELIZABETH II' Getting the idea? So, what does this mean? It means that Statutes passed by a CORPORATION called 'MEMBERS OF PARLIAMENT' are the 'legislated rules' of the CORPORATION known as 'THE UNITED KINGDOM CORPORATION'. They are the Company Policy of the CORPORATION known as 'THE UNITED KINGDOM CORPORATION'.
57
Freedom Is More Than Just A Seven-Letter Word And, if you don't work for that CORPORATION - if you are not a Member (i.e. employee) of that CORPORATION, then the 'legislated rules' don't apply to you. I'll repeat this, in order to drive it home. Statutes do not apply to you, unless you are a Member of a CORPORATION called 'THE UNITED KINGDOM CORPORATION'. (These legislated rules being created by the sub-CORPORATION, designed for that purpose, called 'MEMBERS OF PARLIAMENT'. Are you a Member of THE UNITED KINGDOM CORPORATION? When did you apply? Was your Membership request accepted? The answer is: Your parents applied when you were born. Because they Registered your birth. And, in doing so, a Legal Fiction Person was automatically created for you as a Member of THE UNITED KINGDOM CORPORATION. Legal Fiction Persons are described in their own Chapter. However, it is very doubtful that your parents realised what they were actually doing at the time, and thought they were under an obligation to do what they did. In the same way that you may very well have done the same thing in the case of your own children. No recriminations, therefore. And no recriminations really necessary - for the simple reason that, Common Sense must tell you, Full Disclosure never occurred at the time - otherwise no Registrations would (I think it can be reasonably assumed) ever have occurred. No-one in their right mind, appraised of all the facts, would willingly hand over their newborn to become an employee of a massive conglomerate CORPORATION. Any assumed Contract, between your parents and that CORPORATION is null & void (in Law), due to lack of Full Disclosure, lack of Equal Consideration, and lack of Intent to Contract.
58
Societies & Statutes Bingo! You are free, because you say you are free! All you have to do is to remember: The Organic Robots haven't a clue about all this, and they have loads of 'numbers' and loads of 'muscle'. They have brawn, but no brains. On the other hand you will tend to be dealing with only one or two at any given time. Consequently the best thing to do is to tie them up in knots ... before they get the chance to reach for the 'muscle'.
59
Freedom Is More Than Just A Seven-Letter Word
Chapter 9: Common Law, The Law-of-the-Land
N
ow we are cooking on gas! This is where it all starts and it all ends. What is Common Law? Well it really doesn't matter what any dictionary says. However let's have a quick look at what Osborn's Concise Law Dictionary (10th Edition) says: “That part of the law of England formulated, developed and administered by the old common law courts based originally on the common customs of the country, and unwritten. It is opposed to equity (the body of rules administered by the Court of Chancery); to statute law (the law laid down in Acts of Parliament); to special law (the law administered in special courts such as ecclesiastical law and the law merchant); and to the civil law (the law of Rome). It is "the commonsense of the community, crystalised and formulated by our forefathers". It is not local law, nor the result of legislation”. That's as good a definition as any. Because, in short, Common Law 'is'. It just 'is'. It is there. No ducking. No diving. No weaving. No way out. Applicable to all. From the highest to the most lowly. That's what the definition says. But then, who wants a way out? Common Law (commonsense) says the way to live peacefully is to: 1) Not breach the peace; 2) Cause no-one else any harm; 3) Cause no-one else any loss; 4) Not use mischief in your promises and agreements. Personally speaking, I have no problem whatsoever with that. In point of fact I fully welcome it as, I submit,
60
Common Law, The Law-of-the-Land so would any sane, reasonable, and responsible Human Being. Common Law is the Law-of-the-Land. It is the Law that has come about by means of the customs & traditions of Land-Dwellers. And, the point is, Parliament has absolutely no say in Common Law. It is there, and they cannot touch it. In point of fact, Parliament (and Congress) is actually bound by it. Just like everyone else. (Not that they realise that, of course. One of the biggest ‘upsets’ on the horizon will come when enough people realise this, and bring them to book for their gross negligence). The only 'law' that Parliament can create (since the Law-of-the-Land has already been created) is the Law-ofWaters. Hence Statutes are the Law-of-Waters. And Statutes need your consent, before they can be applied to you, if you are located on dry land. In this case you need to become a Member of the UNITED KINGDOM CORPORATION, and for Legalese Fictional purposes actually be prepared to be considered as 'a ship on the ocean'. There is more detail about this in the Chapter on the Law-of-Waters, which has its own Chapter in this book. Common Law = Common Sense. It has been developed over centuries, within Case Law, to have - by now - squeezed just about every drop of justice out of just about every conceivable, fundamental, situation where Human Beings are involved and interact. Advances in technology are irrelevant. Common Law rests entirely on 'the Human Condition'. Has one individual behaved honourably, or not? That sort of thing. It is based fair and square on the 'customs & traditions' from the ancient past. Customs & traditions that were evolved, in a codified manner, so as to create peaceful co-existence all round. Just look at the principles, above. What else is necessary? Answer: Nothing. Stick to those principles, and nothing else is necessary.
61
Freedom Is More Than Just A Seven-Letter Word It has been said: “Look into your heart. Use your Common Sense to know what is right and what is wrong. If what you want to do is fair, and just, then you can do it”. No amount of Common Law deviates from these principles. Only legislated Statutes aka Company Policy of THE UNITED KINGDOM CORPORATION or THE UNITED STATES OF AMERICA CORPORATION (etc.), deviate from these principles. Any deviation is null and void. But you have to say so. You have to understand what is happening, and to firmly, and politely, stand your ground. The Examples, in the Appendices of this book, indicate ways of doing that. I wrote about Notices (there is a Chapter on them). And how you can 'put someone on Notice about your intentions'. And how you can create an estoppel. What you are actually doing is making Common Law. If you take a Solemn Oath, you are making Common Law. If you create an Affidavit, you are making Common Law. Because, in either case, you are stating Your Truth as you see it. And you have the right to state Your Truth, as you see it. That's why Common Law is so ephemeral. It's everywhere. Provided you do not deviate from the principles - provided that you act with honour - you are making Your Own Common Law! You are saying: “This is My Custom. This is My Tradition. And I will stick to these peaceful principles”. Common Sense … yet again! After all, what is the Law, anyway? How does it come about? Consensus facit legem. Consent makes the Law. The consent of the overwhelming majority, whose one primary desire is to live their lives in peace. In peaceful co-existence with everyone else.
62
Common Law, The Law-of-the-Land Free to do whatever it is they choose to do, provided they do not adversely affect anyone else. Free to travel at will. Free to express opinions. Free to exchange. And so on. Freedom from imposed fictions & illusions. Freedom from tyranny. Freedom from the domination of the many by the few. And those Common Sense desires were codified in Common Law, as a protection of it. And this was done many centuries ago. It formed the basis of the Magna Carta, the US Constitution, the French Constitution, and so on. It actually forms the basis of every Constitution ever written. (Any Constitution worth its salt, that is). There is an Appendix dedicated to the Magna Carta 1215, and it is well worth reading. So the ideas are not new. In point of fact the ideas are so old, we seem to have forgotten them. It is my sincere hope that this book serves as an appropriate reminder. Do you consent to live in peace? I hope you do, otherwise this book is not for you. Do you consent to pay for the use of your own property, once purchased? Your dwelling (Council Tax), your conveyance (Road Tax), your entertainment (TV Licence)? Bearing in mind, of course, that none of these impositions on your freedom actually fund whatever it is they purport. That, in point of fact, they fund just about everything else besides. Do you consent to aiding & abetting War Crimes? You don’t? Well, in that case there is no Law by Consent. Is there?
63
Freedom Is More Than Just A Seven-Letter Word
Chapter 10: Notices, Invitations & Summonses
I
group these together because they are all, essentially, the same thing. They are 'offers to Contract'. You see, a Summons (for example) is not something that should make your knees go to jelly. A Summons is just a Notice that should be read as: “An invitation to go to a place of business, at a certain time, and on a certain date, in order to be made an offer for a service”. The service in question being the one of 'adjudication'. 'Arbitration' if you want to call it that. And you are perfectly entitled to write back: “No thanks. Your services are not required”. Whaaaaat!?! When you receive a Summons there will be accompanying paperwork. You will be offered the chance to plead guilty or not guilty, to the charge made against you. Actually, as you will see in the appropriate Chapter, the charge is not levelled at you - it is levelled at your Legal Fiction Person. Nevertheless, by pleading guilty or not guilty, you are accepting the service of arbitration that is on offer, and in doing so you are admitting responsibility for your Legal Fiction Person. However if, instead of pleading, you make it quite clear that you are not the Legal Fiction Person, but are actually a living, breathing, Human Being with a soul, and live in the real world of Common Law, then you are perfectly entitled to write back : “No thanks. Your services are not required. Good day”, as I explained, above. You do this in the form of a Notice. Their Summons to you was a Notice. You respond with a Notice of your own. And, in the same way they would have put a timelimit of the Summons (it may very well be the Court Date), then you can put a time-limit, for the Court's response, on your Notice back to them.
64
Notices, Invitations & Summonses You would head your Notice something like: NOTICE OF NON-ACCEPTANCE OF OFFERED SERVICES AND REQUEST FOR CLARIFICATION. You would then write a letter explaining that you are a Human Being, and would they please clarify the situation, because the Summons was addressed to a Legal Fiction Person, which you cannot accept as such, but you wish to know how you, as a Human Being, have dishonoured any lawful obligation on your part. Remember: The charge against your Legal Fiction Person will be based in the fictional and illusory world of Legalese & Statutes. You need them to show which Common Law Principle your Human Self has breached. They will not be able to do this. The Court will probably ignore your Notice, which will place itself (they, themselves) in dishonour. It may be necessary to actually go to the Court, at the date & time of the Hearing, and to point out their own dishonour. Fundamentally by claiming Common Law jurisdiction. All is explained in the Chapter on Courts & Proceedings. It is likely to be a very short Hearing. Probably about a minute or so, before you walk out with an enormous smile on your face. If you do it right. And that means understanding everything in this book.
65
Freedom Is More Than Just A Seven-Letter Word
Chapter 11: Legal Fiction Person
T
he Legal Fiction Person is mentioned frequently in this book. It is one of the basic irrationalities of Legalese. But Legalese exists. Anything to do with the Courts or the Police, in relation to Statutes, is bound up in Legalese. On a practical note it is no good just telling a Solicitor, or a Magistrate or a Judge, or a Policeman that they live in a fictional world of illusion. They do. But their world is so ingrained they will not believe you. They even find it impossible to recognise their own double-think. Of course, one of the most important things about double-think is that you can only do it as long as you can't recognise you are doing it. (In that sense it is self-fulfilling, aka self-supporting) What you need to do is to know the score, and know how to duck. One of the primary components of knowing the score is to know when something that drops on your doormat is addressing you, or your Legal Fiction Person. If it is addressed to you, Your Human Self, then you'll need to deal with it, in order to avoid dishonour. If it is addressed to your Legal Fiction Person, then there are other ways of dealing. Primarily to place a Universe between Your Human Self and your Legal Fiction Person. (Sometimes called: “Tin-plating your own backside”). So, there are three things you need to know: 1. What is a Legal Fiction Person, anyway? 2. How do you recognise your Legal Fiction Person being addressed? 3. How do you tin-plate the backside of Your Human Self?
66
Legal Fiction Person First of all, a Legal Fiction Person is often referred to as a STRAWMAN. The reason for this is that the letter addressed to the STRAWMAN is, actually, clutching at a straw. If you respond as people normally do - because they do not recognise the situation - then the grasp at the straw will succeed. If you respond as explained in this book, the clutch at the straw will come away empty-handed. This is possibly one of the hardest concepts to grasp. The use of the word 'person', in Legalese, is very subtle and very clever. Simply because most Human Beings will consider themselves to be 'a person'. And, of course, in Oxford English, they are. The best analogy I have heard is that the word 'person' comes, originally, from the word 'persona'. And you need to consider what a 'persona' actually is. It is your outward manifestation presented to the 5sense world. It is what you present, as yourself, to the world at any given time. It is very much tied to your personality. (After all, the word 'person' is the stem of the word 'personality'). It can be thought of as a mask. Or an overcoat. One or more you can wear, when circumstances permit. In wet weather your overcoat would need to be a rainproof. In cold weather your overcoat would need to be one that keeps you warm, rather than just rainproof. Do you get the idea? In the circle of your family & friends your persona would generally be friendly and kindly. In the presence of an enemy your persona would be hateful. Your persona depends on the circumstances you are in, at any given time. However you, Your Self, are exactly the same flesh & blood & soul irrespective of the circumstances. You are always the same sovereign Human Being, with a living soul.
67
Freedom Is More Than Just A Seven-Letter Word You are not your persona. You are you. You take on a persona (wear a persona) according to circumstances. You could also think of it as wearing different masks. (By the way, you are not your Name, either. See the Chapter on Names). The clutch at the straw is attempting to make You, Your Self, The Human Being, wear the Legal Fictional Person 'overcoat' or 'mask'. It is necessary to get you to wear this overcoat or mask because that means you accept your role or employment as a Member of THE UNITED KINGDOM CORPORATION, to whom the Company Policy applies. (To whom the Statutes apply). As a free Human Being you can choose to wear this mask, or not. If you understand what is really happening, you would almost certainly not choose to do so. If you don't wear the Legal Fiction Person mask then you are not a Member of THE UNITED KINGDOM CORPORATION, and its rules don't apply to you. Its Company Policy has no force of law upon you. You can just walk away. That's why you are perfectly entitled to say: “No thanks. Your services are not required. Good day”, as I explained in the Chapter on Notices, Invitations & Summonses. So how do you recognise a letter addressed to your Legal Fiction Person? Well, first of all, there is such a thing as a Legal Fiction Status. Or 'Title', such as 'Mr.', 'Mrs.', 'Miss', 'Ms.', and so on. These are fictional titles! They have no meaning at all! They might be considered to be a politeness, but once you recognise what they actually do - they are a long, long, way from being polite. They are a long way from being polite, because they create a Legal Fiction Person. A STRAWMAN. And when present as the first line of the address on a Demand or Summons, etc., they represent an attempt to fraudulently shake you down. To extract money from you, with menaces. And that's not what I call 'polite'.
68
Legal Fiction Person This is the most common way of addressing a Legal Fiction Person. It is generally accompanied by writing all or a part of your name in CAPITALS. Actually a 'Name' is a Legal Fiction as well. In order to be free, you do not have a Name. Instead 'you respond to what you are commonly called'. What 'you are commonly called' can be written by placing colon (“:”) after your Given Names (all Given Names hyphenated together), and then writing your Family Name. This book has been written by Veronica: Chapman (for short) … as commonly called … or Veronica: of the Chapman family (for long). In practice, since this Lawful Rebellion is all so new to the world, and the Organic Robots have yet to come to terms with it, I do accept "Veronica Chapman" as addressing My Human Self. In other words I do not stamp my foot at the missing colon. However I flatly reject 'Ms.' or 'Miss' prepended. That's Legal Fiction Statusville. However perhaps I should point out that this system of writing 'what you are commonly called' - has no 'legal basis’. It is just a convention that has been adopted by those in Lawful Rebellion. Can we do that? Yes … of course we can! Why the hell not? The fact that it has no 'legal basis' is good, because it separates us from the illusory world of Legalese.
69
Freedom Is More Than Just A Seven-Letter Word
Chapter 12: Solicitors, Lawyers & Notaries
W
hat is the first duty of your Legal Representative? To you, the Client? Gosh, no! Wrong! The first duty of a Legal Representative is to the Court. Then to the public. And then to you, the Client. So, if the Court barks, your Legal Representative jumps! What is your relationship to the Court if you are legally represented? You are being re-presented to the Court (represented in Court) as an 'imbecilic child'. It doesn't matter what your actual age is, in years. As far as the Court is concerned you are a 'ward of the Court'. You are considered a 'child', and your Legal Representative is the 'adult' who is looking after you. And you are expected to pay for the privilege of being viewed in this way. Actually, it does all make sense. In the illusory world of Legalese. You are - to all intents and purposes - a noncomprehending creature (a child in essence), and you do need an 'adult' looking after you. An adult who understands Legalese, and therefore what is going on. So, here is yet another reason for, firstly, representing Your Self, and secondly standing on Common Law - thus avoiding any contact with Legalese, and the 'legal' world. And remaining within the real world of Common Sense. Very few, if any, Solicitors and/or Lawyers are prepared to defend you on Common Law principles. They will tell you it is: “Baseless”. That it has: “No legal standing”. Of course it is perfectly true that it: “Has no legal standing”. Absolutely!
70
Solicitors, Lawyers & Notaries But the point is that: “It has LAWFUL standing”, and that always trumps 'legal standing', so it is a zillion miles from 'baseless'. The Court system does not like this. It hates what it calls Litigants-in-Person, because that upsets its apple cart. They. Do. Not. Like. It. Up 'em! How is this derived? Well consider the sections from the Corpus Juris Secundum (C.J.S.) legal encyclopedia, volume 7, section 4, in Figures 1 through 4. To what or whom is an attorney's first duty? See Figure 1. What is the legal relationship between an attorney and his/her client? See Figure 2.
Figure 1: The relationship between Legal Representative & Client
Figure 2: The relationship between You & the Court.
71
Freedom Is More Than Just A Seven-Letter Word
Figure 3: A Ward of the Court.
Figure 4: A Litigant-in-Person. What is a ward of the court? See Figure 3. Do you need to challenge jurisdiction? Better see Figure 4, particularly the part that says: “... because if pleaded by an attorney ...”. It means you accept the jurisdiction of the Court.
72
Veronica’s Very Cunning 2-Step Plan for Freedom
Chapter 13: Veronica's Very Cunning 2-Step Plan for Freedom
I
already mentioned this in the Foreword, but I need to expand upon it. These steps are nothing more than Common Sense. And that is the same as Common Law. And most nations on this planet operate under Common Law as a fundamental basis, particularly those that - historically - were spawned from the British Isles (e.g. the united States of America and Commonwealth countries, left over from the days of the British Empire). Step 1: You are free because you say you are free. Because no-one else will. You have to think free 24/7, be free 24/7 and act free 24/7. If you don't do that, then you are faking it, and playing with fire, and are likely to get your fingers burned.our is contrary to Common Sense and Common Law - and these, therefore, are not only basic crimes, but the only crimes. Those are the basics and, once you understand them, everything else falls naturally into place.
73
Freedom Is More Than Just A Seven-Letter Word In point of fact Common Sense is worldwide ... stemming from humanity itself. The exceptions are strongly religious States who suppress Common Sense with irrational dogma. It is hard to understand how those poor souls can ever be free, but one must, I suppose, never give up hope for them.. The Freedom Movement says: “Step out of being a Mind-Controlled Organic Robot, and start thinking for yourself. Look into your heart. Listen to it. All the answers are there”. And that's all the Freedom Movement says. The rest is just left to your Common Sense. However this does not mean to say you have to take everything on board all at the same time. There is plenty of room for edging your way into Lawful Rebellion. Notice of Understanding and Intent and Claim of Right, and I have included mine in an Appendix. This does not mean I have to immediately execute the Rights I claimed. I can leave them in abeyance for as long as I like. That's entirely my own choice. Just because one may possess a bicycle, doesn't mean one can't go to work in one’s car. (Especially if it is raining). You might find it more effective to simply introduce these ideas to as many friends as possible (rather than anything else), by starting a local group of like-minded
74
Veronica’s Very Cunning 2-Step Plan for Freedom. And you must never let yourself become intimidated by anyone or anything. If you know your Rights (your heart will tell you what they are), you must stand your ground. It does not matter what they say. They are wrong. You must always remain reasonably polite, but firm, and be prepared to 'say it like it is'. All that is really important is to understand the techniques of showing them they are wrong. You'll find those methodologies in the Example Templates, included in an Appendix. This may be difficult for those with partners who are not fully behind you. In such cases it is probably better not to start what cannot be finished.
75
Freedom Is More Than Just A Seven-Letter Word
Chapter 14: The Principles of the Application of Common Law
I
t is imperative that you understand them. They are really not hard, because they are based entirely on the Common Sense of peaceful and equitable coexistence.. Because only a Human being has a Mind with which to devise a claim. It cannot be 'THE COURT', or 'THE CROWN PROSECUTION SERVICE', etc., because these are not Human Beings, and have no Mind with which to devise the claim. Law) Contracts stem from Common Law. Contracts between two Human Beings. And this is the crux of the 'Freeman
76
The Principles of the Application of Common Law business'. And this is why Legalese attempts the subterfuge of defining Partnerships as being equivalent to Human Beings via the Legal Fiction Person construct. Because, for a Contract to be lawfully-binding (enforceable), it must comprise the four components described in the Chapter on Promises & Contracts. The only positive way to avoid entering into a lawfullybinding Contract is to use the Intent component, by stating, up front: “I do not consent” (in front of witnesses). Although a better way, which requires no witnesses, is to state it in a letter.
77
Freedom Is More Than Just A Seven-Letter Word
Chapter 15: Fundamental Established Axioms
T
hese are as simplified as I can make them, based on the work of Robert-Arthur: Menard, MaryElizabeth: Croft and (to some extent Winston Shrout and Irene-Maus: Gravenhorst). A good 80% of it is their work, tweaked a bit by re-writing, and removing the unnecessary 'God' bits - thereby reducing it to absolute fundamentals. 1) 'Lawful' is what it is all about. 'Lawful' .vs. 'unlawful'. Never get trapped into discussing 'legal'/'illegal'. For example, if you receive back a response, which does not address the substance of your letter, then invariably it will be attempting to inform you of some 'statutory obligation'. Some 'legal obligation' you are assumed to have. (The Respondent will be acting by rote, of course. Because that is the only world inhabited by Organic Robots). You have no statutory or legal obligations, unless you consent. Therefore it is possible to respond along the following lines: “If your counsel has been advising you on the basis of the fictional world of Legalese and Statutes, then I suggest that you should consider sacking him or her for the perpetration of a fraud. For the simple reason that they are being grossly negligent by ignoring the real world of Common Law, as you will discover quite shortly, should you continue to pursue this matter based in his or her advice. “I hereby give you Notice that further correspondence in this matter will be charged at £500 per letter from me. If your counsel advises you that I cannot do that, then that would support my contention in the previous paragraph. “(Ask him if he does it? And ask him what gives him the right to do it. The answer is: Common Law. Then get him or her to re-advise you accordingly. To advise you, for example, that you need to respond in substance, in order to avoid dishonour. And make sure he or she
78
Fundamental Established Axioms advises you that there is such a thing as a Counterclaim. For harassment. And that I'm not afraid to use it)” … is the sort of thing. The Solicitor or Lawyer would then respond to the Client: “Well, I suppose, they may have a point. It might, I suppose, be an idea to humour them? Just in case? I have heard a bit about Common Law, but I'm not terribly au fait with that side of things”. Send them a copy of this book(?)”. A good example of this is Peace Officers. If you can empower your representatives (your Government) to create a Peace Force (they would call it a Police Force), then you must have the power to create a Peace Force of your own. After all, where does a People's Government's power come from - if not from the People? Axiom 3, above,
79
Freedom Is More Than Just A Seven-Letter Word). Not convinced? Perhaps you can think of it this way: What is the benefit of registering anything? Oh! It makes it 'official'! But what, precisely, does that mean? Does registering: 1. Alter the size of anything? 2. Alter the shape of anything? 3. Alter the colour of anything? 4. Alter the value of anything? No? Well … what does 'registration' do then? What does 'making it official' do? For you, I mean. For you, the 'registrant'? Not sure? Well, it must do something, because it is - apparently - so important. Surely there is only one possible answer. 'Registering' transfers Ownership. Away from you, and to whoever accepts the registration. What else could it possibly do? I repeat: “What else could it possibly do?” (Please don’t say: “I don’t know”, because you know as much as anyone else). What are your benefits from having 'registered something'? The only one I can think of is 'freedom from undue & unnecessary harassment'. But that's hardly a benefit, surely? In the case of cars, for example, the
80
Fundamental Established Axioms 'benefit of registering your car is that you get regular demands for the payment of Road Tax - because you are the Keeper (check your V5, it calls you the Keeper), and no longer the Owner'. But it is still up to you to pay for everything, including the MOT and all servicing costs. This is a 'benefit'? If this is considered a 'benefit', then it sounds to me like someone is using the wrong dictionary. What is the benefit of registering a child? So that it can be pumped full of toxic vaccinations while it cannot in any way defend itself? At the time when it must trust you most? (Check the ingredients of vaccines, they will make your hair stand on end. Vaccinations do not work. They are nothing more than toxic). Registration so your child can be 'treated' by a General Practitioner who is blindly following the rules laid down by the British Medical Association to create nothing more than 'consensus medicine'? Where each one does what all the others do - rightly or wrongly - such that none of them can be picked out and sued for harmful practices? Meanwhile there are Holistic Practitioners who will offer actual cures (without side effects, and as opposed to just 'treatments'). If any of this is news to you, check out the WebSite of the Nurses Movement for Responsibility in Medicine () for more information. And then, of course, there is the 'benefit' of indoctrination from the age of 5 years. Sorry, I meant 'education'. Not indoctrination? Well, how much of the contents of this book did you learn at school? Did you learn about the Grand Deceptions of Money, Legalese & Religion at school? Or did they just train you to be nothing more than a compliant workhorse, as they did me? After finishing (let's say) 'schooling', your child will go out to work, trailing his or her National Insurance Number all over the place. This allows your child to be taxed to the hilt. Which is all a complete fraud as the Chapters on Money and Mass Mind Control and Enslavement fully explain.
81
Freedom Is More Than Just A Seven-Letter Word Registration of cars and children have benefits? Really? Registration of your car means the Government owns your car, and you are the Keeper. And you have all the expenses. Registration of your child means the Government owns your child, and you are the Guardian. And you have all the expenses. (But yes, you still get all the love … unless they decide to take your child away from you … which they can, and do, sometimes on the slightest pretext). Registration of your house means the Government owns your house, and you are the Occupier. And you have all the expenses. The Government can take back your house if you don't leave it to a next of kin. The Government doesn't care. It will get it one day. In the meantime you fund all the upkeep. 7) When parts of the Magna Carta were 'transferred' into Statutes what was actually happening was that fundamental Rights were being transferred into revocable privileges. Thus they were being watered down. Diffused. Being rendered powerless. However the Magna Carta Statute did not revoke the Magna Carta Peace Treaty, signed by John with the Royal Seal in 1215. A Statute cannot do that. Thus whatever parts were left out of the Magna Carta Statute (notably Article 61, creating the right & duty of Lawful Rebellion), and whatever parts of the Magna Carta Statute have been repealed, the entire original Magna Carta Peace Treaty 1215 stands in perpetuity as an irrevocable foundation of the Common Law.) Law can give rise to a fiction, but a fiction cannot give rise to Law. Consequently a Legal Fiction called THE GOVERNMENT has no power to make Law. It is, in point of fact, bound by Law (like everyone else, and
82
Fundamental Established Axioms including all other Legal Fictions). PARLIAMENT is another Legal Fiction entity. Statutes created by Parliament are not, therefore, the Law. They are 'legislated rules for a Society' and only applicable to few of those left (unless you insist that the Court operates de jure, by demanding a Trial by Jury. But they will attempt to resist that with every fibre in their 'corporate', soulless, 'bodies'). Courts de jure only tend to exist as the Higher Courts, where (for example) murder trials take place. Nevertheless the Magna Carta gives everyone the Right to Trial By Jury – or: “ ... by the law-of-the-Land ...” which is Common Law, of course.,
83
Freedom Is More Than Just A Seven-Letter Wordbound to follow them. Different Societies can exist, having their own unique set of rules. One way of 'choking' the action of a Court de facto is to claim Membership of a Society that only exists in Common Law jurisdiction. The World Freeman Society (Google it) has been set up precisely for this purpose. 14) Contractual Obligation. For any Contract to be lawful it must comprise the following: A) Full Disclosure by both Parties. Neither Party can later claim 'you should have known' if it was not specifically declared at the time of making the Contract. B) Equal Considerations offered by both Parties, this being the subject of the exchange. It must be a sum of money, or an item of value, and must come from a Party’s own resources. Both Parties agree that their Consideration is worth (to them) the other Party's Consideration. The Considerations, once agreed, must be fixed – otherwise they cannot remain 'equal'. C) Lawful Terms & Conditions for the Contract, to which both Parties agree. These should rest entirely on Common Law. D) Manifestations of Intent by both Parties, such as 'wet' (handwritten) signatures, or some conduct or performance which shows 'Intent to Contract'. Even though businesses and officials act as though there is a lawful contract in place, 99 times out of 100 these rules have not been followed. (Maybe it is 999 times out of 1,000 - or even more!). Standing on these four rules, requesting Proofs, is the simplest way of stalemating just about every action that may be taken against you. (See Axiom 16, below)
84
Fundamental Established Axioms 15. Agreement to Pay. Consequent to Axiom 14, above, all 'payment demands', that could result in court actions against you, can be stopped by 'conditionally agreeing to pay the sum demanded', subject to Proofs that the four Conditional Agreement to Pay, subject to the Proofs being presented. The Court should consider that any further action is 'frivolous', i.e. a complete waste of its time, since there is no Controversy on which it can adjudicate. (The Court may even consider whoever applied to be in contempt). (See Axiom 16, below) 16. “I feel 'guilty', because I owe the money. I took it and spent it”., they took a risk by offering it back to you, and reckoned on being paid twice or even more, via the Interest. Are you just beginning to feel slightly less sympathetic? If not, I don't
85
Freedom Is More Than Just A Seven-Letter Word know what else to say, except maybe to Google Money as Debt, the superb animation by Paul Gringnon, which explains the entire process step by step, and how it all came about, historically). always remains your Responsibility. 18. A Solicitor or Lawyer has his or her first duty to the Court & the public, not to the Client. In this situation, in Court, they are considered to be an 'adult', and the Client is considered to be 'a ward of the Court'. A ward of the Court is considered to be a 'noncomprehending child'. With good reason, if you think about it. Actually the Client's status is, in essence, that of an 'imbecilic child'. And, furthermore, because the first duty is to the Court, and therefore its jurisdiction, the 'imbecilic child' has immediately tacitly consented to Statute Law jurisdiction in the Legalese world of illusion. (Unless you get this totally straight with the Solicitor or Lawyer at the outset. However you will go a long way before finding a compliant one).
86
Signatures
Chapter 16: Signatures
D
o not sign anything unless you intend to Contract. This sounds obvious but it is not obvious. Not signing anything includes letters of rebuttal.
The reason is simple. In this day and age counterfeiting your Signature is perfectly possible. And it happens. And has happened. Obviously the counterfeiting mechanism will not be perfect, but a Human's Signature Mark varies over time. It is one thing to say, in Court: “That signature is a forgery”, but it is another thing to prove it, unless you are prepared to pay the fees of a Handwriting Expert. It may be that you can show, by means of other correspondence, that you never had any intention to Contract. A Court may, or may not, accept this reasoning. The best thing to do is to not let anyone get a specimen of your Signature. There are a number of possible tricks. You could get a friend to sign the bottom of a document. This would be a sure way of proving a forgery and consequent perjury. Another way suggested is to affix a stamp, and sign over the top of it, thereby making it very hard to extract that section of your actual Signature. Another possibility is to print a complicated graphic as a Signature Box, and make your mark inside it. Another possibility is to use a Rubber Stamp with some miscellaneous pattern on it. Finally it is possible to simply not sign it.
87
Freedom Is More Than Just A Seven-Letter Word
Chapter 17: Courts & Proceedings
B
efore going any further it is necessary to explain the Courts. There are two kinds, known as a 'Court de jure' and a 'Court de facto'. 'De jure' means 'of Justice', thus a Court de jure is a Court of Justice. 'De facto' means 'of fact'. It is. It just 'the 'de jure' and, as I said, they are rarely directed properly. Generally speaking you will receive Summonses for Courts de facto. You will get very little 'justice'.
88
Courts & Proceedings) 'adjudicators' sitting as a 'panel', or 'bench'.).
89
Freedom Is More Than Just A Seven-Letter Word.
90
Courts & Proceedings (* 'LAWFULLY 'a”.
91
Freedom Is More Than Just A Seven-Letter Word Yes, there is a 'wearing 'totally
92
Courts & Proceedings”
93
Freedom Is More Than Just A Seven-Letter Word 'falsethe”
94
Courts & Proceedings .
95
Freedom Is More Than Just A Seven-Letter Word Furthermore, whenever asked to give or confirm your Name and Date of Birth you are expressing hearsay in Court. You only have your parent's and Birth Certificate's word for those two things. You only 'know' 'designated place' and 'identify themselves correctly'? The answers are, of course, that the 'designated place' is on board their 'ship'. And 'correct identification' means 'accepting
96
Courts & Proceedings present. After a short retirement (usually) the Magistrates and the Clerk return and say: “Liable person not present”. This is really good, isn't it? So much for 'justice', then! Before the Hearing starts, the 'person' is already condemned as 'liable'! However this is a bit of a double-whammy - back on the Clerk of the Court. Because, if one is sitting in the Public Gallery, then one is certainly 'present in the room'. Not present on the 'ship', 'might is right'. Is that not so? What
97
Freedom Is More Than Just A Seven-Letter Word other reason could you possibly have? I'm not causing any violence nor breaching any peace. The fact is you are simply reaching for 'muscle', 'powers that be' do not give up without a fight. In the front line are the Organic Robots who simply 'operate by the book'. So here are some examples of how to stop Kangaroo Courts. Letters written to Organic Robots, based on the Templates included in the Appendix, are 'outside the realm of their Operation Manuals'. Therefore they simply do not know what to do with your letters. So they ignore them. In fact you'll discover, as you try Lawful Rebellion, you will either be ignored, or responded to by repetition of your so-called 'Statutory obligations'. The point is here that by operating on the Freeman Principles, as described in this book, you will have built up all the evidence you actually need … IN LAW. The trouble is that, when (eventually) 'invited 'LEGAL training', and is often referred to as "The Magistrate's Legal Advisor". However he or she will most probably have long forgotten any 'LAWFUL training' (if s/he ever had any) - in the desperate struggle to 'slap down as many miscreants as possible' via the Conveyor Belt of the Magistrates Court. So it would be possible to ask:
98
Courts & Proceedings “Yes, I can see you have a Legal Advisor, but who is your LAWFUL Advisor?” A real example is that, of 178 Summonses issued for one day, only 3 people turned up for their Hearing. And this is what 'they' expect. And ‘they’ expect to deal with the 175 (who were hoping that it would 'they' 'identify 'courtesy'
99
Freedom Is More Than Just A Seven-Letter Word XXX … and not 'Mr. 'religion'. (One thing to try … which has not been tried … is to say: “My religion is very personal to me, and it is my business, not yours”. This would tend to give them a problem). However, the 'biggie'!)
100
Courts & Proceedings They will overcome this by agreeing that 'the 'process (crossexamine) 'listening'!).
101
Freedom Is More Than Just A Seven-Letter Word
Chapter 18: Liability & The Ultimate Sanctions
T
it”.
he vast majority of 'offences' (they are not actually 'offences', but ‘Statute violations’, of course) involve 'money'. Specifically: “The non-payment of
The Chapter on Money explains how it does not exist in reality, and is nothing more than a Belief System. For this reason the most that can ever be extracted from you is 'belief in something you value', in other words your Credit Rating, or your Liberty. While the Monetary System is king, a Credit Rating can be assumed to have value. However, I have to say that, in my own case, I paid off my Credit Card in the early 1980s (ACCESS Card, if you can remember them), and cut it up. I did this because I realised I was on a hiding to nothing. And I've never used a Credit Card since (even though I've been constantly bombarded with junk mail offering them to me). But that's me. However, it does explain why I, personally, have no idea what my Credit Rating is, and I really don't care. It's not something I consider to have any value. If I want something, I wait until I can afford it, and buy it. It is as simple as that. But that did not stop the Inland Revenue from placing me in (what they called) 'Notional Debt', and proceeding against me into bankruptcy (because I did not consider I owed them anything). And it did not stop the Margaret Thatcher Government from proceeding against me, and placing me in prison for refusing to pay her Poll Tax. So I write all this on the basis of two personal experiences. Firstly, being made bankrupt and losing any Credit Rating I had. And secondly, spending time in prison and losing my Liberty for a while. And, having actually experienced all that, I firmly believe NONE of it would have happened if I
102
Liability & The Ultimate Sanctions had known then, what I know now: The Freeman Principles. I am absolutely positive I could have stopped both actions against me, dead in their tracks. I know what was said at the time, because I was there. And I now know what I could have said, but didn't entirely due to lack of knowledge. Even without this knowledge I did – in point of fact – have two ‘successes’. Guided purely by Common Sense I fought both by simply not co-operating. The result was that the Local Council never bothered me again (because, I presume, they had come to realise it wasn’t worth the effort … after all I did tell them that on a number of occasions), and the Inland Revenue never bothered me again, for (I assume) the same, or similar, reason. Which proves, to me at least, that when they operate by rote they may win the battle, but they don’t win the war. However, any procedure against you is always in two stages: 1. To establish Liability, and make a corresponding Court Order against you for the amount demanded; 2. Failure to pay the amount demanded, within the stated timescale, invokes a new Summons to demand that you be placed into bankruptcy, or into prison. Which of these demands is made, depends on the circumstances (the Statutes). In the case of Council Tax, for example, they will demand a prison sentence for non-payment. The sanction being to take away your Liberty. This is because it would be pointless making you bankrupt ... because they would have no means of making any further demands on you until the bankruptcy expires. (And we can’t have that, can we!). Until this subsequent Hearing has taken place no prison sentence has been passed on you, and so there is no way you could actually be carted off to prison. There has to be a sentence passed before they can do that. In this case, which is a Civil Offence, you can extricate yourself from the whole situation at any time by paying
103
Freedom Is More Than Just A Seven-Letter Word up. Even if you get as far as prison. They will take the length of the sentence, and divide it into the amount, and come up with 'an amount per day incarcerated'. As each incarcerated day passes, that amount is written off. The remainder will always buy you out. On the last day of your sentence it has all been written off, and you are free once more. (There is no parole for a Civil Offence). In the case of failure to pay, for example, Income Tax, the likelihood is that they would go for bankruptcy. The idea being that they can take your house, to pay off their 'Notional Debt' ('notional', because 'money' is an illusion). They would tend not to worry about the fact that they could not grab anything from you for a while (i.e. until the bankruptcy has been discharged), on the basis of creaming as much as possible this one-time. 'Long-sightedness' is not one of their stronger points. (Otherwise they wouldn’t be doing their job in the first place!). If you co-operate with the Official Deceiver (Receiver), then a bankruptcy is auto-discharged after 3 years. (But they won’t bother to tell you, quite probably). (It may even be 2 years by now). However, the overall point here is the Second Phase. Either the Incarceration Petition or the Bankruptcy Petition. Nothing can happen to you until this Second Phase has been successfully accomplished by whomsoever is making the demand. All too often people do not realise what is actually going on, and what is happening, and that there are these two, distinct, phases. And that both can be challenged by Common Law jurisdiction. If the Liability Petition is dismissed because the Court is 'de facto', and does not have Common law jurisdiction, then the Ultimate Sanction Phase cannot occur.
104
The Law-of-Waters
Chapter 19: The Law-of-Waters
I
n the Chapter on Common Law it was explained that Common Law is the Law-of-the-Land. It is the only Law-of-the-Land. And the only Law that needs to be obeyed on dry land. It fully defines peaceful co-existence within its principles. Nothing can go wrong where everyone adheres to the Law-of-the-Land. Nothing else is necessary. Adherence to Common Law gives everyone total freedom, provided they remain honourable, and is capable of coming down like a ton of bricks on anyone who deviates from honourable, peaceful, co-existence. So, what the hell has Parliament been doing, then? Since it was all sorted out in the 11th, 12th and 13th centuries? What a bloody good question! The answer is that, driven by the Banksters, it has been very slowly, and in the most subtle manner, ingraining the Grand Deceptions. It has been doing this by fully-utilising the gullible nature of Mankind in general. It could be argued that while the Law-of-the-Land sorts out what happens on dry land, but what happens on water? Don't we need a Law-of-Waters, to take account of the high seas? Common Sense should tell anyone that the answer is possibly: “No”. That the Common Law still works perfectly well on the high seas, because it fundamentally addresses the Human Condition (honour, dishonour, etc) and Humans on the high seas should still remain honourable. One the other hand there are such things a Pirates, and Salvage, and also different Cultures, and so on. And you can't reasonably expect Pirates to be honourable, and you can't expect to impose your own Law-of-theLand on to some other culture's Law-of-their-Land. There
105
Freedom Is More Than Just A Seven-Letter Word will be remarkable similarities, but there may be Religious differences (which they have to contend with, poor souls, and you do not). So it is reasonable to assume that a Law-of-Waters which needs to be fully International, contending with the aspirations of all different Cultures - is something that needs to be created and mutually agreed. Sure, that's all very fine & dandy. It's fine to create some Law applicable on waters … but to impose that same Law on dry land? Oh, come on! No-one would fall for that one, would they? Errr … well … yes, by subterfuge everyone fell for that one, and can be most vociferous in supporting the irrationality! Try explaining to a Policeman that he or she swore, on Oath, to uphold the Law-of-the-Land. And, by bleating on about Statutes, he or she is imposing the Law-of-Waters on dry land. The fact that the Police have a duty to understand this, and are grossly negligent if they do not - actually committing serious crimes if they do not - is something that passes completely under their radar. However before you, the Reader, get the impression that I have an axe to grind with regard to Policemen, it might be an idea to correct that assumption. When in the course of their duties, they uphold the Law-of-the-Land, in accordance with their Oath of Service, they are acting as Peace Officers. In that role I have as much admiration and respect for them as anyone else. Someone needs to do that job. Someone, some group, some force, needs to impose the Principles of Common Law on those who choose to act outside its boundaries. This is for my protection, as well as everyone else. It is only when they exceed their jurisdiction, and the authority vested in them via their Oath of Service, that I (and most, by Common Sense, I think) have a problem with the way they act. Just the mere act of stopping and questioning someone, without lawful excuse, is vastly exceeding their Common Law jurisdiction, and that is
106
The Law-of-Waters without considering their involvement in traffic (for example). On the other hand they do things that I would not wish to do. Picking up torn limbs resulting from road traffic accidents, for example. I salute them, and all the Emergency Services, in that respect. Acting as Peace Officers is what they are paid to do. I have no problem with that, and welcome it. Acting as Company Policy Enforcement Officers (Policymen), enforcing the Law-of-Waters on dry land, and not realising it, and making absolutely no attempt to realise it, is where they have no authority, no jurisdiction, and are behaving in a grossly negligent manner. That's where the problem arises for me. And furthermore I suggest that, deep down within their Common Sense, most people feel the same, without actually being able to put their finger on it. So now you know. When acting as Policymen, they are enforcing the Company Rules of a Company you did not even realise you were working for. No wonder you were confused! Common Law provides the uninhibited Right to Travel. Actually across National Boundaries without the need for any kind of Passport, as it happens. Common Law says the following are crimes: Injuring someone, or causing them loss. If you are travelling at 90 mph on a Motorway, and you get from A to B, what injury have you caused? What loss have you caused? What crime have you committed? Answer: None. Ah! Ah! Ah! The Policymen will say: “But you could have hurt someone! So there! Can't have you possibly hurting someone! Need to book you. Just doing our job!” Firstly if you pick up a knife, to cut a sandwich, you could easily hurt someone, if you dropped it. You could hurt yourself, or someone standing near you. Has no-one ever accidentally dropped something? No? Never happened?
107
Freedom Is More Than Just A Seven-Letter Word For crying out loud! Give over! The potential for harm is ever present. 24/7! The potential. But, because most of us actually know what we are doing, the potential doesn't normally turn into a reality. If the potential ever turns into reality, then we have, indeed, committed a crime and the Law should, indeed, be brought to bear on us. That's precisely what the Lawof-the-Land is for! To rein in those who cause harm or loss to others, due to irresponsibility. But going from A to B at 90 mph is not irresponsible. If it is, then going from A to B at 70 mph is almost as irresponsible. What's the difference? 20 bloody mph! Duh! Most people understand this by Common Sense. That's why you can be doing 70 mph on a UK Motorway, and cars whizz by you. No-one is particularly concerned. I'm certainly not. People are just relying totally on their own Common Sense, and basically saying: “Sod the stupidity of Statutes”. It's a form of 'voting with your feet'. You always have that vote. (If this doesn't tell the UK Parliament, and its jobsworth Policymen, 'something', I'm not sure what ever will. Actually I think it does. None of the cameras seem to work, and on a 4-hour journey recently, I did not see one Policyman). Statutes are the Company Policy of THE UNITED KINGDOM CORPORATION. They are the Law-of-Waters being applied on dry land. That's OK if you consent. But not, if you don't! Various other names are the same thing: Law Merchant, Commerce Law, Equity Law, Fleet Law, Maritime Law … you-name-it Law … just various speciality flavours of the Law-of-Waters. In point of fact there are only two jurisdictions: Common Law and the Uniform Commercial Code. And they co-exist side-by-side. The Uniform Commercial Code applies worldwide, and determines what happens when transactions in Sales of Goods (or a Sales of the
108
The Law-of-Waters Leases of Goods) takes place. That's it. 'Goods' must be movable. Consequently Real Estate transactions (they are not 'goods', because they are not movable), and all Services fall under Common Law, the Law-of-the-Land. Therefore the Service provided by the Courts and the Police should be one of Peace Keeping under Common Law principles, and nothing more. It’s pretty easy to see why this should come about. The Law-of-Waters, as a Uniform Commercial Code (worldwide) provides Trading Standards for Goods moved between Nations … over intervening seaways. But how on earth could Uniform Commercial Standards be applied to Services, taking place on dry lands, but split across a seaway? How can diners be located in England, while the waiters (providing the Service) be located in, say, France? The only thing applicable to the manner in which those Services are provided, is the Lawof-the-Land (the customs & traditions) within which the restaurant, the diners, the kitchen staff and the waiters are all located. Returning to water’s connotations for a moment, in anticipation of our acquiescence to be duped, and to remain duped, by the application of the Law-of-Waters on dry land, many words in common usage have been adopted. All have associations with water. Banks = the two sides of a river, which contain the flow of water, the current. Which lends itself to the word 'currency' to determine the flow of 'money'. The idea that, when your mother's waters broke, you came down the Birth Canal, and can therefore be considered to be a small 'ship'. Because of this you were given a Berth Certificate (although, to hide this, they write it 'Birth', but the pronunciation is exactly the same), because you can be considered to be a small ship 'at berth'. A 'berth' being the place where a ship is moored. If you are called into a Court, you will be expected to stand in the Dock. A Dock is also another name for
109
Freedom Is More Than Just A Seven-Letter Word where a ship is moored. The basic idea is that, if a ship is impounded (in a Dock), then the Owner will appear to sort the situation out. This is synonymous with you, as a Human Being, being the Owner of your Legal Fiction 'ship'. And when you 'appear to sort the situation out' they can have your body, and do what they like with it. For example, cuff you and send you to prison, should they decide there is a necessity to do that. More 'water' association comes from the 'shipassociated' words in our language: Citizenship, Relationship, Courtship, Ladyship, Lordship, Worship (Warship? Whoreship? Actually from Worthship ... but at all seems to amount to the same thing, from what I have seen), Ownership, etc. There are just far too many co-incidences for these water-associations to be accidental, or random in any way. Indeed, even giving people the pseudo-title 'Officer', is indicative of a ship's personnel. And that's the way it is.
110
Names
Chapter 20: Names
“S
ticks and stones may break my bones, but names will never hurt me”. So they say. If only that were true and, by the time you have read this Chapter, you will understand why I say that. For the simple reason you are not your Name. Your Name was 'given' to you … usually by your parents. But, if you think hard about it, what - precisely - is a Name? It is a word. Or, more specifically, a group of words. It consists of the word you were 'given' by your parents (they may have 'given' you more than one), and the name of a family into which you were born i.e. your Family Name. These are nothing more than words. They can be written on paper, and can be sounded by someone speaking. If you hear your name spoken, or you see it written, you assume you must respond to it. You assume You, Your Human Self, Your Flesh & Blood, Your Sovereign Soul … must respond to it. This is a megadeception. Do you not see an enormous difference between Your Human Self, Your Flesh & Blood, Your Sovereign Soul … and some marks made on a piece of paper? Or sound pressure waves in the air? No? Well, let's have another go then. Have you ever heard of a Deed Poll? I would guess you probably have. What does it do? It allows you to change your Name. To any collections of words you choose. You are saying: “My Human Self, My Flesh & Blood, My Sovereign Living Soul, will henceforth only respond to this new collection of words, whether written or spoken”. That's what a Deed Poll does. And this could only happen if it were possible to DETACH one set of words to respond to (your original Name), and to ATTACH an
111
Freedom Is More Than Just A Seven-Letter Word alternative set of words to which you henceforth respond (your newly-chosen Name). 'Names' are attached! They are attached to flesh and blood, purely for convenience. Imagine a family with three children. The parents decided not to bother to name them. So, when one child is naughty, the parent shouts: “Stop doing that!” All three would turn to look, to see which child the parent was looking at. He or she would then have to say: “Do you mean me?” I think you will find that, a long, long, time ago (in a far-off galaxy?) it was decided that - for convenience fleshes and bloods should be told “Listen: Whenever I, or anyone else, says this word, I mean you. OK?” And the child would - eventually - comprehend. Of course, it isn't done like that in practice. It's done the same way we do with domestic pets. Repetition. So they get used to the sound. But the practical convenience, behind the process, is exactly the same. Why is this so important? Well, simply because your Government thinks your Name is the same as You. (Well, it probably doesn't really, but it always acts as though it does, so you never figure out the difference. And it certainly doesn't inform you of the difference. Did they tell you this at school?). Every letter you receive is addressed to YOUR NAME. Get it? Addressed to your Name. Not to Your Human Self. Because Human Selves are born 'nameless'. We are not born with a Name tattooed on our foreheads, are we? This is why your name is actually a Legal Fiction Name. If anyone writes to you, or calls you, using that Name, then you are perfectly entitled to ignore it, or respond: “'Scuse me, are you talking to me? If you are, then I'm commonly called dah-de-dah”. In my case it's: “'Scuse me, are you talking to me? If you are, then I'm commonly called Veronica”. And when they continue: “Yes, Ms. Chapman, I …”, I interrupt by saying: “I just told you I'm commonly called Veronica. 'Ms. Chapman' is
112
Names a Legal Fiction. I am Human and real. I am not fictional, legal or otherwise, as you must surely be able to see?” Within their jurisdiction, they can only address your Legal Fiction Name. So. They. Do. Not. Like. It. Up 'em! Maybe you 'get it' now? What's in a Name? Everything, baby! EVERYTHING! Forced to carry an ID Card, You & Your Name are being glued together. Forced to have a microchip implanted, You and Your Name are one and the same thing. And there is something else of considerable importance. If, in a Court, you are asked to confirm your Name (and Date of Birth), you cannot. You cannot for the simple reason that any knowledge you have is hearsay. You would be confirming only what your parents told you. They could have lied about these things, for all you know. Sure, they probably didn’t, but how do you know? Sure, you were around at the time … but not in the position of understanding what was going on! Hearsay is not allowed in a Court, and you can remind them (politely!), explaining that the best you could do would be to repeat, as hearsay, what your parents told you.
113
Freedom Is More Than Just A Seven-Letter Word
Chapter 21: Orders
I
f dependent on the one who carries out the order. The Mail Order firm, and the shop, set their rates. You decide whether or not you are prepared to pay that amount before you place any order. If someone gives you an order (e.g. a PCSO, Policyman, or a Magistrate), you can say: “Is that an order?”. If the answer is: “No”, then you can say: “In that case I respectfully decline to provide that service”. If the answer is: “Yes”, you can say: “In that case, since an order is chargeable, I will charge you £50,000 for carrying it out. Are you prepared to pay?” I leave you, dear Reader, to guess what the answer will be. If they are silly enough to agree, in front of witnesses, then you have a Lawful Contract with them (a Lien). So, it is possible to remind them: “Based on the fact that you are agreeing to a lawfully enforceable Contract, would you like the chance to re-consider?” (I think you’ll find they generally tend to re-consider).
114
Laws, Regulations, Guidelines & Sovereignty
Chapter 22: Laws, Regulations, Guidelines & Sovereignty
I
'm the Legal Fiction, baby ... now here's the twist ... I ... don't ... exist! (with apologies to the Bonzo Dogs, featuring the late Viv Stanshall). Before going anywhere in this morass, we need a few basics. There are two fundamental kinds of ‘Law’: Natural and Man-made. Let’s characterise them. I think you might agree there are three main characteristics in each case. Natural Laws or the Laws of Nature, Science, etc.. 2) They apply universally and unilaterally without fear or favour. 3) There is no penalty for breaking them because they cannot be broken. Man-made Laws, Acts, Statutes, etc. 1) Mankind does make them. Mankind changes them in accordance with its own desires, wishes, needs, etc. Mankind can wipe them away (repeal them) at the stroke of a pen. 2) They are applied by Courts of Law. They are not applied equally because they always depend on 'judgment'. It is often said: “There is one law for the rich and one law for the poor”. 3) There is always a penalty for breaking them because they can be broken if one is prepared to accept the consequences.
115
Freedom Is More Than Just A Seven-Letter Word Stated that way I submit it is possible to see that the two kinds are exact opposites. Each characteristic is the exact inverse of the other. And yet we use the same word – 'Law' – to describe them both! So what happens? The latter become psychologically imbued with the characteristics of the former! So: “I’ve got to pay it …because it’s the Law” takes on the same characteristics as: “If I jump off this cliff I will fall downwards”. Actually, in summary, the most important difference between the two is a simple word: 'consent'. If you jump off the cliff you will fall downwards. The falling does not require your consent. It will happen. Your consent is whether or not you actually jump – or whether or not you are standing on the edge of the cliff at all. In the second case (“I’ve got to pay …”) your consent is very much required. You have to consent to reach for your chequebook and fill in a cheque – and post it, etc. However, the essential point being made here is that even if you do not consent to write that cheque, your consent is still needed in all stages of: “What may happen if the bill is not paid”. Your 'consent' is built-in as an essential to the system of Man-made Laws, Statues, etc. Your consent is irrelevant to the Laws of Nature. The Law of Gravity is set in tablets of stone, and operates whether someone has written it down or not. You will have been led to believe, throughout your entire life, that Statutes are equally set in tablets of stone. They are not. They are nothing more than Company Policy written down using ink on paper. The trick, the Grand Deception, is to create the Legal Fiction Person for you, and to address everything ‘statutory or officious’ to that fiction, using a Legal Fiction Name … which is sufficiently similar to what you would naturally respond (i.e. to “What you are commonly called”). Thereafter you have become tricked
116
Laws, Regulations, Guidelines & Sovereignty into accepting a role in this: “All the world’s a stage, and we are just players of bit parts”. To do this they get you to pretend to be what you are not. But they call this 'thing' something you will naturally assume that you are. And they know that you will naturally make this assumption. And they utterly rely on it. Only a system that is utterly evil and thoroughly corrupt - without any possibility of redemption - could have dreamed up this dooley, which is fully described in the Chapters devoted to Legalese and to the Legal Fiction Person. From the point of view of you, yourself, the Human Being with the living soul, Man-made Laws or Statutes can be treated as guidance and nothing more. They are not Laws. They are Regulations. As far as you are concerned they can be considered to be Guidelines … but that’s only if you choose to consider them that way. It is perfectly possible to reject any or all of them, as not having your consent. And this leads to the idea of ‘sovereignty’. We often hear that: “All are created equal” – and, of course, we are. Any baby arrives (basically) the same way, and has the exact same needs. It doesn’t matter whether you are born in the Queen’s Hospital or in a Traveller’s Van. But, what does: “All are created equal” translate to? In practice? How can everyone be created equal? The only way is by some standardised mechanism. This is usually stated as: “In the image of the Creator”, which implies that each created individual is a clone from the same model. Even if you don’t believe in a Creator (as I don’t – I believe in a Universal Life Force, Universal Consciousness – you can call it God if you like), it still amounts to the same thing – just using different rhetoric. Of course: “All are created equal”, thus no-one should be treated differently from anyone else.
117
Freedom Is More Than Just A Seven-Letter Word But I am not you, and you are not me. (That’s arguable, actually, if we are all derived from One Consciousness) So that’s a big difference. But there is a big similarity: We are individually responsible for our individual actions. And that’s one of the basic tenets of life. And the only way that I can be responsible for my own actions, and – at the same time – you be responsible for your own actions is if we are both sovereign individuals, and equal in all cases (“In the same image”). I’m sorry if I lost you. Think of it this way. You say your Country is ‘sovereign’. What does that mean? It means it is equal to all other countries. It means it has the right to govern itself, without external interference. Your country considers itself to be equal to all other countries. The same applies to you. Why not? A ‘country’ is only a collection of individuals who, together, make up the population. You must be as sovereign as your Country. And so must everyone else in your Country. Otherwise how can your Country be sovereign? Where does your Country’s sovereignty come from, then? FACT: You are a sovereign Human Being by birth, because your spirit is sovereign. You are responsible for your own actions – certainly after the 'age of majority'. You have two choices: You can take your sovereignty, and wield it. Or you can, by consent, give it away. So now we are back to 'consent'. And we are also back to 'person' because – by consenting to wear the Legal Fiction Person overcoat, you tacitly accept the jurisdiction of any Statute Law/Regulation/Guideline you may be accused of violating.
118
The Hive Mind
Chapter 23: The Hive Mind
W
e must get out of the habit of falling into the 'Hive Mind Trap' constantly and consistently. Almost, it seems, with every breath we take. Perhaps one of the best ways of expressing the Hive Mind is by example. When asked: “Why do you do that?”, a Hived Mind response is: “It's what we do now. That's the way we do it”. End of story. End of conversation. End of discussion. End of argument. No … it's not the end of the discussion! Nothing like! The original question is not answered by that response. However, it is generally the only answer you'll get from some Organic Robot who has a Hive Mind. In other words that's a Hive Mind answer. But there are also Hive Mind questions. For example: “How do we do this officially?”, is that kind of question. The question should have been: “What's the best way to do this honourably?” I mean, what has 'officially' got to do with anything? The Hive Mind is ingrained into our psyche due to the indoctrination we suffer during childhood. It comes from our parents and schooling. It comes from these sources because they were similarly indoctrinated - as opposed to being properly educated - during their own childhoods. “What would the neighbours think?” was a perennial favourite of my own mother. It I used to tell her: “I don't give a shit what they think. That's their problem, not mine”. (I can only presume I was born a rebel). I hated school … due to its Hive Mind attitude. Although I couldn't put my finger on it at the time. I just knew it was all wrong 'somehow'. A Builder can make a house. A house cannot make a Builder. The Builder is 'above' the house.
119
Freedom Is More Than Just A Seven-Letter Word A Human Being can make a Law. The Law cannot make a Human Being. The Human Being is 'above' the Law. It has to be that way. And the Law has already been made. Centuries ago. Although there were attempts beforehand, a major boost, to codify it properly, occurred in 1215. When we are in Hive Mind mode we are not 'above' anything. Our mentality is 'below' the situation. We are looking upwards, and wondering: “How to do this officially?” We are looking for 'guidance from above'. The correct attitude is to use our Common Sense, and to take an honourable course of action. Then our mentality is right where is should be: Above the situation at hand. I'm often told that many people want 'to be led'. This argument can - to some extent - be countered by wondering whether or not their childhood indoctrination has left them in that state? And whether or not, if they had been educated instead of indoctrinated during that period of their lives, perhaps they would not want to let the Government (and it propaganda arm, called 'The Media') do all their thinking for them? But I'm obviously out on a limb with that answer. Simply because I'm unable to prove it, of course. My Common Sense tells me … but that's all. But my Common Sense also tells me that - even if the vast majority would not want to be led by the nose had they been properly educated - then there is still the possibility that some would want it that way. OK. Fine. Let them be sheep, and led by the nose - by some nannying Big Brother-style Government. But don't include me in that, sunshine! Because I don't accept being treated as a 'lowest common denominator'. And, I believe, there are millions of us who object to being treated like that. And we have a voice. And that's what this book is all about.
120
Without Prejudice
Chapter 24: Without Prejudice
Y
ou will find that letters considered to be 'of importance' may include the words: “Without Prejudice” somewhere prominent, either at the top or the bottom. And you can use this yourself on correspondence you create. What, actually, does this mean? Well, it doesn't mean that whoever writes it is 'not prejudiced against the addressee'. And it is important to know this, if you decide to use it yourself. In Court, you may very well be asked to explain what it means, and if you say: “It means I'm not prejudiced against anyone”, they will know you don't know what you are talking about, and what you are really doing. So it's a very good idea to know exactly what it means, and exactly what it does, before employing this technique. Or, conversely, what it means if you receive a letter that says: “Without Prejudice”. What it means is: 1. The Sender of the correspondence is reserving all Rights, and nothing in that correspondence should, or could, be taken to give up any Rights. (The things that are not being 'prejudiced' are one's Natural Inalienable Rights). It means that the Sender openly stating: “Not to be bound by any Contract unknowingly entered into, and only bound by those that meet the four criteria of Full Disclosure, Equal Considerations, Lawful Terms & Conditions, and Manifested Intent to Contract”. 2. It - therefore - means that the correspondence cannot be entered into Court evidence without the permission of the Creator. So you can send anyone a letter, saying whatever you like. If you add: “Without Prejudice”, then that letter cannot be used against you in Court, unless you agree. (Obviously you can always submit your own correspondence into evidence … that's always yours to submit if you choose … you just can't
121
Freedom Is More Than Just A Seven-Letter Word submit theirs - if either side had written: “Without Prejudice”, see blow). 3. And the same thing for them, of course. But there is more. Once either Party has used: “Without Prejudice”, all further correspondence, from either side, in the current matter, is protected by the original “Without Prejudice” - whether it is employed from then onwards (in further correspondence) or not. So how does one use it, then? Actually there is a very strong argument for not using it. If one is sure of one's position, and making strong, assertive, statements (which is the Freeman-on-the-Land way of writing), then one's Natural Inalienable Rights will be being asserted. And this needs no protection from any future Court case. Quite the opposite, of course. Normally you would want what you said to the other Party to form a major part of your defence against them. Thus, in that scenario, if you are sure of yourself (as you should be!) there is no point in using: “Without Prejudice”. But then, there's nothing you can do to stop them using it. And then all your correspondence, from then onwards becomes, 'protected' (see (3), above) - as well as all theirs. But this still does not alter the fact that you could submit your own correspondence into evidence and, if they chose to hide theirs, your statements would stand un-rebutted. Which would put you in a very powerful position. I suppose it's a bit like a game of Poker. But a Freeman-on-the-Land doesn't need to be bluffing, and therefore doesn't need to hide his or her cards - as long as they understand the game, and know what they are doing.
122
Mass Mind Control & Enslavement
Chapter 25: Mass Mind Control & Enslavement
P
revious Chapters have explained the triumvirate of the Grand Deception, namely Money, Legalese and Religion. And it is all fundamentally bound up with the illusion of 'money'. Have you ever asked yourself: “Where does money come from, in the first place?” You have? Well, congratulations! What was your answer? I'll tell you what mine was. I decided that everything must have an ultimate source. My Common Sense told me that. I knew you could obtain money by working for some Company, as a salary or wages, and I knew you could also obtain money by selling things. I didn't think I was very far out on a limb with these thoughts. But then I thought: “Well, yes to all that … but where did it come from originally?” Now most people would say: “The Bank of England. The Royal Mint. They make it, don't they? Daft question, V!” So I thought: “Well, is it such a daft question? I mean how do they put it into circulation? Do they hire a plane, and drop it from the sky? Well, I've never heard of that. Does someone stand with a bucketful of it, in Threadneedle Street, and throw it up in the air, for anyone to catch? Well, no, I've never heard of that either”. I decided that there must by a 'system'. A mechanism. A controlling mechanism. Am I bonkers? (Don't you dare answer that!) Well, I decided that I wasn't quite ready for the Looney-Bin just yet. (Even though, by the way, I was actually born in one. In Sedgefield, in County Durham, during WWII. No, my mother wasn't mad. She had been evacuated to there. From out of London)
123
Freedom Is More Than Just A Seven-Letter Word So I continued thinking. And I looked around. And I saw Banks. And I saw them going cap-in-hand for bailouts. And I saw some Banks and Building Societies going titsup. And I thought: “If they go belly up, then they can't be the source, because - if they were – going belly-up wouldn't happen”. So I decided I didn't have the answer to my puzzle. And I was left with a few serious (in my view) questions, which were: 1. How is ‘money’ created? 2. Who, or what, authorises it? 3. How is ‘an amount of it’ created? 4. How does it get into circulation? I thought, for a moment, that I'd bitten off more than I could chew. But then I remembered what is supposed to be a Government Agency (but actually isn't!) called 'Her Majesty's Treasury'. So I did a Freedom of Information Request to HM Treasury, asking them if they could kindly help me answer these questions. And, to cut a long story short, they very kindly replied. And I have obtained four responses from them, which I include in an Appendix. The responses I obtained have been very helpful (in many ways), but not one has actually answered any of my four questions. Well, you might suggest: “That's probably because they don't know, Veronica!” And, I suppose, that is possible. But, if HM Treasury don't know, then who does? Does 'money' just appear by magic, then? (They say it doesn't grow on trees, but obviously that's where all the banknotes actually start their lives). But here's another important facet. In one of the letters I sent to HM Treasury, I explained exactly what I understood the answers to my questions were. (Never ask a question unless you know the answer, otherwise you never know whether or not the answer you are given
124
Mass Mind Control & Enslavement is bullshit). And I asked them to please confirm or deny my understanding. And, do you know what? They did not confirm - BUT DID NOT DENY - my understanding! And denial would have been so easy. All they had to do was to say: “No, sorry, but you are wrong”. But they didn't! You can check out the entire correspondence in the appropriate Appendix. You will see that HM Treasury did impart some very useful nuggets. Such as the fact that 'money' has not been backed by any precious metal since 1931. (In other words my lifetime, and probably yours). And that currency is fiat, i.e. 'it has no intrinsic value'. And that the best you can ever do is to swap a tenner for two fivers, and so on. And that the issuance of 'money' (from wherever the ultimate source lies) is limited by Government Statute called The Currency Act. Yes 'limited' … but on who, which Authority, is this limitation placed? That's the question! What were the answers I gave to HM Treasury, that they did not deny? I asked the questions in this way: 1. What, precise, mechanism causes the release of 'some amount'? It must require some authority. Whose authority? 2. What defines 'the amount'? 3. How does this created money 'get into circulation'? I self-answered those questions, back to HM Treasury, in this way:,
125
Freedom Is More Than Just A Seven-Letter Word 'because the Banks demanded it'. But this is very unusual, as I'm sure you will agree. Hence all the furo. HM Treasury did not deny these answers. They ignored them. So what the hell does this mean? It means that you apply for a loan of some kind. This could be a straight monetary loan, or a Credit Card, or a mortgage. Anything similar. You make an application, by filling out an Application Form. You think it is an Application Form, asking the Loan Shark (commonly called a Bank, Bankster, Credit Company, Loan Company, Building Society … you get the picture) to lend you some of their own money.
126
Mass Mind Control & Enslavement You think this because everyone else thinks the same thing. Even most of the Organic Robots who work for the Loan Sharks, processing applications, think that's what's happening. But, it isn't. When you sign the Loan Application, you are - in point of fact - actually signing a cheque (a Bill of Exchange). A cheque drawn on an Account you did not realise you had. It is an Account that is automatically created, in the name of your Legal Fiction Person, when your birth was registered by your parents. It is, fundamentally, a 'notional' Account. Really just numbers on a ledger (a computer database, these days). The Account Number is somehow tied to your National Insurance Number and your Birth Certificate Number, and is named by taking your name in all capitals. Thus mine is VERONICA CHAPMAN, for example. You send this cheque to the Loan Sharks, and they rub their hands in glee! Because you have made some 'money' for them! They then send this cheque to HM Treasury, or some Government Department 'known only to them'. (It is this knowledge, that is obviously sort-of secret that enables a Loan Shark to start up in business. My Freedom of Information Request was designed to extract that secret, but I was just stone-walled, because I'm not a Loan Shark. But notice … my answers were not denied!) The 'source of all money creation' will take the cheque and 'cash' it. 'Cashing it' comprises 'Authorising credit to the Bearer of the cheque'. ("I PROMISE TO PAY THE BEARER ON DEMAND …", remember?) So the Loan Shark is credited with the amount you signed for. If you applied for £50,000 then he is 'up' by £50,000! Lovely jubbly! Clap hands … walk away with your money (if he wanted to!). He could send you back a
127
Freedom Is More Than Just A Seven-Letter Word letter saying: “Oh, sorry. Your Loan Application failed, after all!” And you would be none the wiser. But he knows, if he always did that, people would stop applying for loans. Because there would be no point. And he also knows if he moves that £50,000 into a Personal Account you can drawn on, then you will draw on it. And spend it. And you will think you have to pay it back (because everyone thinks that!), and you will also assume that you have to pay an additional amount called 'interest' (because everyone thinks that!) And he knows that, in this latter situation, bearing in mind the way Compound Interest works, he is likely to end up with being paid TWICE (at the very least)! Being paid twice for money you made! Lovely, lovely, jubbly! He steals something from you in the first place, and gets you to pay it back with Interest. Oh boy! What are the words I'm looking for? I have a big problem finding the words, because fraud, theft, grand larceny just do not do the situation justice, in my humble opinion. But that's not even where it ends. Oh yes ... there's lots more to come. First of all, within that mechanism, even if it were not utterly fraudulent, there is only the mechanism for 'creating' the £50,000. There is no mechanism at all for creating the Interest! There is no mechanism for creating Interest. Which means that, under the current fraud, all loans could never, ever, be paid off! It is impossible! And that situation creates the dog-eat-dog so-called 'civilisation', which we all know only too well. Because we have to live in it, 24/7.
128
Mass Mind Control & Enslavement Only utter psychopaths, such as I described in the Chapter on the Global Elite, could have designed this, surely? You would need to be inhuman, surely? But there is more. Think about it. You have a Government Agency 'creating money'. (It doesn't matter which one it is … it ain't you, that's for sure!). You have another Government Agency 'wanting money'. In the UK these two Agencies are HM Treasury and HM Revenue & Customs. In the united States this would be the US Treasury and the IRS. Now, why can't HM Revenue & Customs, if they 'want money', get it directly from HM Treasury, who can 'make money'? 'Make as much money' as HM Revenue & Customs would ever need? Why bother you & I? I can only think of one possible, plausible, reason: “Money has to pass through us in order to keep our noses to the grindstone. In short, to keep us enslaved. It also has to pass through the Loan Sharks because the Global Elite own them, and that’s how they obtain their massive wealth. And they own the Governments, thus they can ensure the legislation that enables these ripoffs. Generally without the knowledge of Joe Bloggs”. To keep us in the prison-without-bars. So now what is a bailout? Oh, it’s pretty simple isn’t it? And why there is so much angst involved. A bailout is the creation of money without directly enslaving anyone to ‘pay it back + interest’! That’s the reason for the angst. But there is one more final thing to say. While the Loan Sharks are getting you & I to pay back – to them – the ‘money’ we, ourselves, created … please note: They don’t have any need (in turn) to pay it back to where they got it from … i.e. the Treasury. Oh lovely, lovely, lovely, lovely jubbly!!
129
Freedom Is More Than Just A Seven-Letter Word Now, perhaps, you can understand why this Chapter was called Mass Mind Control and Enslavement? I hope so. I've done my best to explain. Why am I so convinced my answers are correct, and that this system operates the way I have explained? Because there is no other way. There is no other way to apply domination and mass mind-control over the entire planet. No other way such that even a dullard could not see through. Every scrap of practical evidence we have supports this contention. Every prevarication we encounter universally supports this contention. Every media article is universally designed to hide this contention. Every book of Law, Accountancy, or Economics likewise. Every cognitive dissonance, from every Organic Robot, supports this contention. And our own Common Sense literally screams this contention. Well, it does to me, at any rate. Think about it. I have explained how Money & Legalese (supported by Religions) are massive illusions. Merely Belief Systems that could be jettisoned at the snap of finger and thumb. But, if that were the case, then domination and enslavement would no longer be possible. On the other hand, the set-up of these Belief Systems was based on pandering to innate greed. It is very easy to see how the concept of 'money' could have been slipped into the universal psyche, based on: “You worked hard for that, you should have some return” and: “This system is so much easier, more convenient, and more flexible than bartering. All we have to do is to set some standards”. Constantly supported, at every turn, by psychologies whose design basis was 'greed' (Roman Empire - greed for domination? Feudal System - greed of the Nobility and the Monarchs?) Never once did anyone (of importance) (apparently) say: “I have to take, because I'm alive. But all I need is all I need. I don't need any more, thanks. It is
130
Mass Mind Control & Enslavement dishonourable to take more than I need. I don't need to be greedy. I firmly believe we should all think that way. The only reward I will ever need is simply the honour of contributing selflessly to the good of one and all. And I think that should be the only reward anyone ever needs. Don't need 'money'. Don't need 'legal'. Don't need 'religion'. Don't need illusions!” Back in the relatively uncivilised days, when it all started, it is easy to see how people could be fooled. There was a time when they believed wholeheartedly in a God who made the Sun, and made it revolve around the (flat) Earth. And they never questioned these things. So why should they question 'the introduction of a Monetary System for their convenience'? You would, and still do, need to take a step back and realise there is no dishonour in taking, and think about the Farmer, Miller, and Baker example, before it is possible to see the hoodwinking. You also have to understand the psychology of sicko psychopaths, who would actually want to create these illusions. You have to do this before the audacity of it ever has the slightest chance of dawning upon you. And, even then, you would still need to answer why you even asked the question: “What makes you so sure, Veronica, that your answers are right?” The fact that this latter question even crosses your mind shows how ingrained the whole system of illusions has become. You have to remember that we were made by sicko psychos, in the first place. The Annunaki (the Biblical Elohim/Nefilim). And their own half, of their creation, implanted the sickness of greed within us, so they knew exactly how to pander to it. We took our example from them. We knew no better. We copied their appalling example. We saw the way they behaved, and copied it, on the assumption that was the way to behave. We were told they were Gods - what chance did we actually have to know any better? We can know better because of one thing. We are also half human. And, wherever 'human' came from, it came with compassion, conscience, empathy. It came with
131
Freedom Is More Than Just A Seven-Letter Word Common Sense. We have that, and they don't. We have a 'better nature', and they don't. That allows us to unravel their carefully constructed illusions, which I hope I have done in some small part. Nevertheless the reality they have constructed, in order to maintain their domination, is immense and very, very, thorough. But there is a way out. The Examples in this book show that. It comprises what is called Lawful Rebellion. It's a sort of 'lawful Judo', where you take the momentum of the attacker and use it against them, in your own defence, by adding dollops of Common Sense. It is pointless telling me you have ‘democracy’ available to sort anything out, because your ‘democracy’ doesn’t work. It doesn’t work because those who attain the ‘highest positions’ all work for the same Masters (the Global Elite). It doesn’t matter to the Global Elite whether the current Prime Minister is Tony B Liar, Gordon Brown, David Cameron (or whoever – at the time of writing), anymore than it makes any difference whether the US President is a DIMocrat or a RepuliCON. The only thing anyone has at their disposal is not a useless ‘democratic vote’, but Lawful Rebellion - used to its most potent effect. The vast majority of which can be done from your armchair, sitting in front of your computer, and writing letters in your own defence. The more people that do this, and to stand up for themselves & their loved ones, the better. I'm sure you'll get the idea from these Examples. If not then you can join in the Forums that have been setup up at forum.fmotl.com. The only reason why ‘they’ get away with any of this, is simple: People just do not know their Rights. Rights that many of our forefathers gave their lives to protect. It seems to me (at least) we need to do three things: 1. Learn or re-discover them;
132
Mass Mind Control & Enslavement 2. Use them at all times; 3. Teach them to our children, so they never get lost or forgotten ever again. Like them, you are a magnificent part of all that is, all that ever was, and all that ever will be. And it’s long past time you claimed your freedom to be what you truly are. It’s a lot more than just a seven-letter word.
133
Freedom Is More Than Just A Seven-Letter Word
Epilogue
N
othing I have written herein incites or induces violence of any kind. Nor any form of racial hatred. In point of fact, quite the contrary. All I've done is used Common Sense to point out the obvious, and documented methods by which perfectly peaceful, and perfectly lawful, rebellion can be achieved - entirely within the Law-of-the-Land. And nowhere have I even suggested that anyone should break the Law-of-the-Land … or even Statutes for that matter. Once again, quite to the contrary. And the Magna Carta 1215 says quite clearly, in Article 61, that it is the Inalienable Natural Right and Duty of each and every one of us to rebel with lawful excuse, as ever it may become necessary. The content of this book indicates that such necessity is upon us, in my humble opinion. I am fully prepared to go toe-to-toe with any Judge, Magistrate, Lawyer, Solicitor, Policyman, General, Admiral, Politician, King, Queen - indeed anyone - and stand on the Common Sense I have documented. This is not bluff. I am not bluffing. And I am not afraid of you. Yes … you know who I mean. But, of course, you would never do that, would you? Go toe-to-toe openly? You would use your undoubted 'muscle', supplied by your meticulously-created Mind-Controlled Organic Robots, to lock me away without discussion. Or you would make sure I somehow disappeared. 'Character assassination'/'actual assassination' … you don't care … as long as the Truth remains covered up. 'Suicide' is your favourite one, of course. That and 'Strange
134
Epilogue accidents, when the CCTV just didn't happen to be working'. You are snivelling, psychopathic cowards - and that's the way you act. That's the way you have to act. That's the way you've always acted, since the beginning of time. Because your actions could never withstand any scrutiny in the light of day. The 'hand' has to be kept 'hidden', doesn't it? You disgust me, to the root of my soul. But do I hate you? No, not at all. I just want you locked up, away from decent people, to have a very long life – and the opportunity to consider all the evil and corruption you have perpetrated upon decent souls. I want to give you as long as possible to think about all that. In a real prison. With real bars. So there’s no mistaking the situation: “It’s not corruption that’s the problem. It’s the acceptance of corruption that’s the problem” said Pat Rattigan in 2004. And anyone who reads this book will know what you are. If anything happens to me, as it has done to others who have revealed Truths, then what I have said becomes Truth anyway. But then left to stand as it is, the blinding obviousness of what I’ve written is, frankly, rather hard to rebut, is it not? Bit of a problem, then. And you do, after all, have an awful lot to lose. But, for me: “Freedom's just another word for nothing left to lose”, as Kris Kristofferson once wrote. Sue me. Prove you are not a psychopath. Let’s have your DNA examined by a Court … even a de facto one. You have no clothes! You Emperors have no clothes! The bits of blue cloth you wear, with metallic trinkets attached, the wigs you don, the trappings & robes you wear … still leave you as naked as the day that you were born!
135
Freedom Is More Than Just A Seven-Letter Word (If I ever say anything different, 'it will be the drugs talking'. The ones your Robots will have used, without my permission or my consent).
136
Templates & Usage Disclaimer
Appendix A: Templates & Usage Disclaimer
D
isclaimer: You are playing with fire. And you know what happens if you do that, without knowing exactly what you are doing. It is, therefore, absolutely essential that you have read this book from end to end before attempting to rebut any legal action taken against you. And, furthermore, you do it in accordance with the information herein entirely at your own risk. The techniques explained herein will not, necessarily work in any case if you have already been through Court Proceedings because, at that point, you will have tacitly agreed to be the Legal Fiction Person. All the information contained in this book is used entirely at your own discretion. In no way should anything be read herein other than to encourage you to consider possibilities. And to use your Common Sense to understand the deceptive world in which you live. There is no encouragement or incitement to take any actions of any kind. The Templates can be found on the Internet, on the links given below. This is the best way to present them, because of their 'dynamic' nature. They can be used for more than one circumstance, for example if more than one Legal Fiction Person is involved i.e. 'Mr. & Mrs.'. Furthermore certain prefixing can be invoked depending on circumstances The responses to them will either be 'standard' generally to repeat Statutes in return (fundamentally they have no idea what you are talking about, and respond by rote). Where necessary the Templates include the condition of 'estoppel by acquiescence', and so this should be pointed out in the reply, specifically:
137
Freedom Is More Than Just A Seven-Letter Word (a) No response to the Human Self has been forthcoming (response was still addressed to Legal Fiction Person), and this is the last time you will reply pointing this out; (b) No response in substance has been forthcoming; (c) Thus 'permanent and irrevocable lawful estoppel by acquiescence' has been gained, due to their dishonour; (d) Your original Conditional Agreement removed all Controversy, and thus removed the possibility of Court Action on their part; (e) Notice that henceforth a charge of £500 will be levied for letters sent that appertain to the matter in hand (where a communication is addressed to your Human Self). Correspondence continued to be addressed to your Legal Fiction Person will be returned unopened, marked: “No Legal Fictions dwell here. Only Human Beings. Try La-La Land”; These things tend to tie them up on knots. If they still persist, let them. You’ve already won, so why should you care what they do? You can write back and tell them that you’ve already won so, whatever they do – they’ve already lost. Point out that, if they go to Court, their case will be dismissed, and that you will make a Counterclaim for harassment in the sum of £50,000 for all the UNLAWFUL stress you have suffered. (Make sure you always do this from what you are commonly called, and not the Legal Fiction Name they addressed, “Without Prejudice”, etc. The Templates make sure of all this). The best thing is not to open letters addressed to your Legal Fiction Person, but to return them unopened, as explained above. Phone calls: Don’t admit to your name, and DO NOT quote the “first line of your address”. Give them absolutely nothing (not even the time of day, if possible). Have I actually done this myself? Yes. On a number of occasions. What happened to me? Nothing ... as yet. Except the chance to write this book. It is felt that the Templates should be self-explanatory.
138
Templates & Usage Disclaimer I have been asked: “Which template do I use:?”. The answer to that is: “The templates are the 2nd Phase. The 1st Phase is to stop paying. You will then receive a letter, which you will need to rebut. You will then know which Rebuttal Template to use”. The only Templates presented herein are those that have been proven to work. However, while they start the 'rebuttal ball rolling', they do not - necessarily - stop the process immediately. It is often necessary to follow up, explaining the difference between 'legal' and 'lawful' (their response will always be in the 'legal sense'), and pointing out that the ‘lack of response in substance’ has gained the estoppel, explained above. Type templates.fmotl.com into your Browser to obtain personalised rebuttal letters for the following situations:
139
Freedom Is More Than Just A Seven-Letter Word Debt Collection Agency? = DCA Reference Number ?10? = DCA Reference Date ?11? = DCA Address Line 1 ?12? = DCA Address Line 2 ?13? = DCA Address Line 3 ?14? = DCA Address Line 4 ?15? = DCA Address Line 5 ?16? = DCA Address Line 6 ?17? = Your Given Name ?18? = Your Family Name DO NOT SIGN IT. There is no need. ‘They’ often do not sign anything written to you, so why give them a Signature to forge? Send it ‘registered’.
140
Templates & Usage Disclaimer In care of: ?1? ?2? ?3? ?4? ?5? ?6? Near: [?7?] ?8? Re: ?9?, dated ?10?. Notice of Request To Cease Harrassment. To: ?11? ?12? ?13? ?14? ?15? ?16? Dear Sirs, Please read the following notice thoroughly and carefully before responding. It is a notice. It informs you. It means what it says. I refer to your letter dated ?10?. As you are a third party intervener in this matter acting without authority, I DO NOT give you permission to interfere in my commercial affairs as you have no legal standing. I do not have a contract with you and any permission that you believe you may have from me is hereby withdrawn. If you believe that you have power of attorney to act on my behalf you are hereby fired, and any consent that you believe you may have, tacit or otherwise, is hereby withdrawn. I am familiar with the terms of Section 40 of the Administration of Justice Act 1970, and the Protection from Harassment Act 1997. And I believe, should you continue in contacting me after my request for you to cease your activity, that you will be guilty of harassment
141
Freedom Is More Than Just A Seven-Letter Word and blackmail, and you will be in breach of these acts, and you will be reported to the relevant bodies. I am well aware of Section 40, sub-section (3) which you may consider entitles you to proceed. However upon full commercial liability and penalty of perjury you will need to supply the following Proofs of Claims: 1. Proof of Claim that your actions are reasonable. 2. Proof of Claim that any obligation on my part is due, or believed by you to be due to you, and not to some other party. 3a. Proof of Claim that any obligation on my part is to yourself by providing sight of the appropriate contract, or 3b. Proof of Claim that any obligation on my part to persons for whom you act by providing sight of the appropriate contract. 4. Proof of Claim that any obligation on my part protects you from any future loss. 5. Proof of Claim that any obligation on my part is enforcement of a legal process on a Human Being under Common Law jurisdiction, who cannot possibly have such liability under said jurisdiction. You would of course need to provide these Proofs, including showing the full and audited accounting, if you chose to go to law. Please also note that if you contact me by telephone, after a formal request not to, you will also be in breach of the Wireless Telegraphy Act (1949) and, as such, I will report you to both Trading Standards and The Office of Fair Trading. And take further note that continued telephone calls after the receipt of a request not to call, and that you immediately destroy all
142
Templates & Usage Disclaimer of my data held on your records. Failure to do so will result in a report being submitted to The Information Commissioner for Data Protection breaches. You will be deemed to have been served notice of my request and I will deem it served three (3) days from the date of this letter. This has been sent by recorded delivery. I am advising you that any communications from you including but not limited to letters, phone calls and text messages received after this date will be recorded/noted with the intention of them being used as evidence. Do not contact me again..
143
Freedom Is More Than Just A Seven-Letter Word Charge or Demand Rebuttal (incl. Fixed Penalty Notices).? = Charge/Demand Reference Number ?10? = Charge/Demand Reference Date ?11? = Charge/Demand Address Line 1 ?12? = Charge/Demand Address Line 2 ?13? = Charge/Demand Address Line 3 ?14? = Charge/Demand Address Line 4 ?15? = Charge/Demand Address Line 5 ?16? = Charge/Demand Address Line 6 ?17? = Your Given Name ?18? = Your Family Name ?19? = The Legal Fiction Name, exactly as printed in the Demand. ?20? = The Amount Demanded This has been organised for a Fixed Penalty Charge. This same (or similar) wording could be used for any Demand in general. DO NOT SIGN IT. There is no need. ‘They’ often do not sign anything written to you, so why give them a Signature to forge? Send it ‘registered’.
144
Templates & Usage Disclaimer In care of: ?1? ?2? ?3? ?4? ?5? ?6? Near: [?7?] ?8? Re: ?9?, dated ?10?. Notice of Discharge of Outstanding Fixed Penalty Charge and Request for Clarification. ?11? ?12? ?13? ?14? ?15? ?16?
145
Freedom Is More Than Just A Seven-Letter Word unacceptable conduct on my part. You have apparently made demands upon me. I do not understand those apparent demands and therefore cannot lawfully fulfill' ?19? and that I owe £?20? for services' ? 19?, being the entity to which your paperwork was addressed, and not ?17?: of the ?18? family, as commonly called.
146
Templates & Usage Disclaimer.
147
Freedom Is More Than Just A Seven-Letter Word Court de facto Summons? = Summons Reference Number ?10? = Summons Reference Date ?11? = Court Name/Address Line 1 ?12? = Court Address Line 2 ?13? = Court Address Line 3 ?14? = Court Address Line 4 ?15? = Court Address Line 5 ?16? = Court Address Line 6 ?17? = Your Given Name ?18? = Your Family Name ?19? = The Legal Fiction Name, exactly as printed in the Summons. DO NOT SIGN IT. There is no need. ‘They’ often do not sign anything written to you, so why give them a Signature to forge? Send it ‘registered’.
148
Templates & Usage Disclaimer In care of: ?1? ?2? ?3? ?4? ?5? ?6? Near: [?7?] ?8? Re: ?9?, dated ?10?. Notice of Request for Clarification of Paperwork Received. To: The Clerk of the Court ?11? ?12? ?13? ?14? ?15? ?16? Dear Sirs, The enclosed paperwork was delivered to the address at which I dwell. It was addressed in the name ?19?. I have been led to believe this signifies that the paperwork was addressed to a legal fiction known as a PERSON, which is, in point of fact, the name of some CORPORATION. I would be most grateful if you would kindly confirm or deny my understanding in this respect. As a sovereign Human Being, with a living soul, and consequently (as I understand it) under Common Law jurisdiction (i.e. the law-of-the-land, as opposed to Corporate or Statute Law, namely the law-of-the-sea), I am not entirely sure why I have received this paperwork, and would be grateful for any clarification in this matter. I have no wish to dishonour any valid and lawful obligation on my part.
149
Freedom Is More Than Just A Seven-Letter Word Article 45 of the Magna Carta 1215 states quite clearly: raised herein. According to Dun & Bradstreet there is a registered company known as ?11?. Since it is possible to obtain a D&B Credit Report on said company, it seems reasonable to assume that it is in business, actively trading, and offering services. Please confirm that your good selves have no connection with said Trading Company, and that said paperwork was not an issuance from it, being merely an offer to provide a service..
150
Freedom of Information interactions with HM Treasury
Appendix B: Freedom of Information interactions with HM Treasury
T
here is a Website that provides for UK Freedom of Information Requests, called WhatDoTheyKnow.com. I made the following Freedom of Information Request to HM Treasury on 3rd February, 2009: Dear Sir or Madam, Under the Freedom of Information Act I would like an answer to the following question: How, precisely, is money created? For your information I have been given to understand that it is created by means of Promissory Notes. In more detail, when a human being signs a 'promise to pay' (known colloquially as an IOU), which can stand until the end of time. And that the human being's signature on that promise renders said promise lawful. Can you please be so kind as to confirm or deny my understanding and, if necessary, correct my understanding? Thank you. Yours faithfully, … etc. I was told that they did not need to answer such questions under the Freedom of Information Act. That they were only required to pull numbers from their databases, in response to requests for such numbers. However, as a kindness to me, they would respond as they were able. A copy of their response is Figures B1 & B2. Paul Morran had not answered my question, but did supply, in Paragraph 7, sentence 2, the answer: “You are
151
Freedom Is More Than Just A Seven-Letter Word correct in essence that this amounts to an IOU”. And there were some nuggets of information in Paragraph 5, for example, sentence 3: ”Modern ‘currency’ is known as ‘fiat’ money; it is artificially created, has no value in itself …”.
152
Freedom of Information interactions with HM Treasury Figure B1: First response from HM Treasury (1st Page).
153
Freedom Is More Than Just A Seven-Letter Word Figure B2: First response from HM Treasury (2nd Page).
154
Freedom of Information interactions with HM Treasury Rather than bog up the Freedom of Information website, I decided to take Paul Morran up on this offer to contact him further. So I sent the following e-mail: Dear Sirs, I recently submitted a Freedom of Information request that can be read via this link: _creation_of_money It was responded to very courteously by your colleague Mr. Paul Morran. However the fundamental question was only answered by default. Nevertheless that default answer is now the law-of-the-land, in other words now becomes a part of established Common Law. Based on that situation, and under Common Law courtesy, I am now writing to you for further - more detailed - answers in the form of specific clarifications. Please remain assured that I do not wish to 'pull rank'. That is, by being a Member of the Public. A Human Being who, by virtue of my supreme and absolute power, colludes with others of the same rank to provide your ultimate authorisation for existence as 'HM Treasury'. You may consider that your authorisation derives from empowerment by Government Statute. That is fair enough, but who empowers the Government? The Queen? Wrong answer, because who empowers the Queen? There is only one answer. Those with the power to do that. Which is us, the Human Beings who populate this Country of ours.
155
Freedom Is More Than Just A Seven-Letter Word We empower the Queen via the Coronation Oath. We empower the Government by elections. You cannot give someone, or even some 'body' (such as a group of representatives), more than you, yourself, possess. Consequently no-one can empower either the Monarch, or the Government (or HM Treasury) with more power than they, themselves, possess. All this is just saying one thing: If I ask a question with due courtesy, I have the inalienable Right to have it answered courteously, IN FULL, on pain of perjury and full commercial liability, and IN TRUTH (as far as is practicable). You have extended Common Law courtesy until now. And I have responded as courteously as was (I think) possible. And I sincerely hope that will continue. So now I ask you ('money' is henceforth in quotes as defined by Mr. Morran in his original answer): 1) Who authorises the creation of 'money'? Upon whose signature (or signatures) is it created? 2) For what reason is AN AMOUNT created? 3) Do you hold a Live Birth Trust (or some such) for each individual who is alive? If so, is the Reference Number the same as a National Insurance Number, and is any such account 'named' to the legal fiction PERSON of that individual? And, furthermore, if this is the case, is the associated Human Being Prime Creditor on the account? There may be more questions, depending on your truthful answers, which I trust can be responded to within a matter of a few days at the very most.
156
Freedom of Information interactions with HM Treasury If there is any reason why you cannot give answers, then please be so kind as to direct me to a source of them. I thank you in anticipation, Sincerely, without ill-will, frivolity or vexation, Veronica: of the Chapman family as commonly called, a live Human being with a living soul. "Veronica: Chapman", for short (there is no "Ms.", "Miss" or "Mrs.", because those are legal fiction PERSONS and not my Human Self. Only my Human Self has (a) a Mind with which to devise these questions and interpret/comprehend the answers and (b) Eyes with which to read the answers) And I received back the letter shown in Figures B3 & B4. I analysed this response as follows: My requests seem to find their way back to Paul: of the Morran family. He is turning into being one of my favourite people of all time. Notice he addresses me as Veronica: of the Chapman family! But what does his response mean?
157
Freedom Is More Than Just A Seven-Letter Word Figure B3: Second response for HM Treasury (1st Page).
158
Freedom of Information interactions with HM Treasury Figure B4: Second response from HM Treasury (2nd Page).
159
Freedom Is More Than Just A Seven-Letter Word Well, first of all we are being directed to the Currency Act 1983. At the time of writing I have not looked at this, but certainly will. (Now been looked at ... see below) More importantly, in my view, we now have it in writing that: "currency is issued in response to demand". And: "If demand exceeded availability, users would be constrained to make greater use of cheques and electronic transfers". Very curious way of saying something? Because what, exactly, is it actually saying? Finally Paul: Morran goes on to deny the existence of Live Birth Trusts, and any connection with one's National Insurance Number. An interesting response, all told, but it begs so many questions: 1. “currency is issued in response to demand”? Whose demand? Maybe this is covered in the Currency Act? 2. “If demand exceeded availability, users would be constrained to make greater use of cheques and electronic transfers”. If demand exceeded availability? Whose demand ... see above. 'Availability' ... whaaaaat? Paul has already told us that: 'money has no value'. 'The availability of something without value' means what? 'Money' is nothing more than an idea, a belief. The availability of beliefs is infinite. 3. 'users'? Is that us? I assume so. But that is not, necessarily the case. It could easily mean just Banks, Building Societies, etc. Those who directly interface with HM Treasury. I'm not sure what this means. 4. And: “these users would be constrained to make greater use of cheques and electronic transfers”? To do what? To pass 'money' around, but what money? Where is it
160
Freedom of Information interactions with HM Treasury coming from (to be passed around under constraints)? All in all, this seems to be totally circular. Well, almost. I think progress is being made, slowly but surely. I can't see how anything here actually contradicts anything else I've said, except that we are having Live Birth Trusts dismissed. I find the latter so hard to believe. Accounting and bookkeeping practices absolutely scream some kind of mechanism like that, tied to the National Insurance Number. They could not possibly run a free-for-all system. It is against the ingrained robotic nature of any Accountant. Accounts must add up. Otherwise Accountants have no 'profession' to speak of. And why, in that case, is our National Insurance Number demanded left, right, centre, on all 'official paperwork', and a considerable amount of 'private', or 'non-official', paperwork? And, subsequently, after reading most of the Currency Act: This just seems to deal with the standards for minting, etc. (As if it makes any difference to a Belief System. An Idea. An Illusion) Notice ... there it is again: 'bank notes' means notes of the Bank payable to bearer on demand. Totally circular. Chasing the roots of 'money' will have you running round in circles. You might as well chase rainbows or unicorns, which is the same thing. Everyone would get the actual idea if the banknote said: “I promise to pay the Bearer on demand 5 unicorns”. Which would be just as true as what it actually says. However there was one bit I laughed at: “(2) For the purposes of this section, the limit is £13,500 million or such other amount as may from time to
161
Freedom Is More Than Just A Seven-Letter Word time be specified in a direction given by the Treasury.” Yea ... tell that to Gordon Brown. So. No. We still don't know the answers to the questions I asked. These are: 1. How is 'money' created? (How is the belief manifested in the form of Tokens?) 2. For what reason is 'an amount' created? 3. Who looks at that reason, decides it is valid, and therefore authorises the creation of 'an amount'? 4. How is 'an amount that has been created passed into circulation'? Who is it passed to, and why? And the answers are contained within this book. Because there is no other way. Why am I so concerned about this? Is it because I want buckets of it? Actually no, that's not the reason at all. I would like to see us get rid of it once and for all. The reason I'm so concerned is because I don't like having the michael taken out of me. That's the reason. And I don't see why the michael should be taken out of everyone else, either. That's the reason. And I don't see why people of all shapes, sizes and ages should be bombed, shot, maimed, killed, tortured, put through excruciating agonies, enslaved in the most draconian manner ... all based on a mickey-take. That's the main reason. So I sent another e-mail. This is what I said: PLEASE FORWARD THIS E-MAIL (AS NECESSARY) TO YOUR COLLEAGUE PAUL: MORRAN Dear Paul: of the Morran family, I cannot thank you enough for the responses you have already made. I don't know whether or not you are irritated by my
162
Freedom of Information interactions with HM Treasury persistence. I hope not, because the questions I've asked affect yourself, your family, your friends, and everyone else. I fully appreciate that you have strived manfully to answer the questions I have raised in the past. But we still have not got to the heart of the matter. Thank you for the reference to the Currency Act 1983, but - by my reading - that only defines the standards for coinage and banknotes such as to be acceptable legal tender, and does not really answer my questions. May we please start again? May I please ask you the following question? "Is HM Treasury the SOLE authority that regulates the issuance of 'an amount' INTO CIRCULATION at any point in time?" (This does not mean the production of coins and/or banknotes that represent 'money'. You have already answered that as the Royal Mint and the Bank of England, respectively) What I'm trying to get to is: Who tells the Royal Mint to issue a certain number of coins? Who tells the Bank of England to issue a certain number of banknotes? Who ... if not HM Treasury? Best + thanking you in anticipation + apologies if you find this irritating, Veronica: of the Chapman family. The response I received is Figures B5 & B6.
163
Freedom Is More Than Just A Seven-Letter Word Figure B5: Third response for HM Treasury (1st Page).
164
Freedom of Information interactions with HM Treasury Figure B6: Third response from HM Treasury (2nd Page).
165
Freedom Is More Than Just A Seven-Letter Word I decided it was time to pull out all the stops, so I sent the following e-mail: Dear Paul, Thank you once again for your kind response. You say, in (5) you are disappointed at my statement about ‘not yet having got to the heart of the matter’ and that you have to consider the resources available to answer me. I understand that, of course. However I do write on behalf of not just myself. All the information you have provided is valuable, in my humble opinion. And many others are watching this correspondence which is - after all - public information, of course. I would say that your answers have, actually, moved the situation a little closer to the heart of the matter each time, and some progress has been made. OK. Well, in (5) you say that you do not understand what the heart of the matter is for me. May I then please try to explain, as far as I am able? The heart of the matter, what I'm trying to get to, was actually in my very first FoI question. And I suggested an answer, and requested confirmation or denial. I suggested that money was created on the basis of Promissory Notes. And, in your first response, you said that this was true "in essence". But you did not say it was true "in fact". Which is different. So, the heart of the matter is this: 1. What, precise, mechanism causes the release of 'some amount'? It must require some authority. Whose authority?
166
Freedom of Information interactions with HM Treasury 2. What defines 'the amount'? 3. How does this created money 'get into circulation'?, 'because the banks demanded it'. But this is very unusual, as I'm sure you will agree. Hence all the fur)
167
Freedom Is More Than Just A Seven-Letter Word Now that is what I consider to be the heart of the matter. That's what I asked. Those are my understood answers. Am I right or am I wrong? Have I made my standpoint clear? Kind regards + thanks for your kind attention, Veronica: of the Chapman family I received the response shown as Figure B7. I decided to partially give up (although not completely), and sent back on passing shot: Dear Paul: of the Morran family, Thank you for your e-mail. I specifically gave you the answers to the questions I actually asked, in terms of confirmation or denial. I did not wish to do that, because I did not wish to be accused of putting words into your mouth, preferring instead to rely on your intellectual honesty. But, as our correspondence progressed, you left me no choice. You did not deny my suggested answers. But, of course, you did not confirm them either. I leave you to consider whether or not intellectual honesty reined supreme. Anyway, I will assume you have done your best in very trying circumstances (i.e. 'someone like me'), and so I will just say thank you for the information you did provide. The link to the Bank of England you supplied, goes to a page that mainly comprises Sponsorship Adverts and information about Interest Rates. I know I mentioned Interest Rates in my previous email, but that was only in the nature of an example.
168
Freedom of Information interactions with HM Treasury I care not one jot about any Rates of Interest, and did not ask any questions about them. Simply because the mechanism for creating money does not create sufficient to cover any Interest at all. This leaves the entire economy (in total) in perpetual, never-ending, 'can-never-be-paidoff' debt - as I'm sure you can understand. Or, perhaps you can tell me how the monies to create the Interest are produced? Well, no, because you refuse to confirm how the Principal is even created ... so I won't even bother to ask. You hoped to 'allay my fears'. Did I give the impression I was fearful in any way? If so, then I humbly apologise. That was never my intent. I care not one jot about counterfeiting either. With respect, I think that is the Bank of England's problem, not mine. Any perceived value that results from counterfeiting activities is only the same as the perceived value of the banknotes themselves. And you have already told me the banknotes themselves are intrinsically worthless. Consequently those notes issued by the Bank of England have as much worth as counterfeit banknotes, do they not? So why is counterfeiting a problem? No need to answer that last question because the only difference is that counterfeit notes are not issued under 'authority'. But whose authority ... that's the question. Which specific person provides, or specific persons provide, the authority? Do they work for HM Treasury? What are their names & Official Titles? And how do they decide how much fiat paper to authorise at any one time? And why? On what basis is authority for issuance granted? That's what I asked - over an over again.
169
Freedom Is More Than Just A Seven-Letter Word But it's quite plain those questions must remain officially unanswered. Except that we know. That's how we knew what questions to ask, of course. Not confirmed ... but NOT denied. I doubt you have heard the last of this because, as you so rightly say, others are catching on. For some reason they (a) Understand what I'm getting at and (b) Seem to think my questions are reasonable, and should be fully answered in detail. Regards + thanks for your help, anyway, Veronica: of the Chapman family. What is the result of all this? Well, we have a flat denial that a 'Live Birth Trust Account' exists. But we have no denial that it is not called by some other name: 'Exemption Account', or 'Redemption Account' are two suggestions. We have a flat denial that this is tied to National Insurance Numbers, but we have no denial that it may be linked to Birth Certificate Numbers. We have no denials because we have not asked these questions, in the appropriate way, is my best guess. We have been given reasonable suspicion that the questions need to be asked in a specific way, otherwise denial is obviously possible. If you use the wrong name, then the fact that it does not exist is perfectly deniable. We have no explanation for the fact that our National Insurance Numbers are required on just about every scrap of Officious Paperwork. We are left to wonder why that should be. And we have not had a denial that my suggested answers to: “How money is created” were in any way incorrect. And denial would have been a piece of cake. All it would have amounted to was: “I can confirm that you are wrong”. So, there it sits. At the time of writing. But, as Freemanship opens out, the answers will, I firmly believe, have to be forthcoming. The questions I have
170
Freedom of Information interactions with HM Treasury asked strike right into the heart of the illusion. One must expect a certain amount of resistance.
171
Freedom Is More Than Just A Seven-Letter Word Figure B7: Fourth response from HM Treasury
172
Freedom of Information interactions with HM Treasury But then, none of this should be a surprise. It appears that a genuinely-concerned MP, by the name of Stokes, had a go at trying to find out something, along similar lines, back in the 1940s. He did not succeed either. All he received were smarmy, devious, dismissive, responses. Here's some Hansard on and around this subject: UNITED KINGDOM CORPORATION. HC Deb 22 October 1940 vol 365 c942W 942W § Mr. Craven-Ellis: asked the President of the Board of Trade whether the formation by the Government of the United Kingdom Corporation is only a war-time measure; and will he give assurance that the corporation will be wound up immediately after hostilities cease, so that the export trade may flow through its normal peace-time channels? § Mr. Johnstone: The corporation was formed with a view to meeting difficulties in overseas trade which are due to conditions arising out of the war. It is impossible to foresee the conditions that will obtain when hostilities cease and, therefore, I cannot say whether at that date it will be desirable to terminate the activities of the corporation. These activities do not, I think, disturb the normal channels of trade but I can assure my hon. Friend that His Majesty's Government have every desire that trade should be freed from war-time restrictions and be conducted in a normal manner at the earliest possible date. UNITED KINGDOM COMMERCIAL CORPORATION HC Deb 18 April 1944 vol 399 cc39-42W 40W
173
Freedom Is More Than Just A Seven-Letter Word § Mr. Parker :asked the Chancellor of the Exchequer if he will give a list of the names of the present directors of the United Kingdom Commercial Corporation, together with a list of other directorships which they hold. § Sir J. Anderson: The list of directors of the United Kingdom Commercial Corporation and of other directorships held by them is as follows: [Please note: Many, if not all, of these people are now dead. The interesting part, for research purposes, is the Companies involved] Sir Francis Joseph, Bt., K.B.E., D.L. (Acting Chairman) Directorships held: Settle Speakman and Company Limited. Mossfield Colliery Limited. Bignall Hill Colliery Company Limited. Stirrup and Pye Limited. Fenton Collieries Limited. Stafford Coal and Iron Company Limited. Timber and Wood (Merseyside) Limited. A. & S. Henry and Company Limited. Blaw-Knox Limited. London Midland and Scottish Railway Company Limited. Birmingham Railway Carriage and Wagon Company Limited. Midland Bank Limited. Midland Bank Executor and Trustee Company Limited. Rio Tinto Company Limited. Birmingham Small Arms Company Limited. Birmingham Canal Navigations. Dundalk, Newry and Greenore Railway Company. Mr. A. Chester Beatty Directorships held: American Metal Company Limited. Boart Products, Limited.
174
Freedom of Information interactions with HM Treasury Consolidated African Selection Trust Limited. Consolidated Diamond Mines of South West Africa Limited. Mufulira Copper Mines Limited. Northern Rhodesia Power Corporation Limited. Rhodesian Selection Trust Limited. Roan Antelope Copper Mines Limited. Selection Trust Limited. Seltrust Investments Limited. Sierra Leone Selection Trust Limited. Trepea Mines Limited. Union Corporation Limited. United Kingdom Commercial Corporation (Portugal) Limited. Selection Manufacturing Company Limited. Central Mining and Investment Corporation Limited. Karamiat Estates Limited. Mr. G. A. McEwen Directorships held: Co-operative Wholesale Society Limited. Chinese Purchasing Agency. United Kingdom Commercial Corporation (Spain) Limited. *Lord Swinton, Minister Resident in West Africa, still retains the post of Chairman of the Corporation. Sir Frank Nixon Directorships held: United Limited. United Limited. United Limited. United Limited. United Limited. United Limited. Kingdom Commercial Corporation (Spain) Kingdom Commercial Corporation (Portugal) Kingdom Commercial Corporation (Ethiopia) Kingdom Commercial Corporation (Egypt) Kingdom Commercial Corporation (Eritrea) Kingdom Commercial Corporation (Iran)
175
Freedom Is More Than Just A Seven-Letter Word United Kingdom Limited. United Kingdom Limited. United Kingdom Limited. United Kingdom Lebanon) Ltd. United Kingdom Africa) Limited. Commercial Corporation (Iraq) Commercial Corporation (Palestine) Commercial Corporation (Sudan) Commercial Corporation (Syria and Commercial Corporation (East
Mr. J. H. Hambro Directorships held: Hambros Bank, Limited. Hambro Trust, Limited. Ashdown Investment Trust, Limited. British and Continental Banking Company, Limited. John Dickinson and Company, Limited. United Kingdom Commercial Corporation (Spain), Limited. United Kingdom Commercial Corporation (Portugal), Limited. United Kingdom Commercial Corporation (Ethiopia), Limited. United Kingdom Commercial Corporation (East Africa), Limited. United Kingdom Commercial Corporation (Egypt), Limited. United Kingdom Commercial Corporation (Eritrea), Limited. United Kingdom Commercial Corporation (Iran), Limited. United Kingdom Commercial Corporation (Iraq), Limited. United Kingdom Commercial Corporation (Palestine), Limited. United Kingdom Commercial Corporation (Sudan), Limited. United Kingdom Commercial Corporation (Syria and Lebanon), Limited.
176
Freedom of Information interactions with HM Treasury Mr. C. P. Lister Directorships held: R. A. Lister and Company, Limited. Blackstone and Company, Limited. S.A. R. A. Lister et Cie. Mr. L. C. Paton Directorships held: Harrisons and Crosfield (Canada), Limited. Harrisons and Crosfield (Borneo), Limited. Harrisons, Barker and Company, Limited. Wilkinson Rubber Linatex, Limited. Wilkinson Sales Corporation (Canada), Limited. British Borneo Timber Company, Limited. United Kingdom Commercial Corporation (Portugal), Limited. United Kingdom Commercial Corporation (Spain), Limited. Captain J. A. Leighton Directorships held: Stelp and Leighton, Limited. J. H. Wackerbarth and Company, Limited. Southampton Steamship Company. Crete Shipping Company. Sark Motorships, Limited. Guernsey, Alderney and Sark Steamship Company. R. C. Hardman Sons, Limited. United Kingdom Commercial Corporation (Portugal), Limited. Lionel Edwards, Limited, Calcutta, India and any associated or subsidiary companies registered in India, Burma or Ceylon, and including the name "Lionel Edwards" in their title. United Kingdom Commercial Corporation (Spain), Limited. Mr. E. J. Shearer Directorships held: Molyneux et Cie, Limited. Survey and General Loan Company, Limited.
177
Freedom Is More Than Just A Seven-Letter Word
Mr. A. D. Campbell Directorships held: Forbes, Campbell and Company, Limited. George and R. Dewhurst, Limited. Manchester Ship Canal Company. Waring and Gillow (19312), Limited. Martins Bank (Manchester Branch). Manchester Chamber of Commerce. Mr. E. H. Lever Directorships held: Richard Thomas and Company, Limited. Glasbrook Brothers, Limited. Clayton Tin Plate Company, Limited. Gravesend Steel and Tinplate Company, Limited. H. F. Spencer and Company, Limited. Lancaster's Steam Coal Collieries, Limited. Monks, Hall and Company, Limited. New Sharlston Collieries Company, Limited. R.T. Metal Productions, Limited. Richard Nevill and Company, Limited. S. J. Burrell Prior, Limited. South Wales Tinplate Corporation, Limited. Swansea Navigation Collieries, Limited. W. Gilbertson and Company, Limited. Whitehead Thomas Bar and Strip Company, Limited. New Money (Creation) HC Deb 18 April 1944 vol 399 cc30-1 30 § 58. Mr. Stokes: asked the Chancellor of the Exchequer whether he will in future have recourse to the creation of new money without interest instead of adding to the volume of bank advances to the Treasury as this would be no more inflationary and would cost the country less. § Sir J. Anderson: No, Sir. § Mr. Stokes: Will the Chancellor explain why it is preferable in the national interest to create new money with interest rather than create new money without?
178
Freedom of Information interactions with HM Treasury § Sir J. Anderson: My hon. Friend knows very well that I do not accept his monetary theories. He really cannot expect me to argue the matter with him at Question time. New Money HC Deb 27 April 1944 vol 399 cc924-5 924 § Mr. Stokes: asked the Chancellor of the Exchequer how he keeps check of the amount of new money created. § The Chancellor of the Exchequer (Sir John Anderson): I do not find it necessary to attempt any such record as my hon. Friend suggests. § Mr. Stokes: But that is not an answer to my Question. Am I to understand from the Chancellor that he keeps no check on the amount of new money brought into circulation? § Sir J. Anderson: I keep no such check as my hon. Friend seems to have in mind. If he will study the White Paper, published on Tuesday—which he will find a veritable mine of information—perhaps he will then be good enough to indicate to me just what practical purpose he thinks such a record or check as he has in mind would serve. § Mr. Stokes: But is the Chancellor aware that competent authorities are of the opinion that something in the order of £1,500,000,000 has been created by the banks since the war began, at little cost to the banks and at great cost to the community? Does he not think it is his responsibility to see how much new money has been created? Surely it b a matter of business. § Sir J. Anderson: My hon. Friend referred to "competent authorities," but I am aware that the question of who is a competent authority is also a matter of opinion. Government Stock (Interest Payments) HC Deb 11 May 1944 vol 399 cc2086-7 2087
179
Freedom Is More Than Just A Seven-Letter Word § Mr. Graham White: asked the Financial Secretary to the Treasury if consideration has been given to the desirability of saving labour and paper by making arrangements for the payment of interest on 2½ per cent. Consols and other Trustee Securities by half-yearly instead of quarterly payments. § Mr. Assheton: Yes, Sir. As regards Government stocks on which dividends are paid quarterly, it has been established that in view of the limited amount of debt involved, no appreciable saving of labour or paper would be achieved by the suggested alteration. The arrangement has definite advantages, for certain classes of investors. A change of practice would require amendment of the law, and I do not think that a case has been made for it.
180
Freedom of Information interactions with HM Treasury International Monetary Fund (Joint Statement) HC Deb 16 May 1944 vol 400 c31 31 § Mr. Stokes: asked the Chancellor of the Exchequer whether the British experts who collaborated in drawing up the Joint Statement by experts on the establishment of an International Monetary Fund were Treasury officials; and, if not, from what organisations were they selected. § Sir J. Anderson: Yes, Sir. Apart from Lord Keynes, the United Kingdom experts who collaborated in drawing up the Joint Statement were permanent Treasury officials and whole-time temporary officials who have been in the service of the Government throughout the war. § Mr. Stokes: Can the Chancellor assure the House that the whole-time temporary servants who have been in the employment of the Treasury for the period of the war are not drawn either from commercial or banking interests? § Sir J. Anderson: No, Sir, I do not think I could give such an assurance as that.
181
Freedom Is More Than Just A Seven-Letter Word
Appendix C: Magna Carta 1215
T
his is the Magna Carta 1215. The original one. It contains within it wording to the effect that it cannot be superseded. It stands behind all other Law, specifically Statute Law. The reason is simply that there was no such thing as 'Parliament' when this Treaty was enacted between the Nobility (at the time) and the Monarch (at the time – King John). As a consequence any Parliamentary Statute is bound by it. Any Statute that attempts to supersede it is null & void in Law. This renders all Parliamentary Statutes either (a) Null & void or (b) Ineffective - since they can only quote Common Law anyway, and it is pointless to enforce something that is already in force as Law. And this renders each and every one of the 111,000plus Statutes, enacted on the basis of implementing EU Directives, as totally pointless wastes of time & effort. All you have to do is know. And stand up for yourself. You have an ‘EU Referendum’. 24 hours per day, 7 days per week. Some of the most important sections of the Great Charter have been highlighted in bold italics:
182
Magna Carta 1215
183
Freedom Is More Than Just A Seven-Letter Word
184
Magna Carta 1215
185
Freedom Is More Than Just A Seven-Letter Word
186
Magna Carta 1215
187
Freedom Is More Than Just A Seven-Letter Wordworthy
188
Magna Carta 1215
189
Freedom Is More Than Just A Seven-Letter Word.
190
Magna Carta 1215 .
191
Freedom Is More Than Just A Seven-Letter Word ,
192
Magna Carta 1215.
193
Freedom Is More Than Just A Seven-Letter Word [55] All fines made with us unjustly and against the law of the land, and all amercements imposed unjustly and against the law of the land, shall be entirely remitted, or else let them be settled by the judgment of the twentyfive barons who are mentioned below in the clause for securing the peace [See Article
194
Magna Carta 1215
195
Freedom Is More Than Just A Seven-Letter Word
196
Magna Carta 1215five.
197
Freedom Is More Than Just A Seven-Letter Word mentioned and many others. Given by our hand in the meadow which is called Runnymede between Windsor and Staines on the fifteenth day of June, in the seventeenth year of our reign.
198
Notice of Understanding and Intent and Claim of Right
Appendix D: Notice of Understanding and Intent and Claim of Right
Y
ou. Quite obviously you cannot claim Rights that are otherwise unavailable to you under Common Law. You cannot, for example, claim the Right to breach the peace, murder someone, or defraud someone. However what you can do is to state specific instances of what you consider the Truth to be ... in your specific case. You do this by stating what you understand the situation to be. You then state, categorically, your intention to live in peaceful co-existence with everyone else. You then make claims based on that. You provide this Notice to whomsoever you think needs to know. You can use the maxim of: “Service to Principal is considered service to Agent, and service to Agent is considered service to Principal”. This means that, in any organisation, one hand is responsible for telling the other hand what is going on. I now include (below) my own, which was sent to the UK Home Office in March, 2009. I did not get any response, and thus received no objections in the time period. Of course, they were just ignoring me ... as if I didn't count. However the test will come should anything untoward happen to me. Each clause is numbered. I did this in order to resolve any objections easily. I included a Fee Schedule for any
199
Freedom Is More Than Just A Seven-Letter Word transgressions against me. I used 'terms of imprisonment', but could have set 'monetary amounts'. The terms of imprisonment can be anything I choose, and any monetary amounts likewise. I did not set monetary amounts for the simple reason that 'money' is an illusion. This was sent with an appropriate covering letter explaining the need to create any necessary 'services to Agents'. My NOUICOR (as it is called for short) is on the following pages. It should be noted that I do not have to exercise all the Claims I have made. They can be left in abeyance for as long as I determine the need to leave them unused. These are My Claims. My Rights. I can utilise them in whatever way I choose, and as I see fit. Notice of Understanding and Intent and Claim of Right I, Veronica: of the Chapman family, hereinafter known as Veronica: Chapman, a flesh and blood human being in possession of a sovereign and individual spirit, a living soul, do hereby make Oath and state the following is My Truth and My Law: [010] Whereas it is my understanding that in terms of earthly existence there is no species more supreme than a living, breathing, imaginative human being blessed with a living soul, and [020] Whereas it is my understanding that it is impossible to distinguish one soul from any other, and therefore all souls must at all times and in all situations be considered equal in all respects in any fair, just and reasonable context, and [030] Whereas it is my understanding that anything and everything must in practice derive from the aforesaid axioms, and [040] Whereas it is my understanding that any numerical grouping of such souls can be referred to as 'people', and [050] Whereas it is my understanding that a society is, in essence, nothing more than a grouping of likeminded souls since it is defined as a number of
200
Notice of Understanding and Intent and Claim of Right people joined by mutual consent to deliberate, determine and act for a common goal, and [060] Whereas it is my understanding a statute is defined as a legislated rule of a society, and [070] Whereas it is my understanding a legislated rule of a society can be given the force of law to act upon, or lawfully bind, all members of that society, and [080] Whereas it is my understanding if a living soul chooses by free will not to be a member of any society then statutes created by said society do not bind that soul to said statute law, and [090] Whereas it is my understanding a living soul who chooses by free will not to be a member of any society can be referred to as a Freeman-on-theland, and [100] Whereas it is my understanding a Freemanon-the-land remains entirely and solely under Common Law jurisdiction, and [110] Whereas I Veronica: Chapman am a Freemanon-the-land, and [120] Whereas it is my understanding that all authority possessed by elected representatives must inherently derive from those who elect said representation, and [130] Whereas it is my understanding that if I have the right to empower representation by casting a vote then I am empowered to represent myself, and [140] Whereas it is my understanding that the right of empowerment does not derive from any government otherwise it would be possible for a government to revoke it, and [150] Whereas it is my understanding that if the right to empower representation were revoked then no representation would thereafter be possible, and
201
Freedom Is More Than Just A Seven-Letter Word [160] Whereas it is my understanding the only form of government recognized as lawful in the United Kingdom is a representative one, and, [170] Whereas it is my understanding representation requires mutual consent, and [180] Whereas it is my understanding that in the absence of mutual consent neither representation nor governance can exist, and [190] Whereas it is my understanding the United Kingdom is a Common Law jurisdiction enjoying the protection of Common Law, and [200] Whereas it is my understanding equality before the law is paramount and mandatory, and [210] Whereas it is my understanding that for something to exist legally it must have a name, and [220] Whereas it is my understanding that the UNITED KINGDOM is in reality a corporation in Chapter 11 bankruptcy and thus still allowed to trade, and [230] Whereas it is my understanding that by virtue of my birth within the boundaries of my Country England I am a single share owner in said UNITED KINGDOM CORPORATION, and [240] Whereas it is my understanding all Acts are statutes restricted in scope and applicability by the British Constitution and Common Law, and [250] Whereas it is my understanding a statute being defined as a legislated rule of a society is, within the United Kingdom, in fact a rule of said UNITED KINGDOM CORPORATION, and [260] Whereas it is my understanding rules of a corporation are limited in applicability to those who are agents of said corporation, and [270] Whereas it is my understanding those who have a National Insurance Number are in fact employees of the government and thus are bound
202
Notice of Understanding and Intent and Claim of Right by the statutes created by the said government, and [280] Whereas it is my understanding that it is lawful to abandon one’s National Insurance Number while at the same time not affecting the right to any pension claim based on National Insurance Contributions previously paid, and [290] Whereas it is my understanding people in the United Kingdom have a right to revoke or deny consent to be represented and thus governed, and [300] Whereas it is my understanding if anyone does revoke or deny consent they exist free of government control and statutory restraints, and [310] Whereas it is my understanding that a claim of right establishes a lawful excuse, and [320] Whereas it is my understanding that if one has lawful excuse one may choose to not obey a court, tribunal, statute, Act or order, and [330] Whereas a Freeman-on-the-Land has lawfully revoked consent and does exist free of statutory restrictions, obligations, and limitations, and [340] Whereas it is my understanding that I, Veronica: Chapman as a Freeman-on-the-Land, acting peacefully within community standards, would not in that capacity breach the peace, and [350] Whereas it is my understanding that all existing courts and governments are de facto only and not de jure, and [360] Whereas it is my understanding that a woman acting as Elizabeth Alexandra Mary Windsor did take the throne of England on the Second Day of June, Nineteen Hundred and Fifty Three, and [370] Whereas it is my understanding that during a Coronation ceremony said woman acting as Elizabeth Alexandra Mary Windsor was asked by a man acting in the role of the then Archbishop of Canterbury "Will you solemnly promise and swear
203
Freedom Is More Than Just A Seven-Letter Word?" and she responded "I solemnly promise so to do", and [380] Whereas it is my understanding that this ceremony did install said woman as Queen of England and the United Kingdom, and [390] Whereas it is my understanding that on or after the Seventeenth Day of October Nineteen Hundred and Seventy Two said woman did sign into statute an Act of Parliament known as the European Communities Act of Nineteen Hundred and Seventy Two (ECA1972) which accepted without my consent a treaty known as the Treaty of Rome, and [400] Whereas it is my understanding that the terms of the Treaty of Rome are counter in many respects to the “respective laws and customs” of those nations of which said woman is Queen including England which is my Country of birth, and [410] Whereas it is my understanding that anyone who participates in allowing or by culpable neglect enabling my Country to be governed in any way by any foreign power is an act of treason as defined by the British Constitution, and [420] Whereas it is my understanding, therefore, that by signing of the ECA1972 as opposed to dissolving by Royal Prerogative the Parliament that created the treacherous Act was in itself by collusion an attempted act of treason against my Country, and [430] Whereas it is my understanding that as a Freeman-on-the-Land in this common law jurisdiction that I have the duty to stand in defence of the United Kingdom and its people against
204
Notice of Understanding and Intent and Claim of Right foreign armed troops who attempt to invade, govern or police me or my Country, and [440] Whereas it is my understanding that this duty is not affected by agreements made by treasonous and de facto government agents, and [450] Whereas it is my understanding that agreements made on behalf of the United Kingdom by traitors to the United Kingdom do not bind the people of United Kingdom, and [460] Whereas I do firmly and truly believe the aforementioned agreement is an overt act of treason, and [470] Whereas I honourably refuse to be bound by agreements made by traitors such as said Elizabeth Alexandra Mary Windsor in collusion with the then Prime Minister Edward Heath, and [480] Whereas it is my understanding that any peace officer who co-operates with foreign armed troops to govern or regulate the population is also committing treason, and [490] Whereas it is my understanding that historically the purpose of a national armed force was to ensure that foreign powers never invaded and governed under a gun, and [500] Whereas it is my understanding that the existence of armed foreign troops patrolling and policing our streets would be evidence of a war fought unsuccessfully, and [510] Whereas it is my understanding that agreeing or conspiring to agree to allow armed foreign troops to patrol and police our streets is an act of treason, and [520] Whereas it is my understanding that any action for which one can apply for and receive a licence must itself be a fundamentally lawful action, and
205
Freedom Is More Than Just A Seven-Letter Word [530] Whereas as I not a child and I am a Freemanon-the-Land who operates with full responsibility and I do not see the need to ask permission to engage in lawful and peaceful activities, especially from those who claim limited liability, and [540] Whereas it is my understanding that I have a right to use my property without having to pay for the use or enjoyment of it, and [550] Whereas it is my understanding that all ‘public transportation' is in fact and actuality public property to which I have the right of use and access without having to pay, and [560] Whereas it is my understanding peace officers have a duty to distinguish between statutes and law and those who attempt to enforce statutes against a Freeman-on-the-Land are in fact breaking the law, and [570] Whereas it is my understanding that I have the power to refuse intercourse or interaction with peace officers who have not observed me breach the peace, and [580] Whereas it is my understanding that permanent estoppel by acquiescence barring any peace officer or prosecutor from bringing charges against a Freeman-on-the-Land under any Act is created if this claim is not responded to in the stated fashion and time, and [590] Whereas it is my understanding that the Common Law right to travel on the highways without license provided one is not engaging in commerce thereupon is lawful and still exists although it does appear to have been deceptively hidden, and [600] Whereas the Road Traffic Acts of the United Kingdom do make it possible for peace officers in the role of policy enforcement officers to stop an automobile in order to provide services and demand something of value, and
206
Notice of Understanding and Intent and Claim of Right [610] Whereas it is my understanding that if they are not providing a service they have no reason to stop any one and if proof of registration, insurance and licence is not valuable they have no need to ask for it, and [620] Whereas it is my understanding that I have the right to refuse to interact or co-operate with criminals, de facto government agents or grossly negligent peace officers, and [630] Whereas it is my understanding that if I have the power to elect a representative and empower them to appoint peace officers then I also have the power to appoint directly, and [640] Whereas it is my understanding that if I have the power to appoint directly or by proxy I must have the power to fulfil those duties my self, and [650] Whereas it is my understanding that the United Kingdom Police Force although having an illustrious history has had members recently acting in a grossly criminal manner which does tarnish the previous history and record, and [660] Whereas it is my understanding that the Law provides remedy at all times, even against rogue or negligent peace officers and de facto governments apparently hijacked by soulless corporate interests, and [670] Whereas it is my understanding that in order to be a peace maker and deal with rogue and possibly armed police officers who fail to act with respect to the code of Common Law I will need use of and access to firearms of equal or greater power then those people who act criminally have access to, and [680]
207
Freedom Is More Than Just A Seven-Letter Word [690] Whereas it is my understanding that this creation of a person and transfer of authority is not fully disclosed to the parents and if it was all good parents would refuse to register their offspring, and [700] Whereas it is my understanding that the person and the human being to which it is associated are two very separate and different things and that the people playing roles in government only have the right to act upon the person, and [710] Whereas it is my understanding that if I do not exist in association with a person I cannot be lawfully governed by the people playing roles in government, and [720] Whereas it is my understanding a by-law is defined as a rule of a corporation, and [730] Whereas it is my understanding corporations are legal fictions and require contracts in order to claim authority or control over other parties, and [740] Whereas it is my understanding that a summons is merely an invitation to attend and those issued by the Ministry of Justice or its franchises which are de facto corporations create no obligation or dishonour if ignored, and [750] Whereas it is my understanding legal fictions lack a soul and cannot exert any control over those who are thus blessed and operate with respect to that knowledge as only a fool would allow soulless fictions to dictate one’s actions, and [760] Whereas it is my understanding that the people in the government are merely playing roles, and [770] Whereas I AM NOT PLAYING, and [780] Whereas it is my understanding that I am not obliged to obey the orders of any one claiming to be a Queen or King or those acting on behalf of such an insane entity, as no one who does make
208
Notice of Understanding and Intent and Claim of Right preposterous claims that abandon and erode the concept of equality has any authority over me, and [790] Whereas it is my understanding that I can use a Notary Public to perform duties found under any Act including thus they have the power to hold court and hear evidence and issue binding lawful judgments, and [800] Whereas it is my understanding that a Notary Public can also be used to bring criminal charges to bear against traitors, even if they hold the highest office, and [810] Whereas it is my understanding that there may be more of this to follow [820] Therefore be it now known to any and all interested, concerned or affected parties, that I, Veronica: Chap. [830] Be it also now known to any and all interested, concerned or affected parties, that I, Veronica: Chapman as a Freeman-on-the-Land and do hereby serve notice and state clearly specifically and unequivocally that I would never conspire nor would I in any way entreat others to disobey the Common Law of the Land which ensures peaceful co-existence. [840] Furthermore, I claim that these actions are not outside my communities’ standards and will in fact support said community in our desire for truth and maximum freedom. [850] Furthermore, I claim the right to engage in these actions and further claim that all property held by me is held under a claim of right.
209
Freedom Is More Than Just A Seven-Letter Word [860] Furthermore, I claim. [870] Furthermore, I claim it is my right and solemn duty not only to keep the peace My Self but also to intervene wherever may be necessary to ensure that the peace is kept in a situation where peace officers are not present or are unwilling for whatever reason to uphold their sworn and solemn duty so to do. [880] Furthermore, I claim that the identity of My Self is forever possible to establish correctly by my Presence as a living, breathing, Human Being with a soul together as may be necessary sworn attestations from friends, family, and other associates. Furthermore I claim that this supersedes any necessity to obtain or carry any form of external token such as an Identity Card for any lawful purpose of establishing my true identity for the simple reason that no such token can ever represent the sovereign soul with which I am blessed. [890] Furthermore, I claim that the courts in The United Kingdom are de-facto and bound by the Law and Equity Acts and are in fact in the profitable business of conducting, witnessing and facilitating the transactions of security interests and I further claim they require the consent of both parties prior to providing any such services. [900] Furthermore, I claim all transactions of security interests require the consent of both parties and I do hereby deny consent to any transaction of a security interest issuing under any Act for as herein stated as a Freeman-on-the-Land I am not subject to any Act.
210
Notice of Understanding and Intent and Claim of Right [910] Furthermore I claim ownership of my single share in the corporation known as the UNITED KINGDOM and demand a copy of said share such that I will become the shareholder and thereby be in the position of exercising my own voting rights. Furthermore I claim to receive the corresponding dividends for as long as said UNITED KINGDOM operates under the illusion that ‘money has some value’ (notwithstanding the fact that ‘money has no value’ has been admitted by HM Treasury. Evidence of this admission can be supplied, and is anyway publicly available). [920] Furthermore I claim that my inalienable Natural Right to Trial By Jury for any apparent transgressions on my part, including an inalienable Natural Right of Habeas Corpus, and these shall not under any circumstances be infringed. [930] Furthermore I claim the right to be entirely free to determine my own medication needs at all times and never under any circumstances be forced to ingest or otherwise receive into my body by way of vaccination, electro-magnetic energy, audio or visual energy or any other method any substance or alien energies I do not consent to accept. [940]. [950] Furthermore, I claim the right to fulfil my duty to shoot any foreign troops in the United Kingdom who are armed and attempting to police or govern me or my fellow countrymen without consent and to view them as an invading force which must be lawfully attacked. And I further claim to right to nominate as many deputies as may be necessary
211
Freedom Is More Than Just A Seven-Letter Word who by their own free will and consent are prepared to assist me in fulfilment of this duty to my Country. [960] Furthermore, I claim the law of agent and principal applies and that service upon one is service upon both. [970] Furthermore, I claim the right to deal with any counterclaims or disputes publicly and in an open forum using discussion and negotiation and to capture on video tape said discussion and negotiation for whatever lawful purpose as I see fit. [980] Furthermore, I claim my SCHEDULE for any transgressions by peace officers, government principals or agents or justice system participants or agents of the medical profession or any other parties who trespass upon and thus unlawfully hinder My Peaceful Self, Veronica: of the Chapman family, as defined in attached Schedule A. [990] Furthermore I claim the right to use a Notary Public to conduct due process of the aforementioned SCHEDULE against any transgressors who by their actions or omissions harm me or my interests, directly or by proxy in any way. Affected parties wishing to dispute the claims made herein or make their own counterclaims must respond appropriately within FOURTEEN (14) days of service of notice of this action. Responses must be under Oath or Attestation, upon full commercial liability and penalty of perjury and registered at the Place of Claim of Right provided no later than fourteen days from the date of original service as attested to by way of certificate of service. Schedule B is available for the resolution of any objections. Failure to register a dispute against the claims made herein and then successfully defeating these claims in a proper court of law will result in an automatic default judgment securing forevermore
212
Notice of Understanding and Intent and Claim of Right all rights herein claimed and establishing permanent and irrevocable estoppel by acquiescence barring the bringing of charges under any statute or Act or regulation against My Self Freeman-on-the-Land Veronica: Chapman for exercising these lawful and properly established rights, freedoms and duties.
213
Freedom Is More Than Just A Seven-Letter Word Place of Claim of Right: _________________________________ Dated: __________________________________ Claimant: Veronica: of the Chapman family ____________________________ ____________________________________________________ Independent Witness 1: ____________________________ Address: _________________________________________ _________________________________________ _________________________________________ _________________________________________ ____________________________________________________ Independent Witness 2: ____________________________ Address: _________________________________________ _________________________________________ _________________________________________ _________________________________________ ____________________________________________________ Independent Witness 3: ____________________________ Address: _________________________________________ _________________________________________ _________________________________________ _________________________________________
214
Notice of Understanding and Intent and Claim of Right Schedule A Penalty term of imprisonment to apply to each and every individual reasonably involved in the transgression, including all senior officers or line managers as accomplices in law. Transgression My Self being questioned, interrogated or in any way detained, harassed or otherwise regulated My Self handcuffed, transported, incarcerated or subjected to any adjudication process that is outside Common Law jurisdiction My Self forced to suffer the effects of what has come to be known as a non-lethal or less-thanlethal weapon such as a Taser My Self forced to undergo any ingestion of energies or substances forced onto or into my body, whether under to guise of medication or not, without my expressly notarised consent My Self being attributed anything I did not actually speak or write in the event that my written or Penalty Term of Imprisonment 1 year
2 years
5 years
10 years
5 years.
215
Freedom Is More Than Just A Seven-Letter Word spoken communications are shown to be tampered with
216
Notice of Understanding and Intent and Claim of Right Schedule B Objections and Resolutions.
217
Freedom Is More Than Just A Seven-Letter Word Schedule C Supportive Understandings.
218
Notice of Understanding and Intent and Claim of Right Schedule D
Additional Claims.
219
Freedom Is More Than Just A Seven-Letter Word
Appendix E: Summary of Freeman Principles
T
here is a lot of information in this book, and it may take a few reads in order for the whole situation to sink in. You may also find the need to explain to others. I write this Appendix for those reasons, fundamentally to explain exactly 'where the Freeman is coming from' It goes like this. A Statute is "a legislated rule of a Society". A Society is "a group of like-minded individuals who come together to deliberate, determine, and act towards common goals". Those are the definitions. A dictionary can be consulted in order to verify them. For anything to exist in Law it must have a Name, to which it can be referred. As far as a Society is concerned, it must also have a Membership. Individuals apply for Membership when they consider the "common goals" are those they can support. For this to occur, the Society must have defined its goals in the first place … such that Applicants can know whether or not the "common goals" are those that can be supported by Membership. If, at any time, a Member determines that he or she can no longer support the Society's espoused goals, then he or she has the ability to RESIGN Membership. That's a Society, and Statues are the legislated rules it sets for itself. Application for Membership is an application to agree to be bound by the Society's rules. Since Statutes only bind CURRENT Members of any Society, they have no affect on non-Members. This is identical to the Policy (Company Rules) of any Company, since a Company is the same thing as a
220
Summary of Freeman Principles Society. Fundamentally, in terms of 'status', the employees of a Company are indistinguishable from Members of a Society. So, before Statutes can be used to bind an individual in Law, a number of proofs need to be forthcoming: 1. Proof that the Society has a Legal Name, by which it can be uniquely identified; 2. Proof that the Society has set, and published, its Common Goals; 3. Proof that the individual has applied for Membership, and said application was accepted; 4. Proof that the individual has not subsequently resigned. Subject to all of the above proofs, an individual is bound, in Law, by the Statutes of the Society of which s/he is a Member. In this case, by applying for Membership, the individual CONSENTED TO BE BOUND. If any one of the above cannot be proved, then an individual is only bound, in Law, by the Statutes of the Society, IF HE OR SHE CONSENTS TO BE BOUND. In any/all other cases, the individual is not bound by the Society's Statutes, in Law. So ... before going any further ... indeed before taking one more breath ... the above statements need to be rebutted IN SUBSTANCE ... or, by silence and/or lack of rebuttal ... ACCEPTED. That's by anyone, and everyone, with whom we may be forced to interact. 'Legal obligations' are always addressed to a Named Party. You are not a Name. You are a sovereign flesh & blood Human Being, with a living soul, and not a Legal Fiction Name, such as "MISS VERONICA CHAPMAN" (or any variation). You are not a Name, because a Name is merely marks on paper, pixels on a computer screen, or sound pressure waves in the air, when spoken.
221
Freedom Is More Than Just A Seven-Letter Word Now, some may ask: "What's the difference?" But the difference is enormous. It's the difference between the marks on the paper (etc.), and a flesh & blood creature that is 'aware' - in other words something that is 'conscious'. Now, the point is - and this is what it is really all about (if you think about it): How do you grab the attention of a creature that is 'aware'? When you want that attention? How do you grab the attention of a flesh & blood creature? Well … simple … you CALL IT! You CALL it by 'what it is commonly called'! This one, the one writing this book, is COMMONLY CALLED as: “Veronica”! And, since there is more than one Veronica in the world, the Caller may need to be a bit more specific … and so add my clan/tribe/family to the calling, and to call: “Veronica: of the Chapman family”. When I'm CALLED this way, you get my attention! Hey! It works! The Legal Fiction Names used, e.g. "MISS VERONICA CHAPMAN" (and so on), are actually the Names of little ships. Little ships that the Vatican considers it owns. When one writes to these little ships, they should send their letters to the Vatican, not to me. Why does the Vatican do this (via the UK Government)? Very simply because most people think that they are their Legal Fiction Name, and respond accordingly. This places them, by tacit consent, as CONSENTING MEMBERS TO THE STATUTES QUOTED. It's a deception, of course. One is never told this, is one? Well, they never told me, but we've found out. So the deceptions don't work any more. (The Internet is a wonderful thing, if used for something other than just typing "big tits" into a Search Engine) Here's one more point. A Name is not the flesh & blood. A Name is ATTACHED to the flesh & blood. Usually by one's parents, at birth. You "GIVE the child a Name", don't you? You GIVE it a Name. It doesn't have one, as
222
Summary of Freeman Principles the flesh & blood comes into the world, so you GIVE it a Name. The Name is ATTACHED. And this is provable by the fact that a Deed Poll can DETACH a Name, and ATTACH a different one. (Just the same as re-naming a ship, where the old name is blotted out, and the new one painted over). If someone says to me: “Are you Veronica Chapman?” … the truthful answer is: “No, I'm not a Name”. If someone says to me: “Are you the flesh & blood sovereign Human Being, with a living soul, to which the Name Veronica Chapman is ATTACHED, at this moment in time?” … then I have to say: “Yes, it seems like that”, in order to remain truthful. (But I'm never asked that question, in that way. Am I?) My Self, the Human Being, the flesh & blood, attention grabbed by calling Veronica: of the Chapman family, remains solely under the Common Law jurisdiction of England. Provided I do not: 1. 2. 3. 4. Breach the peace; Cause deliberate harm to anyone else; Cause deliberate loss to anyone else; Use deviousness in my promises & agreements …
… then I do not violate any tenet of Common Law. And, if anyone thinks that I may have done, then the mechanism of Trial by Jury exists to try me, and find me innocent or guilty, as its verdict. Doesn't it? They can take me to Court if they like. But I'll just claim Common Law jurisdiction, and ask the Court if it has Common Law jurisdiction. Unless there is a Jury sitting, the Court will have to answer: “No”. So I will ask the Court what jurisdiction it has over My Self. And it will be forced to admit that, while it may have jurisdiction over the MATTER, it has NONE over My Self whatsoever. Obviously I would be asking the Court to prove that I am a CURRENT Member of the Society whose subsisting
223
Freedom Is More Than Just A Seven-Letter Word regulations the Claimant & the Court are attempting to impose … so they'd better be ready to rebut just about everything I wrote about Statutes & Societies, above. This might cause them a bit of a problem, since what I wrote was the plain, unvarnished, truth. No Statute is above Common Law. Statutes are bound by Common Law. If they exceed Common Law, then they are null & void. And that's the Law-of-the-LAND (which is Common Law … and actually nothing more than Common Sense). The reason for this is simple. Common Law/Common Sense was around long before 'Parliament' and 'Government' were invented. These entities were invented under Common Law/Common Sense … not above it. 'Not above it', because only a complete pillock would ever claim to somehow "Do better than Common Sense", surely? Consequently only such a pillock would claim that Parliament could "Do better than Common Sense/Common Law". So, what is Parliament doing? You tell me! It certainly isn't "Doing better than Common Sense", is it? Because that's impossible, isn't it? Any argument to the effect that, because I have a vote, I am somehow bound by the Statutes, is entirely spurious. For the following reason. Before any Member of Parliament can take a seat in the House of Commons, they must swear allegiance to the reigning Monarch. Not to those poor suckers who did their so-called 'civil duty', and put an "X" against said MP's Name. Consequently the allegiance of those 650+ showers of shit is not to you & I, it is to the Queen. She might very well be bound by what they decide, but - since their allegiance is not to you & I - we are not so bound. How can we be? If Human "A" makes a promise to Human "B", Human "C" is not bound by that promise. I'll just throw in a couple of other maxims from old Roman Law (we were under Roman Occupation at one time in our history).
224
Summary of Freeman Principles The first one is "Consensus Facit Legem" … which, translated, means "CONSENT MAKES LAW". Consent. Consent! The Law can only be made by consent. How many people, do you think, would consent to pay Income Tax, Road Tax/SORN etc. if anyone actually dared to ask directly? Bear in mind what I've written about the Grand Deception of 'money'. Why, do you think, the Government is so shitscared of any Referendum? On anything? The EU, Road Tax … anything? Because they would not obtain consent. And the majority know that, as well as I do. The Irish most certainly do, as in: “Keep voting Ireland … we will grind you down until you say “Yes’”. They can only gain consent by grinding us down. (However, the consent is really just a plea to “stop the grinding”). Consent makes Law … and they do not have consent. You know it. I know it. The other maxim is "Let he who will be deceived, be deceived". So don't be deceived. And then we have 'Contracts'. We are constantly DECEIVED into making Contracts we did not realise we were making. However, any and all Contracts we have been DECEIVED into making are null & void, IN LAW, on the basis of: 1. Lack of full disclosure by the other Party 2. Lack of any Contractual Consideration being offered by the other Party entirely from its own resources. 3. Lack of lawful Terms & Conditions, under Common Law. The deceptions are crimes under Common Law. And one final, final thing. If anyone thinks - for one second - that all a Freeman is doing is trying to 'taxdodge', then they'd need to think that again, on top of everything else. And here's the reason.
225
Freedom Is More Than Just A Seven-Letter Word The so-called 'Government' was elected to look after the roads, infrastructure & health care etc. And to protect our freedoms … not to erode them continuously. As such, they are given the power to create a 'Monetary illusion', via HM Treasury. We let them create whatever they decide they need. Don't we? (How/where does money come from then?) So, if ANY Government Agency (e.g. HM Revenue & Customs) wants money, then they can get all they need from the MAKERS … HM Treasury! They are the ones who make it! Don't ask us! Why ask us? We don't make it! Tell me … why can't HM Revenue & Customs, and the DVLA, etc. get all their money from those who create it? Why do they need to bother us? What, precisely, is the point in bothering me? Or any of us? We elect the Government to look after these things … we give them the power to create as much 'money' as they would ever need … and the very first thing they do is demand it from us!!! Huh???!!! If it wasn't so bloody serious, and utterly, preposterously, absurd, it would actually be hilarious! It's perfectly true, isn't it? Plain Common Sense, isn't it? (And the answer, by the way, is that 'the money' has to pass through us for one reason, and one reason only: TO CONTROL US. 'Money' is nothing more - and nothing less - than a Mind-Fuck. It serves no other practical purpose). The sooner everyone comes to terms with this, and stops deceiving people, the better for all concerned. As the deceptions become more & more exposed, I just hope the Great British Public (in fact everyone on this planet) has mercy on the souls of these so-called 'Government Agencies'. Now it's been said. No-one, having read this, can claim ignorance any longer.
226
Summary of Freeman Principles Unless and until these Freeman Principles are rebutted, IN SUBSTANCE, they stand as the REALITY, and the TRUTH, in LAW.
227
Freedom Is More Than Just A Seven-Letter Word
228
229
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview. | https://www.scribd.com/document/34291143/Freedom-is-More-Than-Just-a-Seven-Letter-Word | CC-MAIN-2016-50 | refinedweb | 47,321 | 73.98 |
This is one of these very simple programming puzzles I came across recently: given a function returning random integers from
0 to
4 inclusive with equal probability, write a function returning random integers from
0 to
6 inclusive.
Of course the solution should also return equally distributed numbers. So let’s start from an input function sample definition:
def rand4() = (math.random * 5).toInt
Your task is to implement
rand6() by only using
rand4(). Give yourself few minutes and continue reading.
The first approach is pretty straightforward but happens to be completely broken:
def rand6() = rand4() * 3 / 2
As simple as that. In ideal solution each output value from
0 to
6 should appear with the probability of
1/7. Can you tell from the code above, what’s the probability of
rand6() returning
2 or
5? That’s right, it’s no more than
0, you’ll never get these values. I hope it’s clear why. So let’s go for something more sophisticated:
def rand6() = (rand4() + rand4()) % 7
Looks better, but still pretty far. The code above has two major flaws. First of all the results of
rand4() + rand4() expression range from
0 to
8 but we need
0 to
6. The obvious solution is to use
% 7 operation. However this results in
0 and
1 being returned twice as often because
7 and
8 are overflowing to
0 and
1. So what about this:
def rand6(): Int = { val rand8 = rand4() + rand4() if(rand8 > 6) rand6() else rand8 }
I hope the recursion (which can easily be turned into loop, but I leave that work to the Scala compiler) is not obscuring the intent – if the sum of two
rand4() invocations is above expected result, we simply discard it and call
rand6() again. However there is still one subtle but striking bug, quoting Wikipedia on uniform distribution. The sum of two independent, equally distributed, uniform distributions yields a symmetric triangular distribution. If you don’t quite get the above, have a look at this live demo in JavaScript using
<canvas/> illustrating what Wikipedia means:
This program simply places pixels at random
(X, Y) positions on each panel. In the first panel I use one
Math.random() * 300 call scaled to fit whole canvas. As you can see the distribution is more or less uniform. But we can’t tell that about second and third panels. On the second panel I am using the sum of two uniformly distributed variables, in principle:
(Math.random() + Math.random()) * 150). Even though this expression can return anything between
0 and
300, the points are very biased toward the middle of the canvas (triangular distribution). The same behaviour is emphasized on the third panel where ten invocations of
Math.random() are used.
The correct answer
The approach I’m taking is based on the observation that
rand4() is capable of producing two random least significant bits. So let’s start from implementing
rand3() with known semantics:
def rand3(): Int = rand4() match { case 4 => rand3() case x => x }
rand3() returns uniformly distributed values from
0 to
3 doing so by rejecting
4 output of
rand4(). How will that help us? Well, we now have two random bits, each one being either
0 or
1 with 50% probability. We can easily widen it for larger sequences, e.g.
rand15() and
rand7():
def rand15() = (rand3() << 2) + rand3() def rand7() = rand15() >> 1
You should be rather comfortable with the bit fiddling above. Having the ability to produce two random bits I can easily generate 4 and 3. Now
rand6() is a no-brainer:
def rand6() = rand7() match { case 7 => rand6() case x => x }
Just to make this lesson a little bit more interesting, let’s implement
randN(n: Int) on top of
rand4().
randN() should return uniformly distributed natural values from
0 to
n. I’ll begin by implementing helper method
atLeastKrandBits(k: Int) returning… at least K random bits:
def atLeastKrandBits(k: Int): Int = k match { case 0 => 0 case 1 => rand3() >> 1 case 2 => rand3() case b => (atLeastKrandBits(k - 2) << 2) + rand3() }
Alternative implementation with
foldLeft():
def atLeastKrandBits(k: Int) = (0 to (k + 1) / 2).foldLeft(0){ (acc, _) => (acc << 2) + rand3() }
…or if you really hate those to maintain your code:
def atLeastKrandBits(k: Int) = (0 /: (0 to (k + 1) / 2)){ (acc, _) => (acc << 2) + rand3() }
Having any of the implementations above
randN(n: Int) is simple:
def randN(n: Int) = { val bitsCount = java.lang.Integer.highestOneBit(n) val randBits = atLeastKrandBits(bitsCount) if(randBits > n) randN(n) else randBits }
Conclusions
You might ask yourself a question: why should I even care? If you fail to understand probability distribution your application might produce random output that’s actually quite easy to predict. It’s not a big deal if you are writing a game and enemies are more likely to appear at some places on the map (but the players will discover and abuse it!) But if you need random numbers for security reasons or you rely on uniform distribution e.g. for load-balancing purposes – any bias might become fatal.
Reference: Probability distribution for programmers from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog.
Hello,
I think you could do with rand4 function only (and some additional function, say F)
First divide 0..4 to two sets containing 2 arbitrary integers each, e.g {0,1} and {3,4}
F would return 0 if rand4 returned 0 or 1 and 1 if rand4 returned 3 or 4 (or run rand4 again if there was 2)
Then you generate binary sequence, and the first 3-element fragment of it different from, e.g 111 (but again, this is arbitrary, but taken for simplicity as it is 7 in binary) is our random number from 0..6. The are of course 8 different 3-element sequences, but all of them are equally probable, 1/8, and we are only interested in space of 7, so (1/8)/(7/8) gives us 1/7
Rgds, | https://www.javacodegeeks.com/2013/01/probability-distribution-for-programmers-2.html | CC-MAIN-2017-17 | refinedweb | 1,001 | 60.35 |
i thought that by assigning them to the initialization of the int of each it would work, but i cannot tell if it is...is it?i thought that by assigning them to the initialization of the int of each it would work, but i cannot tell if it is...is it?Code:#include<iostream> #include<cstdlib> #include<ctime> #include<iomanip> #include<iostream> #include<fstream> using namespace std; //function prototype int pp (int&); int score = 0; void main() { ofstream outfile("A:\\0F1017_6_2.txt"); if(!outfile){ cerr << "Cannot open output file" << endl; } srand((unsigned) time(0)); int a = 0(.56); int b = 0(.44); int aa = 0; int bb = 0; ............................ //my function is: int pp (int &score) //function pp {score = ( rand() % 2); return score;}
should i be expressing the chances in the random expression of the function?
thanks Michele/scuba22 | http://cboard.cprogramming.com/cplusplus-programming/27137-chance-assignment-random.html | CC-MAIN-2014-42 | refinedweb | 139 | 71.14 |
How to Add variables to a Tuple
In this article, we will learn to add variables in a tuple in Python. We will use some built-in functions, simple approaches, and some custom code as well. Let's first have a quick look over what is a tuple in Python.
Python Tuple
Python has a built-in data type called a tuple. Data inside a tuple can be of any type say, integer, string or a float value, or even a tuple type. The tuple uses comma-separated values within round brackets or parentheses to store data. Tuples can be defined using any variable name and then assigning different values to the tuple inside the round brackets. The tuple is ordered, unchangeable, and allows duplicate values.
tuple1 = ("Ram", "Arun", "Kiran") tuple2 = (16, 78, 32, 67) tuple3 = ("apple", "mango", 16, "cherry", 3.4)
As we know that Tuples are immutable objects in Python. We cannot perform addition, deletion, modification operations on tuples once created. So, in order to add variables or items in a tuple, we have to create a new tuple instead of modifying the original tuple. Let us discuss various ways to add variables or values in a tuple.
Example: Adding Variables to a Tuple
A tuple can be created using Python Variables. Variables are initialized with some values to store in the form of a tuple. Users can even take inputs for the variables. This example shows how you can add existing values and build a tuple. Variable names are stored inside round brackets or parentheses and then the values associated with these variables are printed in the form of a tuple.
name = "John" age = 40 location = "London" details = (name, age, location) print(details)
('John', 40, 'London')
Example: Adding Variables to a Tuple using vars() Function
This example uses an inbuilt
vars() function which acts like a
locals() function. func() initialized three variables and passed them to another function maketuple(). maketuple() takes variables and their names as arguments.
tuple() is used to convert and store the 'n' number of variables in a tuple type. This method is used in complicated cases.
def maketuple(variables, names): return tuple(variables[n] for n in names) def func(): x = 23 y = 45 z = 67 return maketuple(vars(), 'x y z'.split()) print(func())
(23, 45, 67)
Example: Convert Tuple to a List to Add Items in a Tuple
This method adds items to an already created tuple. It simply converts the original tuple into a list and adds items using
append() function of the list. It then converts the new lists back to the tuple. This method is generally used when the user has to pass a tuple as a function argument, which is often necessary for the NumPy functions.
input_tuple = ("apple", "banana", "mango") #converts to list list1 = list(input_tuple) #adds new item to the list list1.append("strawberry") #converts list back to tuple input_tuple = tuple(list1) print(input_tuple)
('apple', 'banana', 'mango', 'strawberry')
Example: Add Items to a Tuple by Defining a New Tuple
We cannot change an existing tuple but can create a new tuple and concatenate the old tuple using
+operator. If you want to add a single element, make it a singleton like (3,). You can add a tuple of multiple elements with or without that trailing comma. The trailing comma is necessary for the singleton to avoid confusion between an element in parentheses.
tuple1 = (1, 2, 3) tuple2 = tuple1 + (4, 5, 6) print(tuple2) print("Adding to an empty tuple:") t1 = () t2 = t1 + (1,2) print(t2) t3 = t2 + (3,) print(t3)
(1, 2, 3, 4, 5, 6)
Adding to an empty tuple:
(1, 2)
(1, 2, 3)
Note: If you do not add the trailing comma, you will get the following error.
TypeError: can only concatenate tuple (not "int") to tuple.
Conclusion
In this article, we learned to add variables and values to a tuple in Python by using several methods. We used some simple algorithms like concatenation, defining a new tuple, converting tuple to a list, and using the vars() function to add existing values to a tuple. We discussed that all these methods cannot change the existing tuple instead created a new tuple. | https://www.studytonight.com/python-howtos/how-to-add-variables-to-a-tuple | CC-MAIN-2022-21 | refinedweb | 699 | 61.87 |
See my new blog at .jeffreypalermo.com
I labeled this post as 200 instead of 100 because I imagine that beginners in .Net won't be creating their own custom collection classes. I think once someone can create their own custom collections, they should be considered at least intermediate.
Today a colleague approached me with a problem. He was foreaching through a custom collection in C#, and when he evaluated the object he wanted, he need the index of that object for the collection. He was approaching the problem with calls to GetEnumerator(), etc, and I shared with him what I do for this situation:
public int IndexOf(object value)
{
return base.InnerList.IndexOf(value);
}
When I create my own collection types, I normally expose all the helper methods of the InnerList so that my collection is as functional as possible. Inheriting from CollectionBase just strongly types the ArrayList object for you. With generics in v2.0, if you don't need any extra functionality from your collections, then you'll just want to go with ArrayList<T> or you can use the new Collection<T> class:
public class Junk<T> : Collection<T>
{
private int m_myExtraMember;
public Junk(int myExtraMember)
{
m_myExtraMember = myExtraMember;
}
public new int IndexOf(T value)
{
return base.IndexOf(value);
}
}
With v2.0 and generics, you may still want to implement your own custom collections if you need to track a member that isn't included, but still, this method is simplified. I have overriden the IndexOf() method unnecessarily just to show some syntax. With 2.0, all you would need is the m_myExtraMember field. IndexOf is inherited.
Another tip about collections: Know what data structure the collection uses internally. Collection<T> uses the List<T> structure internally which is similar to ArrayList in that it keeps the objects in the same order in which they were inserted. With HashTable-based collections, the objects are retrieved via key, and the order is not guaranteed, so if you foreach on a HashTable, you can never know in what order the objects will be retrieved. I hope this post helps | http://codebetter.com/blogs/jeffrey.palermo/archive/2004/08/18/22497.aspx | crawl-002 | refinedweb | 350 | 54.83 |
January 12, 2017 | 4 min Read
I have recently switched from D3 v3.0 to D3 v4.0, and I have already encountered some important changes. For example, the scaling functions are quite different, and the old layouts available in the older API have been moved and renamed. In fact, D3 v4.0 is no longer a single library, but many small libraries (about 30) that are designed to work together.
For a weekend project I wanted to create a visualization of a simple graph with nodes and edges. In D3 v3.0 this can be done with
d3.layout.force. In D3 v4.0 this is a job for
d3.forceSimulation.
I started looking for JSON files that contained the necessary information to represent a small social network graph. To my surprise, I didn’t find any. Instead, I found some small network data sets as GML files here and here. I had never heard of the GML file format before, but since I liked these data sets I decided to proceed. At the end of the article you can see a visualization of a small social network of dolphins (62 nodes, 159 edges). The original file (
dolphins.gml) was found on this page of the University of California Irvine.
The Graph Modelling Language, not to be confused with the Geography Markup Language, is a portable file format for graphs.
A GML file looks like this:
# dolphins.gml Creator "Mark Newman on Wed Jul 26 15:04:20 2006" graph [ directed 0 node [ id 0 label "Beak" ] node [ id 1 label "Beescratch" ] # more nodes here... edge [ source 8 target 3 ] edge [ source 9 target 5 ] # more edges here... ]
It doesn’t look to different from a JSON file, but the problem is that D3 cannot load it directly. After a brief Google search I found out that I could use a Python library to load the GML file and convert it into JSON.
NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. It’s distributed with a BSD license and was developed by Aric Hagberg, Dan Schulz and Pieter Swart.
In NetworkX one can create graphs for undirected and directed networks, add and remove nodes and edges in different ways, visualize the network and export network data to draw it with an external tool.
In order to visualize the network data you can use the
networkx.draw function and save the image as a PNG with
matplotlib.
import networkx as nx import matplotlib.pylab as plt g = nx.read_gml('dolphins.gml') nx.draw(g) plt.savefig('dolphins.png')
Apparently there must be some randomness when the figure gets generated, because I ran the code twice and I got 2 different PNG images.
Here is the first one:
and the second one:
The network data can also be exported and visualized in a program like GraphViz or Gephi, or, like I will do here, in D3.
I didn’t play with NetworkX too much, but from what I’ve seen the documentation is great. There is also a nice presentation here.
Here is the snippet of code to convert a GML file into a JSON file:
import networkx as nx import simplejson as json from networkx.readwrite import json_graph # parse the gml file and build the graph object g = nx.read_gml('dolphins.gml') # create a dictionary in a node-link format that is suitable for JSON serialization d = json_graph.node_link_data(g) with open('dolphins.json', 'w') as fp: json.dump(d, fp)
Note that the GML file I used with the latest NetworkX version (1.11) caused the Exception
networkx.exception.NetworkXError: cannot tokenize u'graph' at (2, 1). I downgraded NetworkX to version 1.9.1 as suggestes in this thread and it worked fine. Another approach would have been to format the GML file in a different way.
Finally, with the network data available as
dolphins.json, we can use
d3.json to read it. Drag a node or hover on it to know the name of the dolphins in this network!
The file
dolphins.gml contains an undirected social network of frequent associations between 62 dolphins in a community living off Doubtful Sound,
New Zealand, as compiled by Lusseau et al. (2003).).
Additional information on the network can be found in: | https://www.giacomodebidda.com/visualize-gml-files-with-d3/ | CC-MAIN-2019-09 | refinedweb | 725 | 66.94 |
Python VS Other Languages
This is the Second part of this article series- ‘Python Chapters’. In this article, you are going to learn why to use python or at least, you will get posits about several types of “How’s” and “Why’s” about python. That’s why I had given it a name Python Vs Other Languages. It will give you a warm feel of python. VS Other Languages
In this second part we are going to learn about python and several other programming languages. Am going to compare several programming languages with python using some basis concepts and example.
So let’s explore them, one by one:
Python VS JAVA
- As we know time complexity is directly proportional to, space. On behalf of this we can compare both Python and Java. Python snippet runs much slower in comparison to Java snippets.
- Python snippet takes very less memory in comparison to Java. That’s why space complexity of python is better than Java.
- Python snippet required much effort as compared to Java.
- Python snippet for a particular functionality requires less number of lines or statements in comparison to Java.
- Python snippet is 3-5 times shorter than a Java snippet for the same functionality.
- Java is categorized as low-level implementation language, on the other hand, Python is high-level or glue type language.
Example:
Snippet | Python
Print (“GoodBye World!”)
Snippet | JAVA
public class GoodByeWorld {
public static void main(String[] args)
{
System.out.println(“GoodBye World!”);
}
}
Output-
GoodBye World!
>>>
Python VS C++
- Python snippet is comparatively 5-10 times shorter than a C++ snippet for the same functionality.
- Python is a high-level language and C++ is low level.
- Python acts as a glue language that used to combine components written in C++.
- Python provides much flexibility in calling functions and returning values in comparison to C++.
- C++ snippets works faster than Python.
- Python is interpreted while C++ is a pre-compiled.
- Python uses Garbage Collection whereas C++ doesn’t.
Example:
Snippet | Python
Print (“GoodBye World!”)
Snippet | C++
#include <iostream>
void main()
{
cout << “GoodBye World!”;
}
Output-
GoodBye World!
>>>
Python VS Perl
- Perl emphasizes support for Common Application oriented Tasks (For Example: file Scanning, Report Generating etc.) on the other hand Python emphasizes support for Common Programming Methodologies (For Example: Data Structure Design, OOPs concepts etc.)
- Python is much more maintainable and reusable than a Perl Snippet.
- Python is High-level language on the other hand, Perl is middle level.
Example:
Snippet | Python
Print (“GoodBye World!”)
Snippet | Perl
print “GoodBye World!”;
Output-
GoodBye World!
>>>
Python VS JavaScript
- Javascript is all about classes while Python deals with simple functions and variables without getting engaged in class definition.
- Python provides better code reusability than JavaScript.
- Python is better in scalability and maintainability.
- Python is high-level language whereas JavaScript is low level.
Example:
Snippet | Python
Print (“GoodBye World!”)
Snippet | JavaScript
<html>
<head> </head>
<body>
<script>
alert(‘GoodBye, World!’)
</script>
</body>
</html>
Output-
GoodBye World!
>>>
Python VS TCL
- Python is rich programming language when we talk about data structure while TCL traditionally stores all data as a string.
- The Space complexity of python snippet is much less than of TCL.
- For extended functionality or high level of development- TCL lacks features (modular namespaces), that’s why TCL usually contains TCL extensions written in C. on the other hand, Python is stand alone and sufficient for any type of functionality and doesn’t require extensibility in any other language.
Example:
Snippet | Python
Print (“GoodBye World!”)
Snippet | TCL
$ vim GoodByeWorld.tcl
puts “GoodBye World!”
Output-
GoodBye World!
>>>
Python VS Smalltalk
- Python contains dynamic binding and dynamic typing on the other hands Smalltalk lacks both, however, it is also an object oriented language (First object Oriented Language.)
- Python contains a rich library. It has more features to deal with the internet, web such a www, FTP etc. on the other hand Smalltalk’s standard library of collection data types is refined.
- Smalltalk follows a monolithic approach while python has a different and separate development and environment distribution of code.
Example:
Snippet | Python
Print (“GoodBye World!”)
Snippet | Smalltalk
#include <stdio.h>
void main()
{
printf(“GoodBye World”);
}
Output-
GoodBye World!
>>>
Python VS PHP
- Python is much more maintainable than PHP.
- Python snippet executes much faster than PHP (95% faster)
- Python is better than PHP whenever we talk about developing better scalable applications.
- Python is much more stable and upward compatible than PHP.
- Python is object oriented language whereas PHP is structure based.
- Space complexity of python is much more less than python.
Example:
Snippet | Python
Print (“GoodBye World!”)
Snippet | PHP
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo ‘<p> GoodBye World!</p>’; ?>
</body>
</html>
Output-
GoodBye World!
>>>
Greetings! This is my first comment here so I just wanted to
give a quick shout out and tell you I genuinely enjoy reading through
your articles. Can you suggest any other blogs/websites/forums
that deal with the same topics? Thanks a lot!
Hey Buddy!
Glad, to hear that. Kindly, drop some mail and let us know whatelse you would like to explore. We’ll try our best to enhance your experience here. Cheers! 🙂
This content is really interesting. I have bookmarked it. Do you allow guest posting on your blog ? I can write hi quality posts for you.
Let me know. | https://www.letustweak.com/tutorials/python-vs-other-languages/ | CC-MAIN-2021-31 | refinedweb | 884 | 68.87 |
Posts58
Joined
Last visited
clipclicmusic's Achievements
Newbie (1/14)
0
Reputation
Get a refernce to the manager from the item
clipclicmusic replied to clipclicmusic's topic in TransformManager (Flash)Hi Jack Awesome... That's saved me a few hours of headscratching... BTW, I checked the source code. It was an interesting experience to see how code SHOULD be written
Get a refernce to the manager from the item
clipclicmusic posted a topic in TransformManager (Flash)What is the simplest way to get a reference to the manager from an item (that is managed) ie I have several managers... add an item to a manager, then later I have an action from that item, and want to get a reference to its manager (parent?) Any ideas? Thanks Jason
- Hi The crashing has been soled. I disabled "cacheAsBitmap" Not sure if this is general, or just that I was doing it over-zealously? Will post more when I know more Thx jason
- And in terms of memory, no more than a MB
- Huge? Not really 960x540 Is that too big?
MotionBlur
clipclicmusic posted a topic in GSAP (Flash)Is anyone else having trouble with motionBlur plugin crashing Flash ? I am getting this adl(479,0xa09d3540) malloc: *** mmap(size=1723478016) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug adl(479,0xa09d3540) malloc: *** mmap(size=1723478016) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug error: out of memory Haven't done much research as yet - this only started this morning. It only happens in one app, so I must have a goof in my code. Just wondering if anyone has had this problem ? Thx Jason
Copy or clone an object (sorta)
clipclicmusic replied to GreenSock's topic in TransformManager (Flash)Crumbs. That's neat !
- Hi Jack Have sorted all my 'problems' Thanks for the help Just one thing for anyone lookign for it, something that I got stuck on tonight - dropShadow in the Flash IDE has no alpha... the Tween plugin here has alpha's default set to 0... I had assumed it would default to 1, so when I did not specify the drop shadow was mysteriously not being applied. My goof, the docs state that alpha :Number [0] Best Jason
- Hi Jack Here you go When the shadow is on the object that is 'managed', all is fine When the drop shadow is on a child of the managed object, things go awry ! Best Jason
Crop and Drop Shadow
clipclicmusic posted a topic in TransformManager (Flash)Hi Jack The new crop functionality is great. BUT when I have a drop shadow on an object that is a child of the managed item, the crop functionality does not allow for the drop shadow, and cuts it off... Any way you can have crop account for drop shadows ? Best Jason PS : This change you just made : Crop and allowDelete Is something I hadn't noticed, but was about to come up against. Thanks !
JSON
clipclicmusic posted a topic in Loading (Flash)Hi Has anyone used Greensock for loading JSON ? i have a client wanting to use JSON, and bieng very 'Green' in both senses of the word, would prefer to use Greensock than the examples I found on the web. best Jason
dispatchEvent from withing a loaded clip
clipclicmusic replied to clipclicmusic's topic in Loading (Flash)Apologies that this turned out to be off topic.
dispatchEvent from withing a loaded clip
clipclicmusic replied to clipclicmusic's topic in Loading (Flash)Hi Jack Thank you for your speedy reply That nailed it. There are days (or rather evenings and caffeine-fueled nights) when it all seems so complex. When it isn't. Best Jason
dispatchEvent from withing a loaded clip
clipclicmusic replied to clipclicmusic's topic in Loading (Flash)Hi Jack I tried that, but get the same issue - until there is a mouse click, the listeners don't kick in... From what I can see, it is only after the mouse click event that my custom events start firing / being received correctly. Whether the rawContent stays in the SWFLoader or is added as a child Here is a simple mock up... I would really appreciate any pointers you can give. I imagine there is simply something I haven't understood in custom events. But I am flummoxed as to what. Thanks Jason
dispatchEvent from withing a loaded clip
clipclicmusic posted a topic in Loading (Flash)Hi I am trying (without success) to dispatch a series of custom events fro within an swf loaded using LoaderMax. I place the event listsners in the class that is loading the swf (call this parent)... addEventListener(GameEvent.SCORE_UPDATED, gameScoreUpdated) addEventListener(GameEvent.START, startGame) addEventListener(GameEvent.START_TURN, startTurn) addEventListener(GameEvent.COMPLETE_TURN, completeTurn) addEventListener(GameEvent.INIT, initGame) And place the dispatchEvent in the SWF that is loaded (call this child): dispatchEvent(new GameEvent(GameEvent.START)); dispatchEvent(new GameEvent(GameEvent.SCORE_UPDATED)); Etc etc What is driving me nuts is that the only events that the parent movie is capturing are those that happen when the mouse is clicked. The custom event bubbles public class GameEvent extends Event { /** @private **/ public static const VERSION:Number = 1.0; public static const INIT:String = "init"; public static const START:String = "start"; public static const COMPLETE:String = "complete"; public static const START_TURN:String = "startTurn"; public static const COMPLETE_TURN:String = "completeTurn"; public static const SCORE_UPDATED:String = "scoreUpdated"; public function GameEvent(type:String, bubbles:Boolean = true, cancelable:Boolean = false) { super(type, bubbles, cancelable); } public override function clone():Event { return new GameEvent(this.type, this.bubbles, this.cancelable); } } I cant see why my 'global, parent listener) is not capturing the events when the child class inits, starts etc... and yet DOES capture the custom events that are part of a mouse click event in the child (if that makes sense) Any pointers greatly appreciated ! Thx Jason | https://staging.greensock.com/profile/5702-clipclicmusic/ | CC-MAIN-2022-21 | refinedweb | 985 | 60.24 |
Radius < 1 on drawCircle draw unwanted results
Hi! I've been on and off on Haxe for the last year and half, I still feel like a total noob, and just recently I tried using HaxeFlixel, and I found it to be amazing! ;)
But I'm having a small problem using some of
FlxSpriteUtilon my
FlxSpriteobject: I just found out that using a float value that's less than 1 for the radius' value in
drawCircle()makes it draw a huge circle in the graphic I made, way larger than what I really need.
I'm drawing a circle and changing its radius dynamically on my object and when it gets below zero it just expands :sweat_smile:
Could somebody explain why this happens?
This is the current object's code:
import flixel.FlxG; import flixel.FlxSprite; import flixel.system.FlxAssets.FlxGraphicAsset; import flixel.util.FlxColor; using flixel.util.FlxSpriteUtil; class TransitionSpriteObject extends FlxSprite { public function new( ?X:Float = 0, ?Y:Float = 0 ) { super( X, Y ); makeGraphic( FlxG.width, FlxG.height, FlxColor.TRANSPARENT ); drawCircle( 32, 32, .5, FlxColor.WHITE ); } }
And this is what this outputs for me:
Thanks! :D
P.s.: for any admins that read this, I've accidentally posted this same thing on "Dev Logs". I have deleted the topic, but could you please purge that one, if possible? :sweat_smile:
- HappinessSam
If.
- DleanJeans
Yeah, it's actually documented explicitly in the API.
RadiusRadius of the circle (makes sure the circle fully fits on the sprite's graphic if < 1, assuming and and y are centered)
- DleanJeans
If you want to change the "radius dynamically", you will want to draw a bigger circle (since a 1 px radius circle is just a pixel or a square) and then change the
scaleof the sprite or use setGraphicSize() and then
updateHitbox(). For example:
setGraphicSize(0.5); // keeps the ratio if you don't pass in the height updateHitbox();
or
scale.set(0.25, 0.25); // make the circle 4 times smaller updateHitbox();: | http://forum.haxeflixel.com/topic/117/radius-1-on-drawcircle-draw-unwanted-results/2 | CC-MAIN-2020-34 | refinedweb | 330 | 57.06 |
We're in the process of starting to plan for a release of pip (the long-awaited pip 10). We're likely still a month or two away from a release, but now is the time for people to start ensuring that everything works for them. One key change in the new version will be that all of the internal APIs of pip will no longer be available, so any code that currently calls functions in the "pip" namespace will break. Calling pip's internal APIs has never been supported, and always carried a risk of such breakage, so projects doing so should, in theory, be prepared for such things. However, reality is not always that simple, and we are aware that people will need time to deal with the implications. Just in case it's not clear, simply finding where the internal APIs have moved to and calling them under the new names is *not* what people should do. We can't stop people calling the internal APIs, obviously, but the idea of this change is to give people the incentive to find a supported approach, not just to annoy people who are doing things we don't want them to ;-) So please - if you're calling pip's internals in your code, take the opportunity *now* to check out the in-development version of pip, and ensure your project will still work when pip 10 is released. And many thanks to anyone else who helps by testing out the new version, as well :-) Thanks, Paul | https://mail.python.org/pipermail/distutils-sig/2017-October/031642.html | CC-MAIN-2018-51 | refinedweb | 257 | 65.49 |
Namespace with utility functions. More...
Namespace with utility functions.
This namespace contains functions for computing message digests with cryptographic hash functions (md5, sha1), and functions that implement encoding and decoding for common encodings.
These utility functions can be accessed by including the
Wt/Utils.h header.
An enumeration for HTML encoding flags.
Performs Base64-decoding of data.
This utility function implements a Base64 decoding (RFC 2045) of the
data. Illegal characters are discarded and skipped.
Performs Base64-encoding of data.
This utility function implements a Base64 encoding (RFC 2045) of the
data.
When the crlf argument is true, a CRLF character will be added after each sequence of 76 characters.
Guess the image mime type from an image.
This function opens the image
file, reads the first 25 bytes and calls guessImageMimeTypeData() to infer the mime type.
Guess the image mime type from an image.
This function examines the header of an image and tries to identify the image type.
At the moment, it recognizes and returns as mime type :
The header should contain (at least) the 25 first bytes of the image data.
If no mime-type could be derived, an empty string is returned.
Performs Hex-decoding of data.
Illegal characters are discarded and skipped.
Performs Hex-encoding of data.
A hex-encoding outputs the value of every byte as as two-digit hexadecimal number.
Computes a hash-based message authentication code.
This utility function computes a HMAC, and returns the raw (binary) hash value. Takes as arguments the text to be hashed, a secret key, a function pointer to a hashfunction, the internal block size of the hashfunction in bytes and the size of the resulting hash value the function produces. A maximum blocksize of 2048 bits (256 bytes) is supported.
Performs HTML encoding of text.
This utility function escapes characters so that the
text can be embodied verbatim in a HTML text block.
Performs HTML encoding of text.
This utility function escapes characters so that the
text can be embodied verbatim in a HTML text block.
By default, newlines are ignored. By passing the HtmlEncodingFlag::EncodeNewLines flag, these may be encoded as line breaks (<br>).
Remove tags/attributes from text that are not passive. directly using JavaScript.
Modifies the
text if needed. When the text is not proper XML, returns
false.
Performs Url decoding.
This utility function percent encodes a
text so that it can be embodied verbatim in a URL (e.g. as a fragment).
Performs Url encoding (aka percentage encoding).
This utility function percent encodes a
text so that it can be embodied verbatim in a URL (e.g. as a fragment). | https://webtoolkit.eu/wt/doc/reference/html/namespaceWt_1_1Utils.html | CC-MAIN-2021-31 | refinedweb | 438 | 61.02 |
I.
Before we get invested in the example, let’s figure out what this tutorial is not. This is not a finding and installing a compiler tutorial. I’m on a Mac, but the experience for getting started with a compiler is different for all platforms. If you’re confused about compilers, you might start by looking at g++ and MinGW.
As the tutorial suggests in the title, we’re going to be doing a simple “Hello World” type application, common when going through the getting started content for a particular programming language.
Create a file titled main.cpp somewhere on your computer. Within the file, include the following:
#include <iostream> int main() { std::cout << "Hello World\n"; return 0; }
By using
cout we’re going to be using the standard output stream to write simple text to the screen followed by a new line character. By returning a zero we’re saying that our application ran without error, where as, a one would indicate an error.
To compile our application we can execute the following from the command line:
g++ main.cpp -o app
Assuming you’re using g++ as your compiler, the above command will compile our application and produce an output app file. The app file can be ran by executing the following:
./app
If everything went well you should see the text we defined previously outputted to the command line. We can do a little better when it comes to our application design though.
In our current code, notice that in the
std::cout operation that we’re including the
std namespace. Rather than including the namespace with each of our commands, we can actually define the namespace up front. Take the following revision to our project:
#include <iostream> using namespace std; int main() { cout << "Hello World\n"; return 0; }
While not a huge step up from what we had, it could potentially make your life a bit easier as the application grows.
Now that we know how to output data, we can attempt to collect user input and output what we’ve collected. Take the following changes to our application:
#include <iostream> #include<string> using namespace std; int main() { cout << "Hello World\n"; cout << "Input: "; string data; cin >> data; cout << "Output: " << data << "\n\n"; return 0; }
In the above code we’ve included a dependency for string data. After we display our “Hello World” text, we display some text to show the user that we’re looking to collect input. Before we collect the input we define a variable to hold it. Once we have our string in place, we can use the
cin operator for standard input stream data. When a terminating character is used, such as the return key, the data is output and at which point the application ends.
Try to run the application and use a whitespace character such as tab or space. You’ll probably notice that the first part of the input is displayed, but not the rest. When using
cin, the whitespace characters are considered terminating characters in the string. To get around this, we can do the following:
#include <iostream> #include<string> using namespace std; int main() { cout << "Hello World\n"; cout << "Input: "; string data; getline(cin, data); cout << "Output: " << data << "\n\n"; return 0; }
Notice that instead of using
cin the way we had previously, we are now using the
getline method. Unless you’re collecting numeric or boolean information, the
getline approach is probably better.
You just saw how to build a simple “Hello World” style application using C++. In this application we saw how to output data, input data, compile, and run the application. Compared to languages like JavaScript, it is very unforgiving, but incredibly powerful.
If you’re still trying to start started with a compiler, check out the GNU Compiler Collection or MinGW. | https://www.thepolyglotdeveloper.com/2018/08/building-hello-world-example-cpp-application/ | CC-MAIN-2019-26 | refinedweb | 641 | 60.45 |
.
22 Responses to “Installing PyQt on Mac OS X (Snow Leopard)”
[…] Art and Photography « Installilng PyQt on Mac OS X (Snow Leopard) […]
I seem to be having a problem…. it looks like it’s something to do (no doubt) with some previous attempt at install / build (which I no longer recall)…. somewhere / somehow, I’m getting the makefile populated with a library path of /tmp/qt-stuff/source/qt-everywhere-opensource-src-4.7.0-beta1/lib….
And it’s not just in this build (any clues appreciated).
[…] I’ve written about before. For a guide to installing Qt and Qt creator on Mac, take a look at this post. For Windows, instructions can be found […]
I don’t know what I am doing except following your step by step instructions.
When I am to the point where I am doing ‘python configure.py -d /Library/Python/2.6/site-packages/’ and I get the error ImportError:No module named sipconfig what do I need to do to fix that?
I tried copying the sipconfig.py from the site-packages folder to the pyqt folder and it seemed to be working and configureing took about 20 minutes but then at the end of that it said
ld: symbol not found
collect2: ld returned 1 exit status
make[1]: *** [libythonplugin.dylib] error 1
make: *** [install]Error 2
I have follow all the steps and sip seemed to install no problem not sure how to test that, but there were no errors. I am trying to install a program (PySpline) and every time I do it says need to install PyQt first so i apparently haven’t installed it.
Any help is much appreciated.
Thanks
Hi Courtney,
I’m sorry to hear that you’re having so much trouble. What I”m going to say might sound a touch snide, that’s not how it’s meant. Anyhoo …
Take a couple of big, patient breaths. PyQt on Mac OS X is a mess. It has been since Snow Leopard was released, and even though I thought Qt 4.7 fixed most of the major problems, that is not the case. Every day I find bugs, and other issues in my own code and in the code of others. At this time, Qt 4.7 is still in beta on Snow Leopard. I haven’t heard when the final version will be released, but I can only hope it is soon.
For that reason, it is possible (perhaps even probable) that you’re not doing anything wrong. Your problem might just be that, for whatever reason, PyQt is unable to correctly configure and install on your system. If you really need your program to work, I would recommend that you download Virtual Box and install a Linux Virtual machine. For most of the open source/scientific programs I need, this has been much easier than trying to troubleshoot PyQt and the bizarre python distribution included with Mac OS X.
As to your problem, sipconfig.py should be installed when you configure and install sip. After you configure (“python configure.py …”) and compile (“make”), make sure that you run the install command (“sudo make install”). This must be run as the root user (the “sudo” bit), or it will not work correctly. You’ll get an error that says, “Insufficient permissions”, or something like that.
First, I would try and reconfigure/install sip. If that doesn’t solve the problem, I’m not sure what to recommend. The error that you are getting is a linker error (not a compiler error), which means that it can’t find an appropriate library (like sip) to which it can link. Given the frequency that Apple rearranges the internals of their operating system, linker errors crop up with alarming regularity.
One last thought, is there a particular Qt module that fails? I’ve occasionally had this problem when trying to link against Qt Webkit. This article was written prior to the introduction of Safari 5, which may be causing trouble. (I don’t know, I haven’t tried to compile PyQt since writing this article.)
In summary, PyQt on OS X is very hit/miss. If you need it to work reliably, either use Windows or Linux. This is easy to do via Bootcamp, VMware/Parallels or Virtual Box; and is probably your best bet. While things will run slightly slower, it is worth not having to deal with the installation headaches.
To install PyQt on Linux is one simple command:
sudo apt-get install pyqt
Sorry, I couldn’t be of more help.
Cheers,
Rob
@Yarko: Sorry, but I’m not sure what to recommend. You might try deleting the referenced tmp directory, and then removing qmake from your path. (Alternatively, there is an uninstall script for Qt in the /Developer/ directory.) I’d also clean out /opt/, where custom built versions of Qt tend to be installed.
From there, try installing the Qt 4.7 beta version. As I mention in the previous comment, Qt on Mac is a mess. PyQt is even worse. I wish Nokia would hurry up and fix it, and that Apple would take backwards compatibility seriously. (In both cases, I’m not holding my breath.)
The only real recommendation I can make is: if you are trying to set up a production environment, consider using Linux. It’s easier to install/configure, and is far easier to keep current.
As a follow-up to my comments yesterday, I spent a bit of time this morning with the newest version of Qt 4.7 (Beta 2, July 8, 2010). I was able to compile all of the modules (against the most recent snapshots of SIP and PyQt) and to install. Since Beta 1 (the version used in the article), there have been a number of improvements and bugfixes. Buttons no longer stick, and issues with pipes appear to have been repaired. I am, therefore, cautiously optimistic that PyQt might be usable again on Mac OS X.
Edit: Nevermind, I spoke much too soon. After pushing a few more buttons and trying to use my backup program (Time Drive), PyQt still appears to be horribly broken. Backup failed unexpectedly with cryptic errors. Moreover, when compiling LyX-Outline against 4.7, I still still see the bizarre disappearing Window bug. It appears that PyQt/Qt 4.7 are still not ready for primetime on Mac.
First of all, thanks for the nice tutorial!
Compiling and installing sip worked fine, but configuring PyQt did not work, since it did not find the spiconfig module. It turned out that the library path in your article (/Library/Python/2.6/site-packages) is not on the module search path for my Python 2.6.5 installation (the DMG one from python.org).
I had to use the following library path (-d) in the configure command to overcome this: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages
So the configure lines which worked for me:
python2.6 configure.py -d /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages
I had to remove the sip module files form the original library location, then retry compiling both sip and PyQt with the configure line above to get both of them compiled and installed successfully.
I don’t know why the original (shorter) site-packages directory is missing from my default module search path, however. (I did not mix OS X’s own python and the one I installed (2.6.5) for sure.)
Finally, I got the same linker error as Courtney did. I compiled sip-0.10.5 and PyQt 4.7.2 beta 2 on Python 2.6.5. The detailed error message is:
rm -f libpythonplugin.dylib
g++ -headerpad_max_install_names -single_module -dynamiclib -o libpythonplugin.dylib pluginloader.o moc_pluginloader.o -F/Library/Frameworks -L/Library/Frameworks -framework Python -L/tmp/qt-stuff-83153/source/qt-everywhere-opensource-src-4.7.0-beta2/lib -F/tmp/qt-stuff-83153/source/qt-everywhere-opensource-src-4.7.0-beta2/lib -framework QtDesigner -framework QtScript -framework QtXml -framework QtGui -framework QtCore
ld: warning: directory ‘/tmp/qt-stuff-83153/source/qt-everywhere-opensource-src-4.7.0-beta2/lib’ following -L not found
ld: warning: directory ‘/tmp/qt-stuff-83153/source/qt-everywhere-opensource-src-4.7.0-beta2/lib’ following -F not found
ld: warning: in /Library/Frameworks/Python.framework/Python, missing required architecture x86_64 in file
Undefined symbols:
“_Py_Initialize”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyLong_AsVoidPtr”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyErr_Print”, referenced from:
PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o
PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyString_FromString”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyType_IsSubtype”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyModule_GetDict”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyObject_CallObject”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyObject_CallFunctionObjArgs”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyList_Append”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_Py_IsInitialized”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyDict_Next”, referenced from:
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyImport_ImportModule”, referenced from:
PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o
PyCustomWidgets::PyCustomWidgets(QObject*)in pluginloader.o
“_PyObject_GetAttrString”, referenced from:
PyCustomWidgets::getModuleAttr(char const*, char const*)in pluginloader.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
According to what is returned by Python 2.6’s platform.architecture() function my platform is 32 bits, so something is wrong here with the compile target (e.g. the setting the right bit number of the target platform).
Append this to the end of the above error message:
make[1]: *** [libpythonplugin.dylib] Error 1
make: *** [all] Error 2
The post below seems to be related to the linker issue we faced here. Trying this solution, but by setting a 32 bit target architecture:
Got it compiled, finally.
Software versions:
– Python 2.6.5, DMG image downloaded from python.org
– Qt 4.7.0 beta 2, binary installer downloaded from Nokia
– sip 4.10.5
– PyQt Mac GPL 4.7.4
Configuration options used:
NOTE: The options are DIFFERENT for sip and PyQt!
sip:
python2.6 configure.py -d /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages –arch=i386
PyQt:
python2.6 configure.py -d /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages –use-arch=i386
I haven’t tried, but if you need to compile on a 64 bit platform, then you should replace i386 with x86_64, possibly. (Let me know if that worked for you, thanks.)
I can confirm that the x86_64 option works. I was able to compile and install the latest version of PyQt without errors, or linker troubles. I was also able to do so with the system version of Python. I know that there was some strangeness regarding whether Apple chooses to enable the 64 bit kernel, or not.
(I called a friend who might be described as a Mac Guru.)
Based on your type of machine, you may need to modify the compiler flag (–use-arch). Unfortunately, I do not have access to other types of machines to test different options.
Thanks, Viktor, for supplying these instructions.
I had to start from scratch. I reinstalled Mac OS-X and installed everything again. This time the -d parameter was not needed to configure sip and PyQt correctly. The –arch and –use-arch parameters were still required, however.
Software versions for later reference:
Python:
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
XCode: 3.2.3 with SDK 4.0.2
sip 4.10.5
Qt 4.7.0 rc1
PyQt 4.7.4
Hi Viktor and all,
Could you please tell me which package you downloaded from Qt? Was it the SDK (995MB) or binaries (202MB)? I want to install as x86_64 but can’t seem to find out which package is x86_64 (both, neither…not sure)
Thanks,
Matt
Hi all,
I found this site because I am having the same trouble that Courtney and Viktor describe. I wanted to install eric and so PyQt and sip are necessary dependencies. The instructions above helped a lot, however, so far they did not work for me. I used the following versions of the components:
Python 2.6.5 (installed using the Enthought package EPD-6.2.2 32-BIT MACOSX10.5+)
Qt
sip-4.12
PyQt4.8.1
Qt 4.7.0
After having failed several times trying to install the components in various orders and versions, I followed Rob’s instructions above. To be sure, I used the i386 flag for the configuration of both sip and PyQt. Still, I had the same error message that was described by Courtney and Viktor.
Then I tried providing the arguments that Viktor posted, however, using the appropriate paths on my system, i.e., I used
sip:
python configure.py -d /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/ –arch=i386
PyQt:
python configure.py -d /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/ –use-arch=i386
Only partial success. I got rid of the error messages, but for some reason, I still get an error message when I try to install eric, saying that PyQt is not installed:
Checking dependencies
Python Version: 2.6.5
Sorry, please install PyQt4.
Error: dlopen(/Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/PyQt4/QtCore.so, 2): Symbol not found: _sipQtConnect
Referenced from: /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/PyQt4/QtCore.so
Expected in: flat namespace
in /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/PyQt4/QtCore.so
So far this has been the most helpful resource I could find. Thank you very much for sharing. But are there any updates on the issue that you are aware of? Any light at the end of the tunnel that future versions will resolve these hassles (I spend 2 nights already trying to install already)?
Thanks,
Martin
Just wanted to say thanks for this clear tutorial. The whole process looked quite daunting until I came across your instructions – the whole thing went off without a hitch (I did guess that I could just replace 2.6 with 2.7 in the configure path – I was right!).
Hi,
For some reasons, I tried with the arch flags, and that did not work for me, which by the way, I had to modify, because they were not accepted by my system. I still got the same errors as Viktor Ferenczi in his first post above.
I am using the Enthought Pyhton Distribution (EPD64),
I got it to work by 1) removing all 32-bit EPD and 2) booting Mac OS X 10.6.6 in 64-bit mode (see below).
That worked fine.
Best,
Olivier.
To boot in 64-bit kernel by default:
To select the 64-bit kernel for the current startup disk, use the following command in Terminal:
sudo systemsetup -setkernelbootarchitecture x86_64
Then reboot..
You have first to make sure your system can be switch to 64-bit mode, read the links to the apple site above.
Greetings everyone and thanks in advanced
Well I am working in a project that uses PyQt (64-bit) and requires python 2.6.6, the problem is that Python 2.6.6 dmg available here:, is 32-bit (I need the stock version because there is a problem with mac ports and the process module), so I built a 64-bit version of python 2.6.6. My current problem is that python can not find pyqt, Is there a way to bind PyQt and the built python , maybe with configure.py and some parameters?
Hi! I’m attempting to install PyQt on a newly purchased iMac (3.06 GHz Intel Core i3, running OS 10.6.7) I hit one bug in the process though which I should point out…
When attempting to do the configure.py step for PyQt4.7.3, I got the error displayed in this question:
The fix is contained in this answer:
Basically the process proceeded until it invoked SIP and I got the following error:
Generating the C++ source for the QtCore module…
sip: Usage: sip [-h] [-V] [-a file] [-b file] [-c dir] [-d file] [-e] [-g] [-I dir] [-j #] [-k] [-m file] [-o] [-p module] [-r] [-s suffix] [-t tag] [-w] [-x feature] [-z file] [file]
Error: Unable to create the C++ code.
Turns out that you CANNOT have any spaces in the file name or path to the folder which you are doing this process! Not even in any of the enclosing folders; so a full path such as:
~/Desktop/PyQt files/PyQt-mac-gpl-4.8.4
will fail, but changing the middle folder to:
~/Desktop/PyQt_files/PyQt-mac-gpl-4.8.4
will make it work!
Just a note, if you have the error that says:
Traceback (most recent call last):
File “configure.py”, line 37, in
import sipconfig
ImportError: No module named sipconfig
Then what I did to get it to build was take the sipconfig.py and .pyc file and paste them in the dir where my PyQt4 files are then run the script. That’s when it worked for me.
Hi,
To install SIP and PyQt on MacOSX you do not need to pass the -d argument for the configure, as this article does. You just download and untar the two folders, go into each and run 1) python configure.py 2) make 3) sudo make install, both times making sure you run from the two folders.
Care to comment? | http://blog.oak-tree.us/index.php/2010/05/27/pyqt-snow-leopard | CC-MAIN-2017-30 | refinedweb | 2,996 | 59.19 |
In my first post on Command Links I talked about the challenge of developing for something when you have no documentation. In this second post I will discuss how we can use Command Links from managed code – specifically Windows Forms using C#.
I take NO credit for the code snippets. They were expertly crafted by my
Quick Recap
We know that Command Links are no more than Win32 button. We send messages to the button to make it look like a Command Link and to set the note text etc.
- New button style (BS_COMMANDLINK)
- New button messages (BCM_SETNOTE, BCM_GETNOTE)
- Shield (BCM_SETSHIELD)
Windows Forms has a Button control – and the Windows Forms Button Control is underneath the covers a Win32 Button. Looking promising.
It should therefore be possible to get a Windows Forms Button to display as a Command Link with a few messages.
The Solution
We need to create a new button control (hmmmm…. lets call it CommandLink) which derives from a standard Button:
public class CommandLink : System.Windows.Forms.Button
{
}
In the constructor we need to force the control to use the System style and avoid owner draw:
this.FlatStyle = FlatStyle.System;
Next need to attach the style to set of parameters that Windows Forms sends though to Win32:
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style |= BS_COMMANDLINK;
return (cp);
}
}
To set the control’s note text, send it the BCM_SETNOTE window message
void SetNote(string NoteText)
{
SendMessage(new HandleRef(this, this.Handle), BCM_SETNOTE,
IntPtr.Zero, NoteText);
}
To set the control’s shield icon, send it the BCM_SETSHIELD window message
void SetShieldIcon(bool Show)
{
SendMessage(new HandleRef(this, this.Handle),
BCM_SETSHIELD, IntPtr.Zero, new IntPtr (Show ? 1 : 0));
}
And you are pretty much done (Ok – there is a lot more to do around making it into a reusable control – but its now a shiny Command Link).
You will need to use interop services to make the above work. Minimally:
using System.Runtime.InteropServices;
const int BS_COMMANDLINK = 0x0000000E;
const uint BCM_SETNOTE = 0x00001609;
const uint BCM_SETSHIELD = 0x0000160C;
// Override used to send the BCM_SETNOTE/BCM_SETSHIELD message
[DllImport(“user32.dll”, CharSet = CharSet.Unicode)]
static extern IntPtr SendMessage(HandleRef hWnd, UInt32 Msg,IntPtr wParam, string lParam);
A big thanks Catherine.
PingBack from | https://blogs.msdn.microsoft.com/ericnel/2006/06/07/using-windows-vista-command-links-in-managed-code/ | CC-MAIN-2016-44 | refinedweb | 371 | 64.1 |
Linear regression is a method we can use to understand the relationship between one or more predictor variables and a response variable.
This tutorial explains how to perform linear regression in Python.
Example: Linear Regression in Python
Suppose we want to know if the number of hours spent studying and the number of prep exams taken affects the score that a student receives on a certain exam.
To explore this relationship, we can perform the following steps in Python to conduct a multiple linear regression.
Step 1: Enter the data.
First, we’ll create a pandas DataFrame to hold our dataset:
import pandas as pd #create data df = pd.DataFrame({'hours': [1, 2, 2, 4, 2, 1, 5, 4, 2, 4, 4, 3, 6, 5, 3, 4, 6, 2, 1, 2], 'exams': [1, 3, 3, 5, 2, 2, 1, 1, 0, 3, 4, 3, 2, 4, 4, 4, 5, 1, 0, 1], 'score': [76, 78, 85, 88, 72, 69, 94, 94, 88, 92, 90, 75, 96, 90, 82, 85, 99, 83, 62, 76]}) #view data df hours 13 5 4 90 14 3 4 82 15 4 4 85 16 6 5 99 17 2 1 83 18 1 0 62 19 2 1 76
Step 2: Perform linear regression.
Next, we’ll use the OLS() function from the statsmodels library to perform ordinary least squares regression, using “hours” and “exams” as the predictor variables and “score” as the response variable:
import statsmodels.api as sm #define response variable y = df['score'] #define predictor variables x = df[['hours', 'exams']] #add constant to predictor variables x = sm.add_constant(x) #fit linear regression model model = sm.OLS(y, x).fit() #view model summary print(model.summary()) OLS Regression Results ============================================================================== Dep. Variable: score R-squared: 0.734 Model: OLS Adj. R-squared: 0.703 Method: Least Squares F-statistic: 23.46 Date: Fri, 24 Jul 2020 Prob (F-statistic): 1.29e-05 Time: 13:20:31 Log-Likelihood: -60.354 No. Observations: 20 AIC: 126.7 Df Residuals: 17 BIC: 129.7 Df Model: 2 Covariance Type: nonrobust ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ const 67.6735 2.816 24.033 0.000 61.733 73.614 hours 5.5557 0.899 6.179 0.000 3.659 7.453 exams -0.6017 0.914 -0.658 0.519 -2.531 1.327 ============================================================================== Omnibus: 0.341 Durbin-Watson: 1.506 Prob(Omnibus): 0.843 Jarque-Bera (JB): 0.196 Skew: -0.216 Prob(JB): 0.907 Kurtosis: 2.782 Cond. No. 10.8 ==============================================================================
Step 3: Interpret the results.
Here is how to interpret the most relevant numbers in the output:
R-squared: 0.734. This is known as the coefficient of determination. It is the proportion of the variance in the response variable that can be explained by the predictor variables. In this example, 73.4% of the variation in the exam scores can be explained by the number of hours studied and the number of prep exams taken.
F-statistic: 23.46. This is the overall F-statistic for the regression model.
Prob (F-statistic): 1.29e-05. This is the p-value associated with the overall F-statistic. It tells us whether or not the regression model as a whole is statistically significant. In other words, it tells us if the two predictor variables combined have a statistically significant association with the response variable. In this case the p-value is less than 0.05, which indicates that the predictor variables “hours studied” and “prep exams taken” combined have a statistically significant association with exam score.
coef: The coefficients for each predictor variable tell us the average expected change in the response variable, assuming the other predictor.
P>|t|. The individual p-values tell us whether or not each predictor variable is statistically significant. We can see that “hours” is statistically significant (p = 0.00) while “exams” (p = 0.52) is not statistically significant at α = 0.05. Since “exams” is not statistically significant, we may end up deciding to remove it from the model.:
Keep in mind that because prep exams taken was not statistically significant (p = 0.52), we may decide to remove it because it doesn’t add any improvement to the overall model. In this case, we could perform simple linear regression using only hours studied as the predictor variable.
Step 4: Check model assumptions.
Once you perform linear regression, there are several assumptions you may want to check to ensure that the results of the regression model are reliable. These assumptions include:
Assumption #1: There exists a linear relationship between the predictor variables and the response variable.
- Check this assumption by generating a residual plot that displays the fitted values against the residual values for a regression model.
Assumption #2: Independence of residuals.
- Check this assumption by performing a Durbin-Watson Test.
Assumption #3: Homoscedasticity of residuals.
- Check this assumption by performing a Breusch-Pagan Test.
Assumption #4: Normality of residuals.
- Check this assumption visually using a Q-Q plot.
- Check this assumption with formal tests like a Jarque-Bera Test or an Anderson-Darling Test.
Assumption #5: Verify that multicollinearity doesn’t exist among predictor variables.
If these assumptions are met, you can be confident that the results of your multiple linear regression model are reliable.
You can find the complete Python code used in this tutorial here. | https://www.statology.org/linear-regression-python/ | CC-MAIN-2022-21 | refinedweb | 897 | 58.99 |
Halloween is one of my favorite holidays here in the US, and so much so that I spent a few years of my life thinking up and building smart Halloween props and animatronics for the haunted attraction industry. I won’t go too deep into the details of the business, but a few friends and myself founded a company a few years back with the “help” of some investors. It was my first tech startup, and like many tech companies, we had the hardware and software to revolutionize a decades stagnant industry that quite honestly did not want to change. To make a long story short, none of the original founders are part of that business anymore, with myself backing out in late 2015.
One of my duties in the company was to brainstorm and prototype new and innovative props that utilized modern technology, while remaining easy enough to use for the aging haunted house owners to be able to program. Often this was accomplished by making props that just worked once powered up, other times this involved utilizing our custom Raspberry Pi based animatronic / whole scene controller unit on the finished prop. However, during the prototyping phase, I would always develop the project using a bare Raspberry Pi or Arduino, and I loved this part about the business the most. The thrill of coming up with a concept, and then building and presenting a working prototype during our weekly all-hands meeting was exhilarating. This is why I love creating Halloween projects every year here at Element14. It gives me the perfect excuse to build some of those concepts that I never got around to prototyping when I was co-owner of the company.
One of those product ideas that I never got around to building was a smart-mirror that was fully functional while hiding a mind and body jarring jump scare that would be triggered when someone stopped in front of the mirror for more than a few seconds. So when I was asked to come up with a second Halloween project this year, I instantly thought of the smart-mirror. What I did not anticipate was the level of frustration and failure I would experience while building it. Don’t worry though, in the end, I managed to work up something that works 90% of how I wanted it to, and I am going to continue refining this project over the next couple of months, but for now, the smart mirror does work, it just lacks many of the features I wanted it to have. Before we get into the build, I would like to take a moment to talk about what failures I encountered during this project in hopes that a reader may be able to help with the javascript programming when I reboot this project in a month or two.
Experiencing Failure
As I said in the paragraph above, this project was one of the most frustrating, and stress inducing projects I have ever encountered. My issues began when building the wood frame that would house the mirror in its final form, but I am not here to rant about that, because I simply got a measurement wrong at some point in my CAD design. This was easily solved, and I only lost an hour or three rebuilding it. The real frustration kicked in shortly after deciding to use the MagicMirror2 software to power the magic mirror portion of the project.
MagicMirror2 is an amazing smart-mirror package if you are just wanting to build a feature-rich, highly functional smart-mirror. I really like this software, and it appears to be regularly updated, and has a very active community behind it. I can not recommend it enough if you are building a normal smart-mirror. The deficiencies begin to show themselves when one wants to detour from the traditional functionality that most smart-mirror builders desire. To be short, attempting to play a full-screen video, display a full-screen .GIF, or simply display a static .jpg in full screen mode on top of the MagicMirror2 display is quite difficult, if not impossible all together.
I spent three 12-16 hour days trying to get a video via OMX Player, HTML5, and various other raspberry-pi based video players to work when a GPIO Pin is pulled high by a PIR sensor. After I realized I was just not skilled enough in JavaScript programming to do this on my own, I asked a friend who is a great programmer for help, and six hours later we were still stumped. So I reached out via GitHub to one of the MagicMirror2 module developers, and he attempt to help me figure it out for several hours as well. In the end, the general consensus was that at the moment, without some extensive JavaScript coding, and a deep understanding of how MagicMirror2 and Node.JS work, that it was not possible in time to get this project published on time.
So after missing my deadline, and feeling like a complete failure, I picked myself up, tossed MagicMirror2 and all of my code into the garbage and went searching for a new approach. After a few hours of searching, I happened to come across a repository on GitHub that contained a smart-mirror program that was written in Python. This was the best possible outcome for me after the failure as Python is a language I can easily write, and understand. I really would like to make this work with the MagicMirror2 software as it is much more feature rich, and you can do some really cool stuff with Node.js, so if you would like to help me figure that out, please get in touch! Ok, enough about my failures, let's get into the actual project.
Parts Required
Hardware
Raspberry Pi 3 With NoobsRaspberry Pi 3 With Noobs
PIR SensorPIR Sensor
HT-255D Crimp ToolHT-255D Crimp Tool
Crimp ConnectorsCrimp Connectors
HDMI DisplayHDMI Display
HDMI CableHDMI Cable
3D Printing Files
Software
Setting Up Your Raspberry Pi and Downloading The Code
Before we begin installing the software packages we will need to make our spooky smart-mirror, you will need to install the latest version of Raspbian onto the SD card that will go into your Raspberry Pi. If you are using a fresh, empty SD card, then you can follow the video above to learn how to install the latest version of Raspbian to the SD card. If you already have an SD card with Raspbian installed, we can update and upgrade Raspbian from the command line. To do this remotely from the command line on your computer, connect to your Pi to your network via WiFi or a network cable, and then log in (my preferred method) via a terminal app such as Terminal, Putty, or CMDR and then enter the following commands.
sudo apt-get update
Then select “Yes” if prompted
When the update is finished running, its time to check to see if there is an upgrade available, and install it. To do this, run the following command. This could take a while, so sit back and watch some YouTube videos, or check out my Design Challenge Weekly Updates while you wait.
sudo apt-get upgrade
Then select “Yes” if prompted
Once everything is up to date, shutdown the Pi and connect a HDMI monitor, or the TV you will be using for your mirror. I did my initial development using the official Raspberry Pi 7” Touch Screen. Now restart the Pi, and access it once again from a terminal program on your computer.
Before any of the fun happens, we need to install my fork of the Smart-Mirror software. To do this you will need to use Git. If you do not have Git installed, or you have never used it before, here is a helpful tutorial. The Magic Book-bag portion of the tutorial is not relevant to this project, but it does help you understand how to use Git better.
The Smart Mirror Code
Once Git is installed, and you have your SSH key saved in your Git settings, navigate to the home/pi directory again and run the following commands. This will clone my Smart-Mirror-With-Halloween-Jump-Scare repository to the Raspberry Pi.
cd /home/pi git clone git@github.com:CharlesJGantt/Smart-Mirror-With-Halloween-Jump-Scare.git
Navigate to the folder for the repository
cd Smart-Mirror
Install the Smart-Mirror software’s dependencies (Make sure you have pip () installed before doing this.)
sudo pip install -r requirements.txt sudo apt-get install python-imaging-tk
Select “Yes” if prompted
At the moment, the weather widget is broken due to an API change, but for what we are doing with this project at the moment, that does not matter much. With that said, you should still register a free developers account at darksky.net and enter your API key in the smartmirror.py file as pictured above. To do this, enter the following commands.
sudo nano smartmirror.py
And edit line 23 with your API key. Then exit nano with ctrl+x or cmd+x and press enter to keep the same file name.
Screen Orientation and Cleanup
Before we can test the Smart-Mirror install, we need to take care of some minor, but required task. The first task is to rotate the display by 90 degrees so that our smart mirror can hang in portrait orientation. To do this, enter the following commands, and edit the config file.
sudo nano /boot/config.txt
Arrow down to the bottom of the file, and add the following line of code. Then save the file by pressing ctrl+x or cmd+x and press enter to keep the same file name. If your screen's rotation is 180 degrees off after this rotation, change the number to 3 instead of 2.
lcd_rotate=2
Now we need to hide the taskbar, and the only way to do this from the command line is to edit another config file. Enter the following command to edit the necessary file.
sudo nano /home/pi/.config/lxpanel/LXDE-pi/panels/panel
In the “Global” section at the top of the file, you need to modify the following parameters:
autohide=0 heightwhenhidden=2
Replace that line with the following line
autohide=1 heightwhenhidden=0
With those small task taken care of you can now test the Smart-Mirror install by running the following command. Note that you will have to run this from the terminal app on the Pi itself for it to work properly. This is because TKinter will only open if ran natively. There are ways to run this command remotely, but I have found them to be buggy.
sudo python smartmirror.py
An error may pop up about the weather module, but ignore it, and the screen should turn black with white clock and news text appearing on the screen.
The Jump Scare Code
Ok, now that we have the Smart-Mirror running, it's time to connect the PIR sensor to the Raspberry Pi’s GPIO header. Follow the diagram below paying close attention to the Power and GND wires.
- PIR Sensor VCC Pin to RPi 5V
- PIR Sensor Data Pin to RPi GPIO5
- PIR Sensor GND Pin to RPi GND
Now let's take a look at the jumpscare.py file that is inside of the Smart-Mirror directory. You might be wondering why I did not just include this code in the smartmirror.py code, and my reason is just because I expect that file to be updated soon by its creator to fix the weather API, and I also like the idea of being able to turn off the jump scare feature by killing the jumpscare process.
Open the jumpscare.py file in Nano.
sudo nano jumpscare.py
Starting at the top of the file we import the following libraries:
import RPi.GPIO as GPIO import time import os import sys from subprocess import Popen
Next we have to set which GPIO numbering schema we will be using. I always use the BCM schema. There are two different numbering schemes for the GPIO pins on the Pi. The Broadcom chip-specific pin numbers (BCM) and P1 physical pin numbers (BOARD.
Here’s a reference showing all the pins on the P1 header, along with their special functions and both BCM and BOARD numbers:
GPIO.setmode(GPIO.BCM)
Now we need to setup the GPIO and tell the Pi which pins are what. In the first line we are telling the Pi to set GPIO pin 5 as an input, and to attach a pulldown resistor to it. The second line sets up GPIO pin 26 as an output. I left this in the code so that you could connect an LED to pin 26 to use for troubleshooting motion triggers.
GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(26, GPIO.OUT)
Before we get into the loop, we need to declare a variable called "motionDetected". We can use this variable to count motion triggers in our loop. We also need to tell the Pi where the video we want to play is located. Since you cloned this repository from my Github, the zombie.mp4 file will be in the Smart-Mirror directory.
motionDetected = 0 movie1 = ("/home/pi/python_programs/zombie.mp4")
I’m going to break the loop down line by line to better help you understand what's going on. In the line below we are defining our loop and stating that while True do this.
while True:
Here we are telling the Pi to watch the state of GPIO 5
input_state = GPIO.input(5)
In the next block of code we are telling the Pi that if the input state of GPIO equals True (high) then print “Motion Detected” in the terminal, increment the motionDetected variable by one, and then wait for 0.2-seconds before moving on to the next line of code.
if input_state == True: print('Motion Detected') motionDetected += 1 time.sleep(0.2)
Finally, we finish things up with another if statement that says if motionDetected equals 1 then set GPIO pin 26 HIGH, then make sure no instance of OMXplayer is running, then open a video player with the video that was defined earlier in the code. Next we tell the code to wait for 60 seconds before continuing with the loop, resetting the motionDetected variable to 0, and set GPIO pin 26 low to turn off the debugging LED. Note that you can delay or speed up how frequent the jump scare triggers by adjusting the time.sleep(60) setting.
if motionDetected == 1: GPIO.output(26, GPIO.HIGH) os.system('killall omxplayer.bin') omxc = Popen(['omxplayer', '-b', '-o', 'local', movie1]) player = True time.sleep(60) motionDetected = 0 GPIO.output(26, GPIO.LOW)
The full code is listed below.
# This Code Triggers a video to play on # the raspberry pi when motion is detected # via a PIR sensor on BCM pin 5. # Written By # Charles Gantt 2017 # # & # import RPi.GPIO as GPIO import time import os import sys from subprocess import Popen GPIO.setmode(GPIO.BCM) movie1 = ("/home/pi/Smart-Mirror-With-Halloween-Jump-Scare/zombie.mp4") GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(26, GPIO.OUT) motionDetected = 0 while True: input_state = GPIO.input(5) if input_state == True: print('Motion Detected') motionDetected += 1 time.sleep(0.2) if motionDetected == 1: GPIO.output(26, GPIO.HIGH) os.system('killall omxplayer.bin') omxc = Popen(['omxplayer', '-b', '-o', 'local', movie1]) player = True time.sleep(5) motionDetected = 0 GPIO.output(26, GPIO.LOW)
With all of the code finished up, let's set both python programs to run on boot. To do this we are going to write a simple bash script that tells the Pi to run both of the python files in the background.
cd /home/pi/Smart-Mirror-With-Halloween-Jump-Scare nano launcher.sh
Now type in this script
#!/bin/sh # launcher.sh # navigate to home directory, then to this directory, then execute python scripts, then back home cd / cd /home/pi/Smart-Mirror-With-Halloween-Jump-Scare sudo python smartmirror.py & sleep 10 sudo python jumpscare.py & cd /
We need to make the launcher script an executable file. To do this, enter the following command.
chmod 755 launcher.sh
Since we will be using crontab to trigger this script. We need to make a directory to log any errors that may occur. This will help with troubleshooting. Enter the following commands:
cd mkdir logs
Now lets add the script to the crontab. Add the following line to the very bottom of the crontab file.
@reboot sh /home/pi/bbt/launcher.sh >/home/pi/logs/cronlog 2>&1
Now you can reboot the Pi to see if it worked. Enter the following command to reboot the Pi.
sudo reboot
When the Pi finishes booting, you should see the GUI load, then the smart mirror window open. If you wave your hand in front of the PIR sensor, the jumpscare.py script should trigger the zombie.mp4 video, and once finished, the smart mirror screen should reappear.
The Smart Mirror
With our code finished, it’s time to make our smart mirror. This is the part of the project where my end result may differ from yours. I chose to order a new 32” LED TV from Amazon, and try my hand at creating the two way mirror from window tint film and standard plate glass. I also wanted to create a wooden frame to house the TV inside so that it had the appearance of a hand-crafted mirror. Fortunately, I have a complete, fully stocked woodworking shop here at home, and whipping up a frame was a few hour process. As I mentioned at the beginning of this project, I did get my math wrong and made the first version of the frame incorrectly, and the TV screen did not fit. I was able to correct this, but if you do not have an abundance of time-saving tools, and extra wood to work with, take time, and measure your screen’s dimensions carefully. The only advice I can really offer is to leave about 1/16” clearance around the edge of the screen to account for expansion as the steel frame of the TV as it warms up.
I am not going very in depth here about the process I used to build the frame because how you frame the mirror is arbitrary and not very relevant to getting the mirror to work. You could even just tape a 2-way mirror to the front of the TV and the effect would be the same. Some people even create these little mirrors from 15” laptop screens, or HDMI monitors. You do not have to use an actual TV. I simply used a brand new 32” TV because I will be rebuilding this mirror, with a much more refined frame that will be built from exotic hardwood. I do however plan on making a video on that build with a complete step by step guide for my YouTube channel. So if you would like to check that out, it should be out sometime towards the end of the year.
I didn’t get many photos of the glass cutting or tinting process as that was another major issue I ran into during this project. Initially I decided that I would cut my own glass, as it is something I have done in the past, and it saves a good bit of money. My mistake was thinking that the glass I bought from a big box home repair store would be of a high enough quality to actually be easy to cut with the standard score and snap method. I broke $38 worth of glass before I gave up defeated, and called a local glass shop that explained to me that the glass quality that big box home improvement stores sell is just too low quality, and it's not annealed very well giving it a harder surface that is prone to flaking in the scoring process. The higher quality glass that glass shops stock is designed to be cut with laser sharp accuracy, and to minimize errant cracks in the cutting process. They showed me how quick and easy a good, high-quality piece of glass is to cut, and $17.38 later I was on my way home with the glass.
That afternoon, I attempted to tint the glass by myself and while I came very close to succeeding, I botched the tinting process twice. This was 100% my fault, and instead of following the poorly written directions that came with the mirror tint window film, I watched a few window tinting tutorials on YouTube, and realized that by adding a little dish soap to the water I was spraying the glass and film with, the process was much easier, and provided a better result. Living in a home with four dogs, and a couple of cats as well as an attached woodworking shop did end up haunting me a bit during the tinting process though. I spent a lot of time picking specks of dust and animal hair out of the wet tint, and still managed to trap a few dust particles and hair under the tint. Since this is a Halloween prop, I am not to bothered by that. When I rebuild this into a proper smart mirror, I will order a piece of chemically tinted 2-way mirror glass to avoid these issues all together. Another advantage to chemically treated glass is that your mirror can be made from tempered safety glass which means there is a much less chance of injury if it does shatter or fall off the wall and break.
The one thing that I made that may help you along with your build is the corner brackets I designed and 3D Printed that hold the mirror and TV firmly to the frame’s bezel. These brackets take about 20-minutes to print each on a Prusa i3 MK2s at a 0.2mm resolution. If you would like to use these brackets in your project, you can download them from my Thingiverse by clicking here.
So without going into too much detail, here are some photos of the frame build.
Now that we have the frame built and it’s hanging cable attached, it's time to attach the Raspberry Pi to the back of the TV. If you have room, and a 3D Printer, you can print this handy dandy VESA mount Rasberry Pi case bottom that I found on Thingiverse. If you want to print the top piece as well, that is just fine. I only printed the bottom as I wanted my Pi to have good airflow. Unfortunately on the TV I am using, the VESA mount was only part of the rear plastic, so I ended up attaching the Pi to a single screw hole. When I rebuild the mirror, I will print a custom case with mounting points that fit the screw locations on the grey steel backing plate.
As you can see, it mounts to the tv with standard M4 machine screws. Then the Pi attaches to it with small 3mm screws. Then all that is required is to attach a USB cable from the Raspberry Pi 3, and the TV’s USB port.
Finally, we need to attach the PIR Sensor to the top of the frame. To do this, I found a nice and compact PIR sensor case on Thingiverse, which I remixed, and designed a small extension arm for. Download it here. This is held together with M3 machine screws and nuts. To mount it to the top of the frame, I just used more small screws like I used on the corner brackets.
To finish up the PIR sensor mounting I needed to make up a cable that would connect it to the Raspberry Pi. Using a pin and crimp kit, I made the cable about three inches longer than it needed to be to add some strain-relief and prevent the cable from putting too much tension on the pins of the Pi.
Now all that is left is to test the smart mirror and jump scare out, and to do this, I simply stood it up on my workbench. Check out the demo video above, and I hope it shows off the jump scare well enough. This was the final point of frustration for me during this project. I shot a nice video with my DSLR, and lavaliere microphone, but it appears that something is broken in my brand new camera as it will not record audio from its microphone jack. Thankfully, Canon has a spectacular warranty department, and it will be fixed in a couple of weeks. I plan on taking the smart mirror to a friend's Halloween party, and will update this post with a video of some people getting scared if that happens.
So, what are my final thoughts on this project? Well I can honestly say that even after all of the frustration, stress, and unfortunate events, that I am, for the most part, proud of how it turned out. There are things I wish I would have done a different way, and some features that I left off simply because of time constraints. As I mentioned earlier, I am going to continue developing this project over the coming months, and hope a few people will join me in that journey, but for now, I have a working smart mirror that also features a cool jump scare, so I will call this one a win. Albeit, a small win, but a win nonetheless. I guess that the take away from my experience on this project would be that perseverance always pays off, and as long as you refuse to give up, anything is possible. Thanks for taking the time out of your day to read this tutorial. If you would like to see me create more cool stuff like this, please leave a comment below, and hopefully I will get assigned more projects like this! I will see you on the next one, and until then, remember to Hack The World and Make Awesome! | https://www.element14.com/community/community/raspberry-pi/raspberrypi_projects/blog/2017/10/17/halloween-project-everyday-average-smart-mirror-with-a-spooky-surprise | CC-MAIN-2018-26 | refinedweb | 4,406 | 68.3 |
Those who are currently building ASP.NET MVC web applications are very well aware of the Routing concept. URL routing enables the developer to make URLs flexible, dynamic and readable.
URL Routing was originally devised for ASP.NET MVC and has been implemented as a core feature. A route is a URL pattern which has a mapping with a handler, that can be physical file like the ASP.NET Web form .aspx.
URL routing in ASP.NET MVC and ASP.NET Web Forms differs on how you declare the final destination of the request. In ASP.NET MVC, you use a controller-action pair whereas in ASP.NET Web Forms, you use an ASPX path. In ASP.NET 4.0, URL pattern can be defined by defining its mapping with the physical .aspx file. In this pattern, a placeholder can also be defined so that variable data or parameter can be passed to the request handler without using a query string.
For defining routes in ASP.NET you need to use the following:
- Route class: It provides properties and methods for the definition of route as well as for accessing the information of routes. This class defines the specification for the routing process in ASP.NET. Route object needs to be created to define mapping for every URL pattern that needs to map with the physical file or a class handle used to handle the request.
- Routes: This is the property of the Route class. This represent the URL pattern which is used for processing incoming requests.
- RouteTable: This class is used to store the URL routes defined for the application.
Let’s see a simple example of implementing Routing in ASP.NET
Step 1: Create an ASP.NET 4.0 Web Site (or Web Application), name it as ‘ASPNET_Routing’. In the Global.asax import the ‘System.Web.Routing’ namespace as below:
Step 2: In the Application_Start write the following code:
The above code defines the routing table where the “DepartmentwiseEmployees.aspx” physical file is mapped to the URL route pattern ‘Department{DeptName}’. Here {DeptName} is the variable passed while making the request.
Step 3: In the project add a WebForm with name ‘DepartmentwiseEmployee.aspx’. Design it as below:
Step 4: Write the following code in the Loaded event of the WebForm.
The first line in the Loaded event is as below:
string deptName = (string)Page.RouteData.Values["DeptName"];
The ‘RouteData’ property of the Page class gets the route data value (in this case DeptName) of the current request context. Here this value is always a string based upon which the filtering takes place and the result will be displayed.
Step 5: Run the website and the default page will be displayed. In the address bar type the following URL:
The result will be as shown below:
Download the source code
Tweet
4 comments:
Nice article, easy to understand.
@Fabian Fernandez /signed
Thanks.
very nice article
Really helpful, but can we use regular expression in the example above as we use with URL Intelligencia.
Thanks | https://www.devcurry.com/2011/11/aspnet-4-url-routing-quick-overview.html | CC-MAIN-2020-45 | refinedweb | 505 | 67.15 |
Kubernetes supports OpenAPI
Editor’s note: this post is part of a series of in-depth articles on what's new in Kubernetes 1.5
OpenAPI allows API providers to define their operations and models, and enables developers to automate their tools and generate their favorite language’s client to talk to that API server. Kubernetes has supported swagger 1.2 (older version of OpenAPI spec) for a while, but the spec was incomplete and invalid, making it hard to generate tools/clients based on it.
In Kubernetes 1.4, we introduced alpha support for the OpenAPI spec (formerly known as swagger 2.0 before it was donated to the Open API Initiative) by upgrading the current models and operations. Beginning in Kubernetes 1.5, the support for the OpenAPI spec has been completed by auto-generating the spec directly from Kubernetes source, which will keep the spec--and documentation--completely in sync with future changes in operations/models.
The new spec enables us to have better API documentation and we have even introduced a supported python client.
The spec is modular, divided by GroupVersion: this is future-proof, since we intend to allow separate GroupVersions to be served out of separate API servers.
The structure of spec is explained in detail in OpenAPI spec definition. We used operation’s tags to separate each GroupVersion and filled as much information as we can about paths/operations and models. For a specific operation, all parameters, method of call, and responses are documented.
For example, OpenAPI spec for reading a pod information is:
{ ... " } } }, … } …
Using this information and the URL of
kube-apiserver, one should be able to make the call to the given url (/api/v1/namespaces/{namespace}/pods/{name}) with parameters such as
name,
exact,
export, etc. to get pod’s information. Client libraries generators would also use this information to create an API function call for reading pod’s information. For example, python client makes it easy to call this operation like this:
There are two ways to access OpenAPI spec:
- From
kuber-apiserver/swagger.json. This file will have all enabled GroupVersions routes and models and would be most up-to-date file with an specific
kube-apiserver.
- From Kubernetes GitHub repository with all core GroupVersions enabled. You can access it on master or an specific release (for example 1.5 release).
There are numerous tools that works with this spec. For example, you can use the swagger editor to open the spec file and render documentation, as well as generate clients; or you can directly use swagger codegen to generate documentation and clients. The clients this generates will mostly work out of the box--but you will need some support for authorization and some Kubernetes specific utilities. Use python client as a template to create your own client.
If you want to get involved in development of OpenAPI support, client libraries, or report a bug, you can get in touch with developers at SIG-API-Machinery.
--Mehdy Bohlool, Software Engineer, Google
- Download Kubernetes
- Get involved with the Kubernetes project on GitHub
- Post questions (or answer questions) on Stack Overflow
- Connect with the community on Slack | https://kubernetes.io/blog/2016/12/kubernetes-supports-openapi/ | CC-MAIN-2021-25 | refinedweb | 527 | 53.61 |
Ajax, an acronym for Asynchronous JavaScript and XML is a combination of different technologies, used for building rich and responsive user interfaces. According to Enrich Peterson, "AJAX-enabled pages provide a slick, responsive user experience, making web-based applications function more like desktop-based ones". Ajax has quickly become the technology of choice for building lightning fast and responsive user interfaces. The ASP.NET Ajax Server Framework is composed of a collection of server controls and services that extend the functionality of the ASP.NET core. These commonly are known as ASP.NET Ajax Server Extensions. This article looks at the ASP.NET Ajax Server Extensions Framework and how you can work with it.
What are ASP.NET Ajax Server Extensions?
David Barkol, one of the authors of the famous book ASP.NET Ajax in Action states in his blog: ."
The following are the namespaces included as part of the ASP.NET Ajax Server Extensions Framework:
- System.Web.UI Â this namespace includes classes that provide support for implementing rich user interfaces
- System.Web.UI.Design  this is comprised of classes that you can extend to attach functionality to the existing classes to implement rich and intuitive user interfaces
- System.Web.Configuration  this includes classes that can be used to work with configuration data using ASP.NET Ajax
- System.Web.Handlers - this namespace is comprised of a collection of Http Handlers used to process the HTTP requests sent to the web server
- System.Web.Script.Serialization - this namespace includes a collection of classes for providing support for object serialization and de-serialization in your application
- System.Web.Script.Services  this namespace is comprised of a collection of classes that can be used to customize the behavior of web services that you would like to invoke from client side scripts
Services Provided By the ASP.NET Ajax Server Extensions Framework
- Localization and Globalization
- Authentication
- Debugging
- Tracing
- Web services
- Application services
We will now take a look at what each of these services are and how they can be used. Globalization and Localization are two important concepts. While the former relates to identifying the specific portion of the application's code to be localized, the latter is used to change a portion or portions of your application's core to make it adaptable for a specific locale.
Authentication and Authorization are two important concepts in ASP.NET Security. You can validate a user by authentication. Note that you can authorize an authenticated user only. So, authorization works only after the user has been authenticated.
Debugging and tracing are two important concepts used for identifying the problems in your application's code. The MSDN site states, "AJAX-enabled ASP.NET applications contain a mix of server code and client code. The browser can also request additional data asynchronously. This can make debugging AJAX-enabled Web applications challenging." The Sys.Debug class provides support for debugging and tracing functionality of your client side scripts in ASP.NET Ajax. Here is how you can turn debugging on for your application in the application's web.config file:
Note that tracing can be enabled both at the page and at the application levels. Here's how you can enable tracing at the page level:
To enable tracing support at the application level, you can use the following code in your application's web.config file:
Web Services are Open Standard Enterprise Web Applications that are based on the SOAP protocol and are used for the efficient exchange of data on the same or disparate systems irrespective of the architecture. According to MSDN, ." You can use Ajax to invoke Web Services from client side scripts seamlessly.
Components of the ASP.NET Ajax Server Extensions Framework
The ASP.NET Ajax server extensions framework comprises of the following components:
- The Application services bridge - this is used to provide access to the application services that are available as part of the ASP.NET framework
- The Web services bridge - this is used to consume external web services from the client side scripts
- The ASP.NET Ajax Server Controls - these are server controls provided as part of the ASP.NET Ajax server extensions framework for Ajax support in ASP.NET
The major ASP.NET Ajax Server Controls include the following:
- Timer  This control is used to refresh content of a web page at pre-defined intervals of time.
- ScriptManager  This is the brain of an Ajax enabled web page. Note that in order to implement partial page rendering, you should set the EnablePartialRendering property of the ScriptManager control to true.
- ScriptManagerProxy - A ScriptManagerProxy control is used in a content page to pass references to a ScriptManager control placed in a master page to define Ajax behavior. Note that you can have only one ScriptManagerProxy control in your web page.
- UpdateProgress  This control is typically used to show the progress while an update operation in partial page rendering process is in progress. It facilitates designing an intuitive user interface while a partial page rendering is in progress. In essence, it can be used in conjunction with the Update Panel control to enhance the user experience while some asynchronous update operation is in progress in your Ajax enabled ASP.NET web pages.
- UpdatePanel  You need to use this control to implement partial page updates in an Ajax enabled web page. Any control that you would want to participate in partial page updates or partial page rendering process should be contained inside an UpdatePanel control. Partial-page rendering can be used to refresh only a portion of your web page rather than the entire page. Note that there can be only one ScriptManager control but any number of UpdatePanel controls in your web page.
Summary
ASP.NET Ajax Server Extensions Framework is comprised of a collection of server controls that you can use to Ajax enable your ASP.NET web application with ease. In this article, we have had a look at the ASP.NET Ajax Server Extensions Framework and its components and how we can work with it. You can learn more on this framework from my upcoming book titled, "ASP.NET 4.0 Programming". Here is the link to the book at Amazon:. | http://www.webreference.com/programming/asp/AJAX-Server-Extensions/index.html | CC-MAIN-2017-34 | refinedweb | 1,037 | 56.45 |
I want to attribute a unicode character to my segmented images, so that I can subsequently generate a font-file. We are well and truly in the domain of optical character recognition (OCR) here, but because I want absolute control of the results (and 100% accuracy) I’m going to take the simple approach of mapping glyph positions to characters myself.
If you’d like to follow along, the input files for this article may be found at, the notebook and output may be found.
As a reminder, here is a downsampled version the XKCD handwriting file:
First, I want to read in the files that we produced previously. These can be found at.
I get metadata from the filename using the excellent parse library.
import glob import os import matplotlib.pyplot as plt import numpy as np import parse pattern = 'stroke_x{x0:d}_y{y0:d}_x{x1:d}_y{y1:d}.png' strokes_by_bbox = {} for fname in glob.glob('../b80e3b3ab9edbda9ac4304f742cf292b/stroke*.png'): result = parse.parse(pattern, os.path.basename(fname)) bbox = (result['x0'], result['y0'], result['x1'], result['y1']) img = (plt.imread(fname) * 255).astype(np.uint8) strokes_by_bbox[bbox] = img
In order to map strokes to glyphs, I’m going to want to sort them first by line, then from left to right.
At this point, I could either hard code the approximate y location of each baseline or attempt to cluster them. I opt for the latter, using a k-means implementation from
scipy.cluster.vq.kmeans.
To confirm I have the correct information and to visualise the data before clustering, I plot the baseline point (maximum y pixel location) of the stroke against its left-most x position:
import matplotlib.pyplot as plt import numpy as np xs, ys = zip(*[[bbox[0], bbox[3]] for bbox, img in strokes_by_bbox.items()]) xs = np.array(xs, dtype=np.float) ys = np.array(ys, dtype=np.float) plt.scatter(xs, ys, s=50) plt.gca().invert_yaxis() plt.autoscale(tight=True) plt.show()
There appears to be enough structure to group the glyphs into lines… let’s go for it.
import scipy.cluster.vq n_lines = 11 lines, _ = scipy.cluster.vq.kmeans(ys, n_lines, iter=1000) lines = np.array(sorted(lines)) print('Approx baseline pixel of lines:', repr(lines.astype(np.int16))) # Plot the strokes, and color by their nearest line. plt.scatter(xs, ys, s=50, c=np.argmin(np.abs(ys - lines[:, np.newaxis]), axis=0), cmap='Paired') plt.gca().invert_yaxis() plt.autoscale(tight=True) # Draw the line positions plt.hlines(lines, xmin=0, xmax=xs.max()) plt.show()
Approx baseline pixel of lines: array([ 447, 1103, 1708, 2316, 2932, 3380, 3830, 4276, 4713, 5584, 6045], dtype=int16)
Using the baseline position, group the strokes into their respective lines, and then sort each line from left to right.
glyphs_by_line = [[] for _ in range(n_lines)] for bbox, img in list(strokes_by_bbox.items()): nearest_line = np.argmin(np.abs(bbox[3] - lines)) glyphs_by_line[nearest_line].append([bbox, img]) # Put the glyphs in order from left-to-right. for glyph_line in glyphs_by_line: glyph_line.sort(key=lambda args: args[0][0])
Let’s take a look using the same notebook trick we did in part 1…
from IPython.display import display, HTML from io import BytesIO import PIL import base64 def html_float_image_array(img, downscale=5,{}" style="{}"/>' ''.format(encoded_string.decode('utf-8'), style)) return html
To keep this somewhat short, I’ll just show a few lines:
for glyph_line in glyphs_by_line[::4]: display(HTML(''.join(html_float_image_array(img, downscale=10) for bbox, img in glyph_line)))
paragraph = r""" a b c d e f g h i j k l m n o p q r s t u v w x y z u n a u t h o r i t a t i v e n e s s l e a t h e r b a r k i n t r a co l i c m i c r o c h e i l i a o f f s i d e r g l as s w e e d r o t t o l o a l b e r t i t e h e r m a t o r r h a c h i s o r g a n o m e t a l l i c s e g r e g a t i o n i s t u n e v a n g e l i c c a m p s t oo l A B C D E F G H I J K L M N O P Q R S T U V W X Y Z I-pronoun U N A U T H O R I T A T I V E N E S S L EA T H E R B A R K I N T R A CO L I C M I CR OCH E L I A O F F S I D ER G LA S S W EE D R O TT O L O A LB E R T I T E H ER M A T O RR H A C H I S O R G A N O M E T A LL I C S E G R E G A T I ON I S T U N E V A N G E L I C CA M PS TO O L + - x * ! ? # @ $ % ¦ & ^ _ - - - ( ) [ ] { } / \ < > ÷ ± √ Σ 1 2 3 4 5 6 7 8 9 0 ∫ = ≈ ≠ ~ ≤ ≥ |> <| 🎂 . , ; : “ H I ” ’ ‘ C A N ' T ' " É Ò Å Ü ≪ ≫ ‽ Ē Ő “ ” """.strip() paragraphs = [[char for char in line.replace(' ', ' ').split(' ') if char] for line in paragraph.split('\n')]
As I mentioned in the previous post, joining together all strokes into constituent glyphs wasn’t easily achievable. We therefore have four glyphs that each require two strokes to be merged before we can map them to the appropriate unicode character(s). The glyphs in question are |>, <|, ≪ and ≫.
glyphs_needing_two_strokes = ['≪', '≫', '|>', '<|']
We need the function from part 2 which merges together two images:
def merge(img1, img1_bbox, img2, img2_bbox): bbox = (min([img1_bbox[0], img2_bbox[0]]), min([img1_bbox[1], img2_bbox[1]]), max([img1_bbox[2], img2_bbox[2]]), max([img1_bbox[3], img2_bbox[3]]), ) shape = bbox[3] - bbox[1], bbox[2] - bbox[0], 3 img1_slice = [slice(img1_bbox[1] - bbox[1], img1_bbox[3] - bbox[1]), slice(img1_bbox[0] - bbox[0], img1_bbox[2] - bbox[0])] img2_slice = [slice(img2_bbox[1] - bbox[1], img2_bbox[3] - bbox[1]), slice(img2_bbox[0] - bbox[0], img2_bbox[2] - bbox[0])] merged_image = np.zeros(shape, dtype=np.uint8) merged_image.fill(255) merged_image[img1_slice] = img1 merged_image[img2_slice] = np.where(img2 != 255, img2, merged_image[img2_slice]) return merged_image, bbox
characters_by_line = [] for line_no, (character_line, glyph_line) in enumerate(zip(paragraphs, glyphs_by_line)): glyph_iter = iter(glyph_line) characters_this_line = [] characters_by_line.append(characters_this_line) for char_no, character in enumerate(character_line): bbox, img = next(glyph_iter) if character in glyphs_needing_two_strokes: other_bbox, other_img = next(glyph_iter) img, bbox = merge(img, bbox, other_img, other_bbox) characters_this_line.append([character, bbox, img])
for line in characters_by_line[-3:]: display(HTML(''.join(char + html_float_image_array(img) for char, bbox, img in line)))
Finally, save out each glyph as a PPM.
import skimage.io replacements = {'/': 'forward-slash', '_': 'underscore'} for line_no, line in enumerate(characters_by_line): for char_no, (char, bbox, img) in enumerate(line): char_repr = '-'.join(replacements.get(c, c) for c in char) hex_repr = '-'.join(str(hex(ord(c))) for c in char) fname = ('char_L{}_P{}_x{}_y{}_x{}_y{}_{char_repr}_{hex_repr}.ppm' ''.format(line_no, char_no, *bbox, char_repr=char_repr, hex_repr=hex_repr)) skimage.io.imsave(fname, img)
Conclusion
In this edition, I merged the few remaining strokes together to produce the finished glyphs, and classified each of the glyphs with associated characters (mostly unicode). I then saved these rasters out to a semantic filename in the PPM format. Next up, convert the rasters to vector SVGs so that we can import them into our font tool programatically.
This Article was Originally posted here licensed under Creative Commons 4.0. The next article in this series will be Converting PPM to SVG, and creating a font with FontForge. | https://opendatascience.com/blog/classifying-segmented-strokes-as-characters-part-3-of-an-xkcd-font-saga/ | CC-MAIN-2017-26 | refinedweb | 1,351 | 61.36 |
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\Microsoft.WinJS.1.0.RC\1.0\DesignTime\CommonConfiguration\Neutral\Microsoft.WinJS.1.0.RC\css
It looks like you're new here. If you want to get involved, click one of these buttons!
I will into it a bit deeper, to see how the panels and toolbars works, to see if it can be solved with a custom arrangerKind, or will need deeper work.
Media Capture
I'm not sure if creating an enyo.Windows object just to refactor the entire Windows API to make it look more Enyo is a good idea or a waste of time, as the only issue is dealing with every function being a promise object, and seems pretty easy.
Maybe wrapping just the WinJS APIs? Thoughts?
There are also other stuff, but that's perfectly ignorable, as is related to using their own UI (and that's something we're not doing).
So, I think a partial wrap of the WinJS namespace (specifically WinJS.Application and WinJS.Resources.oncontextchanged event) will be enough.
All the other stuff is UI or data-binding related, or covered by Enyo. I will work on this this weekend.
@MachiApps, you have Visual Studio installed? If so, could you try to extract ui-dark.css and ui-light.css files? As they contain the exact styles, it's a good place to look for restyling... | https://forums.enyojs.com/discussion/522/community-project-proposal-winjs-compatibility-library | CC-MAIN-2020-16 | refinedweb | 237 | 67.96 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.