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
|
|---|---|---|---|---|---|
Post your Comment
Customize the Icon in a JCheckBox Component of Java Swing
Customize the Icon in a JCheckBox Component of Java Swing... to customize the icon in a
check box component. That means any icon can be shown where...
box component of swing. The icon is passed to the setIcon() method
jcheckbox
jcheckbox How to insert value into database from jcheckbox using java swing
jcheckbox not enabled in java - Swing AWT
jcheckbox not enabled in java . im new to java..
jcheck box not enabled after i placed in sort select table in gui. what can i do to enable and made a click on it.after that selected rows are are opened in excel . already i.
? |
Creating a Frame in Java Swing |
Setting the Icon for a Frame |
Message... Rollover and Pressed Icon JButton Component |
Creating a JCheckbox Component... Component
Java Swing Tutorial Section - II
Limiting
Values in Number
Setting an Icon for a Frame in Java
an icon for
the frame in Java Swing.
This program helps us to set the icon (image) on the
title bar of the frame. When you open frame or window the icon... Setting an Icon for a Frame in Java
Setting icon on the button in Java
Setting icon on the button in Java
This section illustrates you how to show the icon on
the button in Java Swing.
This program sets the icon on the button in Java
JSlider Component of Java Swing
JSlider Component of Java Swing
...
component of Java Swing. A Slider is a Swing tool which you can use for selecting....
In this program, events on the JSlider component have
also been shown. If you increase
Creating Check Box in Java Swing
component in Java Swing.
In this section, you can learn simply creating the
Check Box in Java Swing. Check Boxes are created in swing by creating the
instance...
Creating Check Box in Java Swing
Java error icon
Java error icon
JOptionPane's icon
support specify icon to which... an error icon. For this we have a class name java error icon. Inside
the main
Java Swing Tutorials
in a JCheckBox Component
This section shows you how to customize the icon... in
Java Swing Applications.
Adding
an Icon to a JButton... of swing in java. Rollover means moving mouse pointer above the
icon
What is Java Swing?
What is Java Swing?
Here, you will know about the Java swing. The Java
Swing provides... and GUIs components. All Java Swing classes imports form the import
Java swing
Java swing Does Swing contains any heavy weight component
Create a JComboBox Component in Java
Component
of swing in java. The
JComboBox is used to display drop-down list...
Create a JComboBox Component in Java
... to create a combo box
in swing using it's constructor.
itemStateChanged
Component gui - Java Beginners
Component gui Can you give me an example of Dialog in java Graphical user interface? Hi friend,
import javax.swing.*;
public...://
Thanks
java swing - Java Beginners
java swing How to upload the image in using java swings.
ex- we...);
setIconTextGap(12);
}
public Component getListCellRendererComponent... icon = toolkit.getImage(f.getPath());
Image scaledIcon
Prinnt UNICODE character on swing component
Prinnt UNICODE character on swing component Hello,
I am trying to put unicode character n swing component.
can anyone tell me how to do this?
Thank you
Java Program - Swing AWT
Java Program Write a Program that display JFileChooser that open...);
setIconTextGap(12);
}
public Component getListCellRendererComponent(JList...(f.getName());
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image icon
Java component
Java component What is the preferred size of a component
swing
swing How to make swing component auto-resizable when JFrame resize
SWING
SWING A JAVA CODE OF MOVING TRAIN IN
Java Swing
Java Swing Write an applet program to transfer the content of the text field into the listbox component on clicking a button code project
...++");
model.addElement("Java");
model.addElement("Perl");
model.addElement
Making a component drag gable in java
Making a Component Draggable in Java
... to
transfer the transferable swing component from on the another. Both components
should be the swing component. This class is helpful to copy from one component
Post your Comment
|
http://www.roseindia.net/discussion/18198-Customize-the-Icon-in-a-JCheckBox-Component-of-Java-Swing.html
|
CC-MAIN-2014-52
|
refinedweb
| 691
| 58.38
|
mqtt problem
I updated the fipy to 1.13.0.b1 version and does not recognize the mqtt module :(
someone knows how can i make ?? or what is the correct name of the module
i tried mqtt, MQTT, mqtt.simple, mqtt.robust in this way
import mqtt
import mqtt.simple etc
@livius thanks man i solved it
i create a folder in my project called lib then copy the raw code from the github.
thanks
@livius thanks thats the way to import libraries then ?
another problem LOL I still trying to get this done too
@yeffrimic
you must put first library into
/flash/libfolder
@yeffrimic this is the problem
|
https://forum.pycom.io/topic/2452/mqtt-problem
|
CC-MAIN-2022-21
|
refinedweb
| 109
| 82.04
|
How to restrict a Function to a part of a mesh given by a MeshFunction?
Hello,
I would like to restrict an existing function to only a part of the mesh. The wanted part is given by a MeshFunction. Simply project the function to a submesh doesn't work in parallel. I did some experimentation with Restriction() but this led to nothing.
Here a minimal example to explain what I'm trying to do:
from dolfin import *
mesh = UnitCubeMesh( 10, 10, 10 )
V0 = VectorFunctionS
v0 = project( Constant( ( 1, 1, 1 ) ), V0 )
plot( v0 )
domains = CellFunction( "size_t", mesh )
for cell in cells( mesh ):
p = cell.midpoint()
if p.x() < p.y():
domains[ cell ] = 1
else:
domains[ cell ] = 2
plot( domains )
v0_vec = v0.vector().array()
for cell in cells( mesh ):
if domains[ cell ] == 1:
print( cell ) # dummy line to make the code executable
# v0_vec[ k ] = 0 for the correct k
v0.vector(
interactive()
Question information
- Language:
- English Edit question
- Status:
- Solved
- For:
- DOLFIN Edit question
- Assignee:
- No assignee Edit question
- Solved by:
- Heinz Zorn
- Solved:
- 2013-06-24
- Last query:
- 2013-06-24
- Last reply:
-
I found the right indices:
v0_vec[ 3*cell.index() ] = 0
v0_vec[ 3*cell.index()+1 ] = 0
v0_vec[ 3*cell.index()+2 ] = 0
And of course thanks in advance for any help!
|
https://answers.launchpad.net/dolfin/+question/231265
|
CC-MAIN-2021-21
|
refinedweb
| 214
| 73.27
|
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo
You can subscribe to this list here.
Showing
14
results of 14
Patch 0351-* pushed to the libpng16 branch of the GIT repo.
Glenn
On Fri, Aug 31, 2012 at 5:36 PM, John Bowler <jbowler@...> wrote:
> Attached is a patch that fixes pngtopng.c and example.c and also
> improves the error messages slightly (the error message was empty if
> the png_image version number was wrong.)
>
> John Bowler <jbowler@...>
Attached is a patch that fixes pngtopng.c and example.c and also
improves the error messages slightly (the error message was empty if
the png_image version number was wrong.)
John Bowler <jbowler@...>
Yes, and there's another bug in there somewhere because even with the
fix I'm getting a failure to read pngout.png - I'll investigate and
John Bowler <jbowler@...>
On Fri, Aug 31, 2012 at 12:51 PM, Glenn Randers-Pehrson
<glennrp@...> wrote:
>
On Thu, Aug 30, 2012 at 5:38 PM, Chris Share <cpsmusic@...> wrote:
>
In that code if 'color_type' is PNG_COLOR_TYPE_PALETTE then
row_pointers[y][(x * bit_depth)/8] is a byte which contains the
bit_depth index of pixel x. If bit_depth is 8 then the index is the
value of that byte, otherwise the indices are packed from the most to
the least significant bit in the byte, so you need to do some bit
bashing to get an individual index out:
(row_pointers[y][(x * bit_depth)/8] >> ((8-bit_depth) -
((x*bit_depth) & 7))) & (bit_depth-1)
bit_depth is always a power of 2. Caveat emptor on the above line of
code - check it gets the right bits.
John Bowler <jbowler@...>
Hi,
I'm currently developing a weather tracking application. The input to the application is a series of indexed .png images. I need to access the .png's individual pixel values. I'm new to libpng.
I've managed to implement some code that reads and displays RGBA pixel values from an RGBA .png however I'm not clear about how to get the pixel values for an indexed image. I understand the principles involved (I think!) - the palette is stored in the PLTE chunk with the index into the palette representing a color value.
What I'm not clear about is how to read (in C code) the palette values for an indexed image - is there an example of how to do this available?
The code that I'm using (so far) is based on the read_png_file and process_file functions from the following:
Cheers,
Chris
libpng-1.6.0beta28 is available from
and from
Version 1.6.0beta28 [August 29, 2012]
Unknown handling fixes and clean up. This adds more correct option
control of the unknown handling, corrects the pre-existing bug where
the per-chunk 'keep' setting is ignored and makes it possible to skip
IDAT chunks in the sequential reader (broken in earlier 1.6 versions).
There is a new test program, test-unknown.c, which is a work in progress
(not currently part of the test suite). Comments in the header files now
explain how the unknown handling works.
Allow fine grain control of unknown chunk APIs. This change allows
png_set_keep_unknown_chunks() to be turned off if not required and causes
both read and write to behave appropriately (on read this is only possible
if the user callback is used to handle unknown chunks). The change
also removes the support for storing unknown chunks in the info_struct
if the only unknown handling enabled is via the callback, allowing libpng
to be configured with callback reading and none of the unnecessary code.
Corrected fix for unknown handling in pngtest. This reinstates the
libpng handling of unknown chunks other than vpAg and sTER (including
unsafe-to-copy chunks which were dropped before) and eliminates the
repositioning of vpAg and sTER in pngtest.png by changing pngtest.png
(so the chunks are where libpng would put them).
Added "tunknown" test and corrected a logic error in png_handle_unknown()
when SAVE support is absent. Moved the shell test scripts for
contrib/libtests from the libpng top directory to contrib/libtests.
png_handle_unknown() must always read or skip the chunk, if
SAVE_UNKNOWN_CHUNKS is turned off *and* the application does not set
a user callback an unknown chunk will not be read, leading to a read
error, which was revealed by the "tunknown" test.
Cleaned up and corrected ICC profile handling.
contrib/libtests/makepng: corrected 'rgb' and 'gray' cases. profile_error
messages could be truncated; made a correct buffer size calculation and
adjusted pngerror.c appropriately. png_icc_check_* checking improved;
changed the functions to receive the correct color type of the PNG on read
or write and check that it matches the color space of the profile (despite
what the comments said before, there is danger in assuming the app will
cope correctly with an RGB profile on a grayscale image and, since it
violates the PNG spec, allowing it is certain to produce inconsistent
app behavior and might even cause app crashes.) Check that profiles
contain the tags needed to process the PNG (tags all required by the ICC
spec). Removed unused PNG_STATIC from pngpriv.h.
Glenn
libpng-1.6.0beta27 is available from
and from
Version 1.6.0beta27 [August 11, 2012]
Do not compile PNG_DEPRECATED, PNG_ALLOC and PNG_PRIVATE when __GNUC__ < 3.
Do not use __restrict when GNUC is <= 3.1
Removed references to png_zalloc() and png_zfree() from the manual.
Fixed configurations where floating point is completely disabled. Because
of the changes to support symbol prefixing PNG_INTERNAL_FUNCTION declares
floating point APIs during libpng builds even if they are completely
disabled. This requires the png floating point types (png_double*) to be
declared even though the functions are never actually defined. This
change provides a dummy definition so that the declarations work, yet any
implementation will fail to compile because of an incomplete type.
Re-eliminated the use of strcpy() in pngtest.c. An unncessary use of
strcpy() was accidentally re-introduced in libpng16; this change replaces
it with strncpy().
Eliminated use of png_sizeof(); use sizeof() instead.
Use a consistent style for (sizeof type) and (sizeof (array))
Cleanup of png_set_filler(). This function does very different things on
read and write. In libpng 1.6 the two cases can be distinguished and
considerable code cleanup, and extra error checking, is possible. This
makes calls on the write side that have no effect be ignored with a
png_app_error(), which can be disabled in the app using
png_set_benign_errors(), and removes the spurious use of usr_channels
on the read side.
Insist on autotools 1.12.1 for git builds because there are security issues
with 1.12 and insisting on anything less would allow 1.12 to be used.
Removed info_ptr->signature[8] from WRITE-only builds.
Add some conditions for compiling png_fixed(). This is a small function
but it requires "-lm" on some platforms.
Cause pngtest --strict to fail on any warning from libpng (not just errors)
and cause it not to fail at the comparison step if libpng lacks support
for writing chunks that it reads from the input (currently only implemented
for compressed text chunks).
Make all three "make check" test programs work without READ or WRITE support.
Now "make check" will succeed even if libpng is compiled with -DPNG_NO_READ
or -DPNG_NO_WRITE. The tests performed are reduced, but the basic reading
and writing of a PNG file is always tested by one or more of the tests.
Consistently use strlen(), memset(), memcpy(), and memcmp() instead of the
png_strlen(), png_memset(), png_memcpy(), and png_memcmp() macros.
Removed the png_sizeof(), png_strlen(), png_memset(), png_memcpy(), and
png_memcmp() macros.
Work around gcc 3.x and Microsoft Visual Studio 2010 complaints. Both object
to the split initialization of num_chunks.
Glenn
libpng-1.5.13beta01 is available from
and from
Version 1.5.13beta01 [August 8, 2012]
Do not compile PNG_DEPRECATED, PNG_ALLOC and PNG_PRIVATE when __GNUC__ < 3.
Removed references to png_zalloc() and png_zfree() from the manual.
Revised PNG_FP_EXPORT and PNG_FIXED_EXPORT macros to avoid generating
lone semicolons (patch ported from libpng-1.6.0beta11).
Glenn
It's just the known bug (fixed in libpng16) that the new
PNG_FIXED_EXPORT and PNG_FP_EXPORT macros don't include the ';' at the
end of the definition, so when FIXED or FP APIs are switched off the
semicolor is still there. It didn't happen before the macros because
every definition was wrapped in #ifdef/#endif (so everything got
removed).
So far as I can see the fix is to move the ';' inside the macro, as
was done in 1.6. I think that should be back ported to 1.5, because
while most compilers don't complain it's technically non-ANSI and it
was introduced in 1.5
John
Maybe the stray ';' is triggered somehow in scripts/options.awk by the lack of
a space separating the "/*" comment from the define in this line:
png.h:#define PNG_RGB_TO_GRAY_DEFAULT (-1)/*for red/green coefficients*/
I don't see anything else unusual in the vicinity. It's the only such comment
so just try inserting a space before the "/*" and see what happens.
Glenn
It's:
#define PNG_NO_foo
*NOT*
#define PNG_NO_foo_SUPPORTED
I don't know what the latter will end up doing for sure but I'm pretty
certain every one of your #define PNG_NO_whatever_SUPPORTED
definitions does nothing.
I suspect you are correct, however, in that there is a stray ";" being
generated; I'll investigate that more.
John Bowler <jbowler@...>
Hi,
I'm attempting to configure libpng 1.5.12 for an embedded system (ARM9, Green Hills compiler). I would like to strip out all floating point support, as well as selected other features. To that end, I've configured a pngusr.h file as follows:
#ifndef PNGUSER
>#define PNGUSER
>
>
>#define PNG_NO_MNG_FEATURES
>
>#define PNG_NO_CONSOLE_IO
>#define PNG_NO_STDIO
>#define PNG_NO_FLOATING_POINT_SUPPORTED
>#define PNG_NO_FLOATING_ARITHMETIC_SUPPORTED
>
>
>#define PNG_FIXED_POINT_SUPPORTED
>
>
>#define PNG_NO_READ_16BIT_SUPPORTED
>#define PNG_PROGRESSIVE_READ_SUPPORTED
>#define PNG_SEQUENTIAL_READ_SUPPORTED
>#define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
>
>
>#define PNG_NO_WRITE_TRANSFORMS
>
>#define PNG_NO_WRITE_ANCILLARY_CHUNKS
>#define PNG_NO_ASSEMBLER_CODE
>#define PNG_NO_WRITE_16BIT_SUPPORTED
>#define PNG_NO_WRITE_INTERLACING_SUPPORTED
>
>
>#define PNG_MAX_MALLOC_64K
>
>
>#endif
I'm using Cygwin tools to generate pnglibconf.h as indicated in scripts/pnglibconf.dfa, and no problems are noted here.
The problem shows up when I attempt to compile pngget.c. When attempting to build libpng, the compiler fails and reports:
"shared\libpng\png.h", line 1161: error #381-D: extra ";" ignored
> int error_action, double red, double green));
Using the preprocessor, I've tracked the problem down to a stray semicolon here:
extern void (png_set_gray_to_rgb) (png_structp png_ptr);
>
>
>;
>
>
>extern void (png_set_rgb_to_gray_fixed) (png_structp png_ptr, int error_action, png_fixed_point red, png_fixed_point green);|
>
>
which appears to be related to how PNG_FP_EXPORT is getting processed in png.h.
Has anyone else seen this problem? Are there suggested work-arounds?
Thanks!
Brett L. Moore, PhD
|
http://sourceforge.net/p/png-mng/mailman/png-mng-implement/?viewmonth=201208
|
CC-MAIN-2015-18
|
refinedweb
| 1,771
| 65.01
|
Ross Paterson <ross at soi.city.ac.uk> wrote: > > Text.ParserCombinators.Parsec > > namespace should be deprecated in favour of: > > Text.Combinators.Parsec > > If you want to make them shorter, it's the redundant "Combinators" > that should go. Is there not a valid distinction between a Parser library (e.g. for XML documents), and a ParserCombinator library (which enables one to write parsers)? Is it helpful to blur the boundaries between the glue and the things being glued? > While we're complaining about module names, how about > System.Console.GetOpt? What is wrong with it? (Not a rhetorical question - I really can't guess!) Ketil Malde wrote: > I've never understood why there is a need for a deep, sparse hierarchy. Really, it is just a social mechanism to encourage developers to come up with long, descriptive names. You could just as easily drop the dots and have TextParserCombinatorsParsec or Text_ParserCombinators_Parsec with almost no technical impact. But lots of people would complain about the amount of letters to type if that was the scheme, and somehow, if we use dots, it lessens the resistance. :-) I'm sure, without dots, we would still be stuck with lots of short module names in every project, clashing with everyone elses libraries. Regards, Malcolm
|
http://www.haskell.org/pipermail/libraries/2006-March/005043.html
|
CC-MAIN-2014-15
|
refinedweb
| 209
| 66.84
|
So I’ve recently just started a programing course and I have been given a uml diagram to complete, as you can see in the image it has the description of what the program is meant to do but im rather confused as to where I’m meant to go or what I’m meant to do after the Count = 1 to loops section, I’ve made an attempt at it but just can’t seem to get it working, any help would be appreciated.
namespace project { class Program { static void Main(string[] args) { int divisor; int loops; bool keyBoardinput; int count = 0;
Console.WriteLine("Please enter your loops number."); keyBoardinput = int.TryParse(Console.ReadLine(), out loops); Console.WriteLine("Please enter your divisor number, make sure its bigger than the loops."); keyBoardinput = int.TryParse(Console.ReadLine(), out divisor); if (keyBoardinput) while (loops >= divisor) { int result; result = count % divisor; if(result == 0) { Console.WriteLine(+count); } } else { Console.WriteLine("Sorry invalid input, try again"); } Console.ReadLine();
submitted by /u/Noxas97
[link] [comments]
|
https://howtocode.net/2019/08/uml-assistance/
|
CC-MAIN-2019-43
|
refinedweb
| 170
| 54.93
|
Docs |
Forums |
Lists |
Bugs |
Planet |
Store |
GMN |
Get Gentoo!
Not eligible to see or edit group visibility for this bug.
View Bug Activity
|
Format For Printing
|
XML
|
Clone This Bug
eselect with doc USE option fails.
eselect boost set xyzzy fails.
Reproducible: Always
Steps to Reproduce:
1. emerge eselect (with doc option set); or
2. eselect boost set 1.3.0 | eselect boost set 0.3 fail
Actual Results:
emerge eselect with (doc), fails with:
/usr/bin/rst2html.py < README > README.html
Traceback (most recent call last):
File "/usr/bin/rst2html.py", line 19, in <module>
from docutils.core import publish_cmdline, default_description
ImportError: No module named docutils.core
make: *** [README.html] Error 1
eselect boost set xyzzy fails with:
Removing symlinks from old version
!!! Error: ${link}" exists and isn't a symlink
Killed
Expected Results:
Emerge eselect with doc option should be tested so it works.
Eselect with set option should give a more informative error message, in
particular it should not say "${link}" which provides little information as to
the problem file.
Does python-updater fix your compilation problem? I left a comment on bug
269517 for your second problem.
Running python-updater (which I have done -- it takes 3 hours and produces a
6.6 MB output file) does not fix the problem.
I have determined what part of the problem is. The developer(s)/testers must
be using a different shell. Because the eselect script contains instances of
functions of the form "ec_....-xyzzy". The dash "-" is not a valid character
in symbols in bash. Changing it to an underscore "_" allows one to get past
that problem. There is still another problem that I haven't found yet. I
suspect the "${link}" error message is also due to the use of a different
shell.
Please have the developer(s) use and test shell scripts in "bash-3.2_p39"
rather than whatever they are using.
I am using app-shells/bash-3.2_p39 and it works for me. Have you checked the
suggestions on bug 269517?
Ok, I found out that the "${link}" error is coming from
/usr/share/eselect/modules/boost.eselect.
I modified the file enough to find out that "$link" is /usr/include/boost. I
suspect that this is yet another bug involving which shell is being used.
It turns out that that was a directory. If I rename it and do a "eselect set
boost 1" it works! (yea!).
However the use of an non-standard shell to do development is highly
undesirable. I note that /usr/bin/eselect starts with "#!/bin/bash"..
I would suggest that this bug not be labeled as resolved until eselect modules
are released that correct these problems. strongly applies here.
Upgrade path was broken for whoever was blindly using $some-overlay, and didn't
know what he was doing. If you have any of those version installed you have to
uninstall them, clean up /usr/lib{,64} and /usr/include and install boost from
::gentoo.
bash-3.2_p39 has some nasty drawbacks. Did you try bash-3.2_p48, Robert?
Could you please provide us with the following information (and then reopen
this bug):
- output of "emerge --info"
- installed versions of:
app-admin/eselect
app-admin/eselect-boost
dev-python/docutils
(In reply to comment #2)
> Because the eselect script contains instances of functions of the form
> "ec_....-xyzzy". The dash "-" is not a valid character in symbols in bash.
Hyphens are (and have always been) valid characters in bash function names.
They are forbidden in variable names and in POSIX mode only.
(In reply to comment #4)
> However the use of an non-standard shell to do development is highly
> undesirable.
Sorry, but what are you talking about here?
>.
Again, these options exist since a long time (bash-2.05b has both of them).
|
http://bugs.gentoo.org/269722
|
crawl-002
|
refinedweb
| 637
| 69.07
|
In this post, we are going to construct a laser security circuit which can send SMS alert to owner of the property or anyone else and activate loud alarm to deter the crook, which can be interfaced via relay.
We always fear about crooks especially when we leave our property alone, this where security systems come in handy. Loud alarm may be enough to grab everyone’s attention nearby area and deter the thief.
SMS alert warns the user to take necessary action just after the crook broke in to your property.
The security systems should be implemented at week points of your house/office, such as doors and windows, sometimes multiple numbers of security systems are required for maximum protection against thief at different points of your home or office.
How it Works
The circuit consists of Arduino, which sense intrusion and take decisions. GSM modem receives command for sending SMS to user and few other passive components to detect intrusion.
The Arduino scans the laser beam for interruption in light 500 times a second. The LDR senses the presence laser light and gives signal to Arduino.
The 10K and LDR forms voltage divider, the analogue signal is taken from a point between these two components.
When the incident light intensity reduces to certain degree or light completely cut-off the arduino recognize as intrusion.
The 10K resistor which is connected to “activate button” acts as pull down resistor to prevent the arduino pin from activating randomly.
The transistor activates the relay in case of an intrusion and the diode protects the rest of the circuit from high voltage spike while switching the relay on and off.
You can connect a siren or lights or whatever you wish to connect to relay.
To activate the security system, we have to press the activate button, the LED indicator confirms that the button is pressed.
The system gets activated only after 2 minutes; this will give time to lock you property and leave the place.
When you return home, to deactivate the system press the reset button. Solder a push-to-on button from reset button terminal of Arduino, so that the reset button to deactivate the system is easily accessible from outside the setup.
Once the circuit detected intrusion, the relay will be activated for 2 minutes and it turns off and it will be ready to detect next intrusion.
The GSM modem need external power supply as arduino can’t provide enough current to the module. Please insert a valid SIM card with a working SMS plan.
That’s all about this SMS based laser security circuit; now let’s see how to implement the setup in correct way.
How to implement the setup:
Place the laser source and arduino circuit in such a way that the laser light falls exactly on LDR. You can also try mirrors reflecting the laser beam to cover a large area.
If you own pets and to prevent accidental or false alarm, elevate the whole setup to hip level of an adult. You pets will go under the laser beams preventing false triggering.
The LDR is susceptible to errors/false alarm when ambient light falls on it. To avoid these kinds of errors, we need to enclose the LDR with opaque hollow cylinder with one end open and other end closed made up of plastic or any other material.
LDR Setup
Make sure the front portion of the tube is covered as well and only tiny hole with few millimeters in diameter for entering laser beam.
When the laser beam falls on the LDR the value read by the arduino is low but when light interruption is detected the value will go to peak at the same instant, which you can witness the same from serial monitor.
Once the light intensity goes below the pre-determined threshold, arduino trigger the relay and send SMS alert to the user.
Program Code:
//--------------Program developed by R.Girish---------------//
#include <SoftwareSerial.h>
SoftwareSerial gsm(9,8);
int LDR = A0;
int OP = 7;
int start = 6;
int LED = 5;
int th = 300;
int x;
unsigned long A = 1000L;
unsigned long B = A * 60;
unsigned long C = B * 2;
void setup()
{
Serial.begin(9600);
gsm.begin(9600);
pinMode(LDR,INPUT);
pinMode(OP,OUTPUT);
pinMode(start,INPUT);
pinMode(LED,OUTPUT);
}
void loop()
{
if(digitalRead(start)==1)
{
digitalWrite(LED,HIGH);
delay(C);
A:
x = analogRead(A0);
Serial.println(x);
if(x<=th)
{
delay(2);
goto A;
}
if(x>=th)
{
digitalWrite(OP,HIGH);
Serial.println("Sending SMS......\n");
gsm.println("AT+CMGF=1");
delay(1000);
gsm.println("AT+CMGS=\"+91XXXXXXXXXX\"\r"); // Replace x with mobile number
delay(1000);
gsm.println("Security Warning: Intruder detected."); // The SMS text you want to send
delay(100);
gsm.println((char)26); // ASCII code of CTRL+Z
delay(1000);
Serial.println("Message is sent\n");
delay(C);
digitalWrite(OP,LOW);
goto A;
}
}
}
//--------------Program developed by R.Girish---------------//
Please replace the “XXXXXXXXXX” with your phone number to receive SMS.
"Howdy friend! Are you a newcomer and looking for personalized help? Please feel free to use the comment box below for posting your queries, and get guaranteed replies within an hour!"
Forum Discussion - Ask a Question
vhafuwi says
Hello Mr Swagatam
I have gone through this post , noted that modification on Aduino Code falls under premium projects ,
I require a quote on some code modification for the above project post for my specific solution , I may have to send to it through to your email
regards
Swag says
Hi Vhafuwi, sorry Arduino coding not being my area of expertise would be difficult to address, and approaching the actual author may be also difficult at the moment for me. Kindly bear with me!
Gycon says
Hi
Pls am done with the project and tested it, everything is working but am not receiving SMS from the GSM. So pls help me out whether there is a problem with the coding.
Swag says
Mr. Girish will reply you soon.
Girish Radhakrishnan says
Hi Gycon,
Open the Serial monitor and try triggering the circuit. You must see “Message is sent” on serial monitor, if yes the circuit is triggered and Arduino is communicating with GSM. If no SMS to your mobile phone, check you connection to GSM module, still no results. Check your GSM module is properly working or not.
Regards
gycon says
hi
pls which part of the circuit is the relay output terminals connects to
Swag says
The relay coil connects with the transistor. For more on relay connections you can refer to the following post:
Gycon says
Hi
Pls am done with the wiring of the diagram and uploaded the program to it but am not having any feedback. Pls kindly help me out.
Girish Radhakrishnan says
Hi Gycon,
I didn’t get you….. can you elaborate what feedback do you mean.
Regards
Gycon says
Am talking of the SMS and the LED which suppose to light up as the output results.
Gycon says
Hi
Pls on the GSM which pins is meant for the external power
Girish Radhakrishnan says
Hi Gycon,
The external power to your GSM module is the DC jack generally. The external “pin” on your GSM module may be differ from mine, so search your model on google or just take closer look on the board it will be named as “Vcc” or “12V” something similar.
Regards
Rakesh says
Hlo sir..
I want such kind an project in which an megnatic switch turns on the one specific pin of arduino to make a call from gsm module to a mobile number…
Plz explain me the complete circuit and the parts list….this project is very important for me…
Not an notifying msg is required…
Just an call by turning on the read switch….
Rakesh41035@gmail.com
Thank u.
Swag says
Hello Rakesh,
presently all Arduino related projects are premium projects, so you may have to pay for the customization, or have to buy the entire kit from us.
Rakesh says
Okkk sir…
How much i hav to pay for this article ????
Swag says
I’ll forward this question to Mr. Girish, he will reply you regarding the price soon…
Girish Radhakrishnan says
Hi Rakesh,
From you comments what we can understand is:
You want to get a call from the GSM module to a mobile number, if the magnetic switch (reed switch) is triggered.
Shall we confirm your requirement? and proceed?
Regards
Rakesh says
Yes sir i want to manage a call by triggering (on/off)the read switch ….
And the call must be repeated until the call is being not answered….
Girish Radhakrishnan says
Hi Rakesh,
Let’s make the technical aspects of your project clear once again,
When the reed switch is triggered you will receive a call to your phone and the call ring to your phone lasts 40 to 50 seconds, it is your wish to cut the call or not. But anyways the call gets disconnected (by the mobile network) after 50 seconds automatically and you will get missed call notification.
The pricing for the project:
For Each word explanation is 1 rupee. (Around 500 words of explanation is expected, but can vary)
For Each line of program code is 10 rupee. (Around 100 to 150 lines of code is expected, but can vary)
Regards
siamfj says
Hello sir Some problem gsm.println(“AT+CMGS=”+91XXXXXXXXXX”r”); // Replace x with mobile number
delay(1000); please solved.And e-mail me code for project.
Swag says
Hello siamfj, I’ll forward this question to Mr. Girish, he will solve the issue for you soon…
Girish Radhakrishnan says
Hi siamfj,
The corrected code will be placed soon.
Regards
Swag says
Thank you Girish,
I have made the necessary corrections, I hope the system will work correctly now.
malek says
i am AUTOMATION & ROBOTICS ENGINEER
GSM Module how it cost ?
kind regards
Malek
Swag says
You can search online for the rates, you can find it easily
OFFOR KELVIN PIUS says
Hi,SWAG. i am really grateful to you for making your circuits open to all God will bless you abundantly.
Pls kindly assist me in this project, i want to build a security system whereby the system will send sms or message to numbers and location using gprs.
Thank hoping to hearing from you soonest from Kelvin
Swag says
Thanks Offor, I am glad you liked the circuits. The Arduino circuits are not designed by me, they are designed by Mr.Girish, so I’ll inquire with him and get back to you soon with the reply. By the way why GPRS is required here? Please enlighten me about this….
Jigar Mistry says
gsm.println(“AT+CMGS=\”+91XXXXXXXXXX\”+91XXXXXXXXXX\r”); // Replace x with mobile number
above example is possible ?can we add two or more number!!!?
Rina Gracia says
Hi! I would like to make this project together with my classmates for our subject Spectra. Do you have a list for the components used in this? Thank you very much!
Swagatam says
Hi, I am glad you have selected this project!
All the parts shown in the diagram are standard parts, you just have to copy them as given in the diagram and show it to the shopkeeper…the shopkeeper will understand and provide them to you appropriately.
Please click the diagram to get an enlarged view of it….
Jade Villanueva says
Thank you
Jade Villanueva says
What is "ASCII code of CTRL+Z" ? Can i change the activation time??
Girish Radhakrishnan says
Hi Jade,
It is termination character for sending SMS, after sending SMS we have to terminate the process.
On which part you want to change activation time? Can you elaborate please.
Regards
|
https://www.homemade-circuits.com/2016/11/sms-based-laser-security-circuit-using.html
|
CC-MAIN-2019-04
|
refinedweb
| 1,952
| 62.48
|
I'm just wondering, is there a way for an import hook to cancel/ignore/no-op a require() so that this code works?
unshift @INC, \&import_hook;
require Foo; # nothing is loaded
require Bar; # nothing is loaded
[download]
I've tried:
unshift @INC, sub {
return (undef, sub {0});
}
[download]
use Tie::Handle::Scalar;
unshift @INC, sub {
tie *FH, "Tie::Handle::Scalar", ""; # or "1;\n"
#$INC{$name} = undef; # or $name. testing
return (*FH);
}
[download]
Perl seems to go to the next @INC entry for all the above two cases. What am I doing wrong?
In reply to Cancel/no-op a require
by sedusedan
Perl Cookbook
How to Cook Everything
The Anarchist Cookbook
Creative Accounting Exposed
To Serve Man
Cooking for Geeks
Star Trek Cooking Manual
Manifold Destiny
Other
Results (145 votes),
past polls
|
http://www.perlmonks.org/index.pl?parent=1007731;node_id=3333
|
CC-MAIN-2014-41
|
refinedweb
| 133
| 55.58
|
Datagrid component, dataprovider dependentartscan65 Dec 24, 2009 2:33 AM
Hello, thanks in advance and sorry for my bad english,
I want to make a new component based on the DataGrid component. The plan is like this:
- Bind DG component to a AC dataprovider.
- On component creationcomplete, check if the dataprovider has any records (if it was populated before so wont have to re-load)
- If no then call a dataservice and return an AC from AMFPHP (returns array, converts it to AC)
- Populate the DG with the result
I have accomplished all the above BUT !!
If i have a blank DG (no columns) when the data returns fills up the DG fine
If i have pre-defined DataGridColumns then altho the DG gets filled with the objects and each object traces the correct object attribute? DG shows blank cells !! All the cells, and all blank... Tested tracing the DG object onClick and appear ok...
I know is kinda weird request amd too complicated...
Thanks
1. Re: Datagrid component, dataprovider dependentchris.huston.t10 Dec 24, 2009 4:39 AM (in response to artscan65)
Did you set the dataField property for your pre-defined DataGridColumns to match the fields in your dataset from AMFPHP? If you are seeing blank cells, then this is probably the problem. For example, if your data was like this:
[{name:John, email:john@something},
{name:Sarah, email:sarah@something}]
Then you would have:
<mx:DataGridColumn
<mx:DataGridColumn
Chris
2. Re: Datagrid component, dataprovider dependentartscan65 Dec 25, 2009 1:18 AM (in response to chris.huston.t10)
Thank you for your reply.
Yes the dataField properties are all set. And the DG is NOT blank. Has all the records and onClick each one is well formed object with it's properties. Just SHOWS blank meaning for some reason the text boxes are like invisible!!
Thank you
Date: Thu, 24 Dec 2009 05:40:09 -0700
From: forums@adobe.com
To: artscan@msn.com
Subject: Datagrid component, dataprovider dependent
Did you set the dataField property for your pre-defined DataGridColumns to match the fields in your dataset from AMFPHP? If you are seeing blank cells, then this is probably the problem. For example, if your data was like this:
[,
]
Then you would have:
<mx:DataGridColumn
<mx:DataGridColumn
Chris
>
3. Re: Datagrid component, dataprovider dependentchris.huston.t10 Dec 25, 2009 4:55 AM (in response to artscan65)
Can you post your mxml code for your DataGrid and also what the data you are getting back from AMFPHP looks like? Whenever I get invisible text boxes, it is because I made a mistake in setting the dataField parameter. If there is a typo in my dataField or the dataset used different field names than I thought, I will see rows in my dataGrid that can be selected, but they will have invisible text boxes as you described. Sometimes hardcoding a small ArrayCollection for your DataProvider can help in debugging.
Chris
4. Re: Datagrid component, dataprovider dependentartscan65 Dec 29, 2009 8:51 PM (in response to chris.huston.t10)
Thank you,
Seems for some reason when data return and populate the DG it 'looses' it's column definition. Here is a work around if anyone stumbles on this at the future:
import mx.controls.dataGridClasses.DataGridColumn;
private function onRepply(arr:Array):void {
var ac:ArrayCollection = new ArrayCollection(arr);
for (var i:Number = 0; i < _formatter.length; i++) {
var col:DataGridColumn = new DataGridColumn(_formatter[i].dataField);
col.headerText = _formatter[i].title;
col.dataField = _formatter[i].dataField;
col.width = _formatter[i].width;
var cols:Array = this.columns;
cols.push(col);
this.columns = cols;
}
this.dataProvider = ac;
}
where:
_fields is an array holding the fields to return from database, ex. _fields = ('field1', 'field2'...)
_formatter is an array of objects defining the columns, ex.
<mx:Array
<mx:Object
<mx:Object
....
</mx:Array>
and you assign it to the component.
Thanks...
Mikhail Zoupas
|
https://forums.adobe.com/thread/544391
|
CC-MAIN-2018-30
|
refinedweb
| 647
| 65.22
|
Some time ago, a dev team here at Microsoft asked me to review their XML vocabulary that they had designed. They wanted to know if the element and attribute names in their vocabulary design were good ones.
This blog is inactive.
New blog: EricWhite.com/blog
Blog TOCNote: I suspect that this is one of those religious issues. I’m not suggesting that this is the one and only way to design XML vocabularies – this is just what I do. There may be good reasons to use different rules. (I have broken every rule here, probably. Well, that’s the story of my life – make mistakes, suffer from the effects, and try not to do it again. J)
Once you release some software that uses a specific vocabulary, it tends to be set in stone. Even if there’s a problem with the vocabulary, it often is more problematic to try to change it after the fact than to continue to work around the problem, so designing vocabularies deserves some thought beforehand.
Much of what I’m presenting here derives from the Guidelines for Names from the .NET Framework Design Guidelines. Krzysztof Cwalina and Brad Abrams are the authors of the book Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries. Some important excerpts of that book are published on MSDN for easy reference, but I consider that book to be a ‘must read’ on the list of professional .NET developers.
Pascal Casing For Tags Longer than Three Characters
Use Pascal casing for element and attribute names that are longer than three characters.
There are mainly three schemes used for casing:
Pascal casing: The first letter in the tag and the first letter of each subsequent concatenated word are capitalized. For example:
<ForegroundColor>Black</ForegroundColor>
Lower casing with hyphens: tags are lower-case, and hyphens separate words. XSLT uses this style:
<apply-templates />
<value-ofselect=“title“ />
Camel casing: The first letter of a tag is lowercase and the first letter of each subsequent concatenated word is capitalized. For example:
<fatalErrorMessage>Contact your IT support department.</fatalErrorMessage>
I prefer Pascal casing for two reasons:
- I find the XML easier to read.
- If you use an XML to Object mapper such as LINQ to XSD, then the types that the mapper generates will conform to the .NET Framework Design Guidelines. If you use the LINQ to XML approach of pre-atomization of element and attribute names, those classes will contain public fields that conform to the guidelines.
I find that I’m somewhat happy that XSLT uses lower casing with hyphens, because if I use Pascal casing for my tags, it makes the elements and attributes in sequence constructors a little easier to see:
<xsl:stylesheetxmlns:xsl=‘‘version=‘1.0‘>
<xsl:templatematch=‘/Books‘>
<SelectedAuthors>
<Author>
<xsl:value-ofselect=‘Author/@Name‘/>
</Author>
</SelectedAuthors>
</xsl:template>
</xsl:stylesheet>
Capitalization Rules for Acronyms
It’s better to use acronyms in tags only when they are widely known and well understood – HTML, for example. Per the .NET Framework design guidelines, capitalize all letters of a two letter acronym, and capitalize the first letter of acronyms that are three characters or longer.
<IO>true</IO>
<Html>false</Html>
<GenerateXhtml>true</GenerateXhtml>
Don’t capitalize each word in compound words that are written as a single word. Examples: Endpoint, Lifetime, Diskdrive, Hashtable, and Grandchild.
One word that I have problems remembering how to capitalize is FileName. Some dictionaries don’t define it as a closed-form compound word (but some do). The .NET Framework guidelines capitalize it as FileName.
Don’t Use Abbreviations
Unless you are designing a highly-specialized vocabulary such as Open XML markup, optimize for readability instead of shortness of tags.
One abbreviation that it’s ok to use is the abbreviation for identifier (Id). Use Pascal casing for Id.
Just for fun: The .NET Framework Design Guidelines says that ‘Ok’ is an abbreviation. Actually, it might be an acronym. There are a number of theories on the origin of ‘OK’, but my favorite comes from a slogan during the American Presidential election of 1840. That election resulted in the oldest written usage of ‘OK’. The democratic candidate, President Martin Van Buren, was nicknamed ‘Old Kinderhook’ (after his birthplace in New York State), and his election campaign had a slogan, ‘Old Kinderhook is OK’. Van Buren wasn’t re-elected. But following the .NET Framework design guidelines, I would use Pascal casing for ‘Ok’.
The designers of Open XML had very good reasons for making element and attribute names short – documents can be very long, and an increase in name length can have an impact on performance and the memory that is used by tools, so they were justified in having names such as w:p, w:t, and w:sdt. Unless you are designing one of those highly specialized vocabularies, it’s better not to use single character tags.
Word Selection
Avoid language keywords such as ‘default’, ‘abstract’, ‘break’, and ‘event’. If you use a tool that generates C# or some other language for de-serialization of the XML, or if you use the approach of pre-atomization of XName objects, code that exactly matches the element or attribute name won’t be valid.
For convenience, here are links to the C#, VB.NET, and C++ references, so that it’s easy to validate that you are not using keywords:
Choose easily readable identifier names. For example, a property named HorizontalAlignment is more readable in English than AlignmentHorizontal. AdjustIndentation is more readable than IndentationAdjust.
Optimize for readability over brevity.
XML Namespaces
I put elements in namespaces, and don’t put attributes in namespaces. Elements need to be in namespaces for a variety of reasons. There are some tools that require namespaces.
But attributes are a different story. For one thing, for all practical purposes, attributes inherit the namespace of their element. You can’t access the attribute without accessing the element, and you can’t get to the element without using its namespace. The designers of XML had to allow for namespaces for attributes because there are some special purpose attributes that sometimes need to be added to elements in an existing vocabulary. The xml:space and xml:lang attributes are examples. By placing these in the special xml namespace, we avoid any possible collisions between names.
Another reason that attributes allow namespaces – I’ve written XSLT transforms where the first operation is to transform the XML into a new tree with new attributes on some elements. The purpose of these attributes is to aid further transforms. By creating these attributes in my own namespace, I can make sure that I avoid name collisions.
This is, I believe, why even if there is a default namespace for elements, attributes are always by default in no namespace.
Sometimes I use LINQ to XML trees as a means of passing more complicated configuration information into a method, or returning the results of a query into SQL or Open XML. In this case, I’m not really using LINQ to XML as XML, but as a hierarchical data store that is LINQ friendly. Of course, in this situation, using XML namespaces would be silly.
There are many more things to consider around designing XML vocabularies, such as when to use attributes vs. when to use child elements, avoiding magic values, etc. This is a much larger discussion, and could fill an entire book, I think.
Hi,
if you look at the configuration files coming with .NET (and other products shipping from Microsoft), they are all but a few using camelCasing.
In my oppinion it really depends on the usage, and as long as you’re consistent within the schema, i guess most developers should be able to read it.
Personally, I tend to use camelCasing in most of the cases because I feel I should align with the .NET framework configuration files. In the rare cases where the schema would suffer, I go with PascalCasing.
Hi Anders,
All good points – this post just details what I do. 🙂
But just have to say, if using the hyphenated lower-case style, it becomes much more messy to implement an XML to Object mapper.
-Eric
"One word that I have problems remembering how to capitalize is FileName. Some dictionaries don’t define it as a closed-form compound word (but some do). The .NET Framework guidelines capitalize it as FileName."
I grew up with DOS, so this is a no-brainer for me: it's Filename. In fact, if you go to your DOS prompt and type 'dir /?' you'll still see it written as "filename". It appears this is not limited to DOS either; if you enter "define filename" into Google you'll find that when used in a context dealing with computers, it's generally written as "filename".
@IObasetom Yeah, I have the same problem with that particular one. I still have to look it up.
|
https://blogs.msdn.microsoft.com/ericwhite/2009/08/12/xml-element-and-attribute-name-guidelines/
|
CC-MAIN-2017-09
|
refinedweb
| 1,490
| 63.7
|
Nubo is a command line program that allows you to start virtual machines on different cloud providers, also making sure you can SSH into those instances once they are available.
As an example, you might want to start a new node on Amazon EC2:
$ export NUBO_CLOUD=EC2_EU_WEST $ nubo start ami-27013f53 Instance i-4ea89004 available on EC2_EU_WEST. Public IP: 54.247.8.150
And then install puppet on it:
$ ssh root@54.247.8.150 "apt-get -y install puppet" Warning: Permanently added '54.247.8.150' (RSA) to the list of known hosts. Reading package lists... Building dependency tree... Reading state information... The following extra packages will be installed: [...]
One of the biggest challenges when deploying virtual machines on multiple clouds is ensuring you can actually access those machines after they have started up. For example, different cloud providers allow you to upload your SSH public key in different ways. Certain providers automatically configure firewall rules which by default deny traffic to your instances. If your deployments need to be automated, your infrastructure code has to deal with that.
nubo abstracts away these differences for you. It uses Apache Libcloud to start virtual machines on different cloud providers and Paramiko to establish SSH connections to the instances you start. Its functionalities are also available as a Python library.
Install nubo with one of the following commands:
$ pip install nubo
Alternatively, use easy_install:
$ easy_install nubo
You need to have ca-certificates installed on your system.
Invoke nubo without arguments to see the available functionalities:
$ nubo usage: nubo [-h] {config,clouds,list,images,start,reboot,delete} ... Start Virtual Machines on multiple clouds positional arguments: {config,clouds,list,images,start,reboot,delete} config set your cloud credentials clouds list available clouds list list running VMs images list available images start start a new VM reboot reboot a given VM delete delete a given VM optional arguments: -h, --help show this help message and exit
Run nubo config to set your cloud credentials. The following examples shows how we can configure one of the available cloud providers:
$ nubo config 1 DIGITAL_OCEAN 2 EC2_AP_NORTHEAST 3 EC2_AP_SOUTHEAST 4 EC2_AP_SOUTHEAST2 5 EC2_EU_WEST 6 EC2_US_EAST 7 EC2_US_WEST 8 EC2_US_WEST_OREGON 9 OPENNEBULA 10 RACKSPACE 11 RACKSPACE_UK Please choose the cloud provider you want to setup [1-11] 5 Please provide your API key: MYAPIKEY Please provide your API secret: MYAPISECRET EC2_EU_WEST cloud configured properly
To see which virtual machine images are available, we can use nubo images:
$ export NUBO_CLOUD=DIGITAL_OCEAN $ nubo images 20 images available on DIGITAL_OCEAN id name =============================== 85271 wheezy 85431 postgres-base 1607 Gentoo x64 13632 Open Suse 12.1 x32 13863 Open Suse 12.2 X64 18414 Arch Linux 2012-09 x64 23593 Arch Linux 2012-09 x64 63749 Gentoo 2013-1 x64 1601 CentOS 5.8 x64 1602 CentOS 5.8 x32 1609 Ubuntu 11.10 x32 Server 1611 CentOS 6.2 x64 1615 Fedora 16 x64 Server 1618 Fedora 16 x64 Desktop 2676 Ubuntu 12.04 x64 Server 12573 Debian 6.0 x64 12574 CentOS 6.3 x64 12575 Debian 6.0 x32 12578 CentOS 6.3 x32 14097 Ubuntu 10.04 x64 Server
New virtual machine instances can be started with nubo start. Note that the command will not return until the remote machine has finished booting up and it accepts SSH connections:
$ nubo start 12573 Instance 150843 available on DIGITAL_OCEAN. Public IP: 198.199.72.211
With nubo list we can see the status of our virtual machines on a given cloud provider:
$ nubo list 1 VMs running on DIGITAL_OCEAN id name state ip ======================================== 150843 test RUNNING 198.199.72.211
All nubo functionalities can be accessed via its Python API. Here is a brief example of how to deploy a new virtual machine:
from nubo.clouds.base import get_cloud Cloud = get_cloud('EC2_EU_WEST') ec2 = Cloud() print ec2.deploy(image_id='ami-27013f53', name='my-new-vm')
Please refer to the following API documentation for further details.
Support deployments on multiple cloud providers.
Return a class representing the given cloud provider.
Convert a node object into a dict
Bases: object
Deploy a VM instance on this cloud. This method is not implemented here, it has to be specialized by the classes implementing specific cloud providers.
Return True if the given node is running.
Return a list of VM images available on this cloud.
Return a list of dictionaries representing currently running nodes.
Return a list of strings representing the available instance size names.
Reboot the given instance id.
eg: reboot(‘i-bb6c3b88’) -> bool
Shutdown the given instance id.
eg: shutdown(‘i-bb6c3b88’) -> bool
Start a new instance.
Each cloud provider requires different values here.
‘name’, ‘image’, and ‘size’ are the lowest common denominator.
eg: startup(params) -> dict
Bases: nubo.clouds.base.BaseCloud
Digital Ocean needs the following information: VM size, image, name, location and SSH key id.
First, we check if our SSH key is already uploaded on Digital Ocean’s cloud. If not, we upload it using libcloud’s driver.ex_create_ssh_key. Then, we call self.startup with the required arguments.
Return uploaded key id if this SSH public key has been already submitted to Digital Ocean. We use libcloud’s driver.ex_list_ssh_keys in order to find it out.
Return None if the SSH key still has to be uploaded.
Bases: nubo.clouds.base.BaseCloud
Amazon EC2 needs the following information: VM size, image, name, location, SSH key name and security group name.
First, we check if our SSH key is already uploaded on Amazon’s cloud. If not, we upload it using libcloud’s driver.ex_import_keypair.
Then, we create a permissive Security Group with driver.ex_create_security_group and driver.ex_authorize_security_group_permissive.
Finally, we call self.startup with the required arguments.
Return uploaded key id if this SSH public key has been already submitted to Amazon EC2. We use libcloud’s driver.ex_describe_keypairs in order to find it out.
Return None if the SSH key still has to be uploaded.
Amazon also returns kernel-related info in driver.list_images. We do not care about kernels here, only about bootable VM images (AMIs).
First, we get the list of available AMIs. Then, we search for the user-specified keyword (if any).
Only 20 results are returned by default to avoid flooding users with too much output.
Bases: nubo.clouds.base.BaseCloud
Rackspace supports libcloud’s libcloud.compute.deployment.
Pass an SSHKeyDeployment to self.driver.deploy_node.
Bases: nubo.clouds.base.BaseCloud
|
https://pythonhosted.org/nubo/
|
CC-MAIN-2018-30
|
refinedweb
| 1,064
| 59.4
|
Do the following regarding files:
- Add global tag support: Same tags everywhere (i.e. not per-application tags)
- Add namespaces to tags. For example: "SMS", "Camera", etc. This way the apps that take photos could use the "Camera" namespace for their tags. They should also allow for tagging outside of their main namespace.
- Include a "System" namespace for tagging that would be used for core functionality.
- Implement file indexing by tag.
- Incorporate tag-based lookups in core libraries.
- Add support for tag editing (metadata editing?) in file manager.
After that:
- Extend the file-open dialog to lookup files by tag. For example, when opening the image viewer, we could search for all files with tags under the "Camera" namespace. A good solution would be to have a two-face "open file" dialog with a "folder view" and a "tag view".
- Make core applications/windows perform file lookups using tags. For example, when changing the background, the open file dialog could lookup for files with the System:Wallpaper tag.
Sample usage:
- Wallpapers (as explained above)
- Include all files under the "Music" namespace in music players, under the "Video" namespace in video players, etc.
- All programs with common-interests will be cooperating. The user just tags music and all music players automatically find them.
|
http://maemo.org/community/brainstorm/view/make_tag-based_file_management_an_integral_part/
|
crawl-003
|
refinedweb
| 212
| 60.01
|
In the GRT Modules are libraries containing a list of functions that are exported for use by code in other modules, scripts, or Workbench itself. Modules can be written in C++ or Python, but the data types used for arguments and the return value must be GRT types.
GRT modules are similar to Python modules, but are imported from
the built-in
grt module, instead of directly
from an external file. The list of modules loaded into the
grt module is obtained from
grt.modules. Modules can be imported in Python
using statements such as
from grt.modules import
WbModel.
To export functions as a module from Python code, you must carry out the following steps:
The source file must be located in the user modules folder. This path is displayed in the Workbench Scripting Shell with the label Looking for user plugins in.... It is also possible to install the file using the main menu item , .
The source file name must have the extension
_grt.py; for example,
my_module_grt.py.
Some module metadata must be defined. This can be done using
the
DefineModule function from the wb
module:
from wb import * ModuleInfo = DefineModule(name='MyModule', author='Your Name', version='1.0')
Functions to be exported require their signature to be declared. This is achieved using the export decorator in the previously created ModuleInfo object:
@ModuleInfo.export(grt.INT, grt.STRING) def checkString(s): ...
For the
export statement, the return type
is listed first, followed by the input parameter types,
specified as GRT typenames. The following typenames can be
used:
grt.INT: An integer value. Also used
for boolean values.
grt.DOUBLE: A floating-point numeric
value.
grt.STRING: UTF-8 or ASCII string data.
grt.DICT: A key/value dictionary item.
Keys must be strings.
grt.LIST: A list of other values. It is
possible to specify the type of the contents as a tuple in
the form
(grt.LIST,
<type-or-class>). For example, (grt.LIST,
grt.STRING) for a list of strings. For a list of table
objects, the following would be specified:
(grt.LIST, grt.classes.db_table).
grt.OBJECT: An instance of a GRT object
or a GRT class object, from
grt.classes.
Note that these types are defined in the
grt module, which must be imported before
they can be used.
The following code snippet illustrates declaring a module that exports a single function:
from wb import * import grt ModuleInfo = DefineModule(name='MyModule', author="your name", version='1.0') @ModuleInfo.export(grt.DOUBLE, grt.STRING, (grt.LIST, grt.DOUBLE)) def printListSum(message, doubleList): sum = 0 for d in doubleList: sum = sum + d print message, sum return sum
|
http://docs.oracle.com/cd/E17952_01/workbench-en/wb-modules.html
|
CC-MAIN-2014-42
|
refinedweb
| 442
| 59.3
|
tan, tanf, tanl − tangent function
#include <math.h>
double
tan(double x);
float tanf(float x);
long double tanl(long double x);
Link with −lm.
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
tanf(), tanl():
_BSD_SOURCE || _SVID_SOURCE ||
_XOPEN_SOURCE >= 600 || _ISOC99_SOURCE ||
_POSIX_C_SOURCE >= 200112L;
or cc -std=c99
The tan() function returns the tangent of x, where x is given in radians..
For an explanation of the terms used in this section, see attributes(7).tan(3), sin(3)
This page is part of release 3.53 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at−pages/.
|
http://man.linuxtool.net/centos7/u3/man/3_tan.html
|
CC-MAIN-2019-35
|
refinedweb
| 107
| 66.33
|
Recursively find first occurrence of a number in a list using Python
Recursion is a process where a function calls itself but with a base condition. A base condition is required in order to stop a function to call itself again.
In this tutorial, we will learn how to find the first occurrence of a number in a list recursively in Python. So, let’s get started.
Find the first occurrence of a number in a list recursively
First, we define a function check() that will take a list(n), index(i) and required number(j) as an argument.
def check(n,i,j):
Now, we will use if-else statements.
if(i==len(n)): return "Not Found" elif(j==n[i]): return i
If index i is equal to the length of the list(len(n)), that means we have traversed the list and j is not found. Therefore we return a string “Not Found”.
Else if j==n[i] i.e, if number to be found and element at ith index are equal. it means our number is found and returns the index i.
And if both the conditions are false, we return our function check() with list n, j, and next index i+1 so that it traverses the list from the next index.
else: return check(n,i+1,j)
This is how our code looks like.
def check(n,i,j): if(i==len(n)): return "Not Found" elif(j==n[i]): return i else: return check(n,i+1,j)
Finally, it’s time to call our function.
print("Your number found at index",check([1,2,3,2,5,6,6],0,2))
print("Your number found at index",check([1,2,3,2,5,6,6],0,4))
print("Your number found at index",check([1,2,3,2,5,6,6],0,6))
The output of our program will be like you can see below:
Your number found at index 1 Your number found at index Not Found Your number found at index 5
Also, learn:
|
https://www.codespeedy.com/recursively-find-first-occurrence-of-a-number-in-a-list-using-python/
|
CC-MAIN-2020-45
|
refinedweb
| 345
| 69.82
|
TypeScript - Understanding TypeScript
By Peter Vogel | January 2015#.
The question then remains, “Would you rather write your client-side code in this language or in JavaScript?”
TypeScript Is Data-Typed
TypeScript doesn’t have many built-in data types you can use to declare variables—just string, number and Boolean. Those three types are a subtype of the any type (which you can also use when declaring variables). You can set or test variables declared with those four types against the types null or undefined. You can also declare methods as void, indicating they don’t return a value.
This example declares a variable as string:
You can extend this simple type system with enumerated values and four kinds of object types: interfaces, classes, arrays and functions. For example, the following code defines an interface (one kind of object type) with the name ICustomerShort. The interface includes two members: a property called Id and a method called CalculateDiscount:
As in C#, you can use interfaces when declaring variables and return types. This example declares the variable cs as type ICustomerShort:
You can also define object types as classes, which, unlike interfaces, can contain executable code. This example defines a class called CustomerShort with one property and one method:
Like more recent versions of C#, it’s not necessary to provide implementation code when defining a property. The simple declaration of the name and type is sufficient. Classes can implement one or more interfaces, as shown in Figure 1, which adds my ICustomerShort interface, with its property, to my CustomerShort class.
As Figure 1 shows, the syntax for implementing an interface is as simple in TypeScript as in C#. To implement the interface’s members you simply add members with the same name instead of tying the interface name to the relevant class’ members. In this example, I simply added Id and CalculateDiscount to the class to implement ICustomerShort. TypeScript also lets you use object type literals. This code sets the variable cst to an object literal containing one property and one method:
This example uses an object type to specify the return value of the UpdateStatus method:
Besides object types (class, interface, literal and array), you can also define function types that describe a function’s signature. The following code rewrites CalculateDiscount from my CustomerShort class to accept a single parameter called discountAmount:
That parameter is defined using a function type that accepts two parameters (one of string, one of boolean) and returns a number. If you’re a C# developer, you might find that the syntax looks much like a lambda expression.
A class that implements this interface would look something like Figure 2.
Like the recent versions of C#, TypeScript also infers the datatype of a variable from the value to which the variable is initialized. In this example, TypeScript will assume the variable myCust is of CustomerShort:
Like C#, you can declare variables using an interface and then set the variable to an object that implements that interface:
Finally, you can also use type parameters (which look suspiciously like generics in C#) to let the invoking code specify the data type to be used. This example lets the code that creates the class set the datatype of the Id property:
This code sets the datatype of the Id property to a string before using it:
To isolate classes, interfaces and other public members and avoid name collisions, you can declare these constructs inside modules much like C# namespaces. You’ll have to flag those items you want to make available to other modules with the export keyword. The module in Figure 3 exports two interfaces and a class.
To use the exported components, you can prefix the component name with the module name as in this example:
Or you can use the TypeScript import keyword to establish a shortcut to the module:
TypeScript Is Flexible About Data Typing
All this should look familiar if you’re a C# programmer, except perhaps the reversal of variable declarations (variable name first, data type second) and object literals. However, virtually all data typing in TypeScript is optional. The specification describes the data types as “annotations.” If you omit data types (and TypeScript doesn’t infer the data type), data types default to the any type.
TypeScript doesn’t require strict datatype matching, either. TypeScript uses what the specification calls “structural subtyping” to determine compatibility. This is similar to what’s often called “duck typing.” In TypeScript, two classes are considered identical if they have members with the same types. For example, here’s a CustomerShort class that implements an interface called ICustomerShort:
Here’s a class called CustomerDeviant that looks similar to my CustomerShort class:
Thanks to structural subtyping, I can use CustomerDevient with variables defined with my CustomerShort class or ICustomerShort interface. These examples use CustomerDeviant interchangeably with variables declared as CustomerShort or ICustomerShort:
This flexibility lets you assign TypeScript object literals to variables declared as classes or interfaces, provided they’re structurally compatible, as they are here:
This leads into TypeScript-specific features around apparent types, supertypes and subtypes leading to the general issue of assignability, which I’ll skip here. Those features would allow CustomerDeviant, for example, to have members that aren’t present in CustomerShort without causing my sample code to fail.
TypeScript Has Class
The TypeScript specification refers to the language as implementing “the class pattern [using] prototype chains to implement many variations on object-oriented inheritance mechanisms.” In practice, it means TypeScript isn’t only data-typed, but effectively object-oriented.
In the same way that a C# interface can inherit from a base interface, a TypeScript interface can extend another interface—even if that other interface is defined in a different module. This example extends the ICustomerShort interface to create a new interface called ICustomerLong:
The ICustomerLong interface will have two members: FullName and Id. In the merged interface, the members from the interface appear first. Therefore, my ICustomerLong interface is equivalent to this interface:
A class that implements ICustomerLong would need both properties:
Classes can extend other classes in the same way one interface can extend another. The class in Figure 4 extends CustomerShort and adds a new property to the definition. It uses explicit getters and setters to define the properties (although not in a particularly useful way).
class CustomerShort { Id: number; } class CustomerLong extends CustomerLong { private id: number; private fullName: string; get Id(): number { return this.id } set Id( value: number ) { this.id = value; } get FullName(): string { return this.fullName; } set FullName( value: string ) { this.fullName = value; } }
TypeScript enforces the best practice of accessing internal fields (like id and fullName) through a reference to the class (this). Classes can also have constructor functions that include a feature C# has just adopted: automatic definition of fields. The constructor function in a TypeScript class must be named constructor and its public parameters are automatically defined as properties and initialized from the values passed to them. In this example, the constructor accepts a single parameter called Company of type string:
Because the Company parameter is defined as public, the class also gets a public property called Company initialized from the value passed to the constructor. Thanks to that feature, the variable comp will be set to “PH&VIS,” as in this example:
Declaring a constructor’s parameter as private creates an internal property it can only be accessed from code inside members of the class through the keyword this. If the parameter isn’t declared as public or private, no property is generated.
Your class must have a constructor. As in C#, if you don’t provide one, one will be provided for you. If your class extends another class, any constructor you create must include a call to super. This calls the constructor on the class it’s extending. This example includes a constructor with a super call that provides parameters to the base class’ constructor:
TypeScript Inherits Differently
Again, this will all look familiar to you if you’re a C# programmer, except for some funny keywords (extends). But, again, extending a class or an interface isn’t quite the same thing as the inheritance mechanisms in C#. The TypeScript specification uses the usual terms for the class being extended (“base class”) and the class that extends it (“derived class”). However, the specification refers to a class’ “heritage specification,” for example, instead of using the word “inheritance.”
To begin with, TypeScript has fewer options than C# when it comes to defining base classes. You can’t declare the class or members as non-overrideable, abstract or virtual (though interfaces provide much of the functionality that a virtual base class provides).
There’s no way to prevent some members from not being inherited. A derived class inherits all members of the base class, including public and private members (all public members of the base class are overrideable while private members are not). To override a public member, simply define a member in the derived class with the same signature. While you can use the super keyword to access a public method from a derived class, you can’t access a property in the base class using super (though you can override the property).
TypeScript lets you augment an interface by simply declaring an interface with an identical name and new members. This lets you extend existing JavaScript code without creating a new named type. The example in Figure 5 defines the ICustomerMerge interface through two separate interface definitions and then implements the interface in a class.
Figure 5 The ICustomerMerge Interface Defined Through Two Interface Definitions
Classes can also extend other classes, but not interfaces. In TypeScript, interfaces can also extend classes, but only in a way that involves inheritance. When an interface extends a class, the interface includes all class members (public and private), but without the class’ implementations. In Figure 6, the ICustomer interface will have the private member id, public member Id and the public member MiddleName.
The ICustomer interface has a significant restriction—you can only use it with classes that extend the same class the interface extended (in this case, that’s the Customer class). TypeScript requires that you include private members in the interface to be inherited from the class that the interface extends, instead of being reimplemented in the derived class. A new class that uses the ICustomer interface would need, for example, to provide an implementation for MiddleName (because it’s only specified in the interface). The developer using ICustomer could choose to either inherit or override public methods from the Customer class, but wouldn’t be able to override the private id member.
This example shows a class (called NewCustomer) that implements the ICustomer interface and extends the Customer class as required. In this example, NewCustomer inherits the implementation of Id from Customer and provides an implementation for MiddleName:
This combination of interfaces, classes, implementation and extension provides a controlled way for classes you define to extend classes defined in other object models (for more details, check out section 7.3 of the language specification, “Interfaces Extending Classes”). Coupled with the ability of TypeScript to use information about other JavaScript libraries, it lets you write TypeScript code that works with the objects defined in those libraries.
TypeScript Knows About Your Libraries
Besides knowing about the classes and interfaces defined in your application, you can provide TypeScript with information about other object libraries. That’s handled through the TypeScript declare keyword. This creates what the specification calls “ambient declarations.” You many never have to use the declare keyword yourself because you can find definition files for most JavaScript libraries on the DefinitelyTyped site at definitelytyped.org. Through these definition files, TypeScript can effectively “read the documentation” about the libraries with which you need to work.
“Reading the documentation,” of course, means you get data-typed IntelliSense support and compile-time checking when using the objects that make up the library. It also lets TypeScript, under certain circumstances, infer the type of a variable from the context in which it’s used. Thanks to the lib.d.ts definition file included with TypeScript, TypeScript assumes the variable anchor is of type HTMLAnchorElement in the following code:
The definition file specifies that’s the result returned by the createElement method when the method is passed the string “a.” Knowing anchor is an HTMLAnchorElement means TypeScript knows the anchor variable will support, for example, the addEventListener method.
The TypeScript data type inference also works with parameter types. For example, the addEventListener method accepts two parameters. The second is a function in which addEventListener passes an object of type PointerEvent. TypeScript knows that and supports accessing the cancelBubble property of the PointerEvent class within the function:
In the same way that lib.d.ts provides information about the HTML DOM, the definition files for other JavaScript provide similar functionality. After adding the backbone.d.ts file to my project, for example, I can declare a class that extends the Backbone Model class and implements my own interface with code like this:
If you’re interested in details on how to use TypeScript with Backbone and Knockout, check out my Practical TypeScript columns at bit.ly/1BRh8NJ. In the new year, I’ll be looking at the details of using TypeScript with Angular.
There’s more to TypeScript than you see here. TypeScript version 1.3 is slated to include union datatypes (to support, for example, functions that return a list of specific types) and tuples. The TypeScript team is working with other teams applying data typing to JavaScript (Flow and Angular) to ensure TypeScript will work with as broad a range of JavaScript libraries as possible.
If you need to do something that JavaScript supports and TypeScript won’t let you do, you can always integrate your JavaScript code because TypeScript is a superset of JavaScript. So the question remains—which of these languages would you prefer to use to write your client-side code?
Peter Vogel is a principal with PH&V Information Services, specializing in Web development with expertise in SOA, client-side development and UI design. PH&V clients include the Canadian Imperial Bank of Commerce, Volvo and Microsoft. He also teaches and writes courses for Learning Tree International and writes the Practical .NET column for VisualStudioMagazine.com.
Thanks to the following Microsoft technical expert for reviewing this article: Ryan Cavanaugh
Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
|
https://msdn.microsoft.com/en-us/magazine/dn890374.aspx
|
CC-MAIN-2018-47
|
refinedweb
| 2,428
| 50.36
|
var-args and overloading
Amitav Chowdhury
Greenhorn
Posts: 10
Amitav Chowdhury
Greenhorn
Posts: 10
W. Joe Smith
Ranch Hand
Posts: 710
Amitav Chowdhury wrote:Following the same logic below code should not compile:
public class Overloading {
static void overload(Integer x){
System.out.println("Integer");
}
static void overload(Double d){
System.out.println("Double");
}
public static void main(String args[]) {
int i=1;
overload(1);
}
}
But it compiles fine giving the ouput "Integer". Any idea why the behaviors are different for var-args and auto boxing?
I suggest looking at this link here. It explains some basic rules of widening, boxing and var-args.
rushikesh sawant
Ranch Hand
Posts: 65
rushikesh sawant wrote:Wrappers are peers to each other. They cannot be converted from one type to other.
very correct!
All wrapper classes inherit from abstract class "Number" except for Boolean and Character.
A Double is a Number
An Integer is a Number
But Double is NOT an Integer
hope this helps!
|
https://coderanch.com/t/492394/certification/var-args-overloading
|
CC-MAIN-2016-44
|
refinedweb
| 162
| 57.98
|
.
Although Exchange 2013 continues to use DAGs and Windows Failover Clustering for Mailbox server role high availability and site resilience, site resilience is not the same in Exchange 2013. Site resilience is much better in Exchange 2013 because it has been operationally simplified. The underlying architectural changes that were made in Exchange 2013 have significant impact on site resilience configurations and their recovery aspects.
Exchange 2010 undoubtedly made achieving site resilience for the messaging service and data easier than any previous version of Exchange. By combining the native site resilience features in Exchange 2010 with proper planning, you were able to activate a second datacenter to serve a failed datacenter's clients. The process you perform to do this is referred to as a datacenter switchover. This is a well-documented and generally well-understood process, although it takes time to perform, and it requires human intervention in order to begin the process.
Anyone who has performed a datacenter switchover in Exchange 2010 will tell you that they are operationally complex. This is in part because in Exchange 2010, recovery of mailbox data (DAG) and client access (namespace) are tied together. This leads to other challenges for Exchange 2010 in certain scenarios:
But all of that aside, the biggest challenge with Exchange 2010 is that the namespace is a single point of failure. In Exchange 2010, the most significant single point of failure in the messaging system is the FQDN that you give to users because it tells the user where to go. Changing the IP address for that FQDN is not that easy because you have to change DNS and deal with DNS latency, which in some parts of the world is very bad. And you have name caches in browsers which are typically around 30 minutes or more that also have to be dealt with.
Significant changes have been made in Exchange 2013 that address the challenges with Exchange 2010 site resilience head on. With the namespace simplification, consolidation of server roles, removal of AD-sited-ness, separation of CAS array and DAG recovery, and load balancing changes, Exchange 2013 provides new site resilience options, such as the ability to use a single global namespace. In addition, for customers with more than two locations in which to deploy messaging service components, Exchange 2013 also provides the ability to configure the messaging service for automatic failover in response to failures that required manual intervention in Exchange 2010.
Specifically, site resilience has been operationally simplified in Exchange 2013. In addition, in Exchange 2013, the namespace does not need to move with the DAG. Exchange leverages fault tolerance built into the namespace through multiple IP addresses, load balancing (and if need be, the ability to take servers in and out of service). One of the most significant changes we made in Exchange 2013 was to leverage the clients’ ability to get more than one place to go. Assuming the client has the ability to use more than one place to go (which almost all HTTP clients do, and since almost all of the client access protocols in Exchange 2013 are HTTP based (Outlook, Outlook Anywhere, EAS, EWS, OWA, EAC, RPS, etc.), others to try to connect to. If a client tries one and it fails, it waits around 20 seconds and then tries the next one in the list. Thus, if you lose the VIP for the CAS array, and you have a second VIP for a second CAS array, recovery for the clients happens automatically, and in about 21 seconds.
Modern HTTP clients (operating systems and Web browsers that are ten years old or less) simply work with this redundancy automatically. The HTTP stack can accept multiple IP addresses for an FQDN, and if the first IP it tries fails hard (e.g., cannot connect), it will try the next IP in the list. In a soft failure (connect lost after session established, perhaps due to an intermittent failure in the service where, for example, a device is dropping packets and needs to be taken out of service), the user might need to refresh their browser.
So what does it mean that site resilience has been operationally simplified in Exchange 2013? Going back to the failure scenarios discussed above for Exchange 2010, if you encounter those scenarios in Exchange 2013, depending on your site resilience configuration, you might not need to perform a datacenter switchover. With the proper configuration, failover will happen at the client level and clients will be automatically redirected to a second datacenter that has operating Client Access servers, and those operating Client Access servers will proxy the communication back to the user’s Mailbox server, which remains unaffected by the outage (because you don’t do a switchover). Instead of working to recover service, the service recovers itself and you can focus on fixing the core issue (e.g., replacing the failed load balancer). Any administrator will tell you that the stress involved with replacing a failed piece of equipment that isn’t blocking service is much lower than the stress involved in restoring service and data access via a datacenter switchover.
So by comparison, in Exchange 2010, if you lose the load balancer in your primary datacenter and you don’t have another one in that site, you had to do a datacenter switchover. In Exchange 2013, if you lose the load balancer in your primary site, you simply turn it off (or maybe turn off the VIP) and repair/replace it.
Clients that aren’t already using the VIP in the secondary datacenter will automatically failover is not spent either. In Exchange 2010, you had to deal with DNS latency (hence, the recommendation to set the TTL to 5 min, and the introduction of the Failback URL). In Exchange 2013, you don’t need to do that because you get fast failover (~21 seconds) of the namespace between VIPs (datacenters).
Since you can failover the namespace between datacenters now, all that is needed to achieve a datacenter failover is a mechanism for failover of the Mailbox. The key is that third location is isolated from network failures that affect the first and/or second location (the locations containing the DAG members).
In this scenario, the administrator’s efforts are geared toward simply fixing the problem, and not spent restoring service. You simply fix the thing that failed; all the admin.
You can allow failover to occur without having to perform switchbacks (sometimes mistakenly referred to as failbacks). If you lose CAS in your primary datacenter and that results in a 20 second interruption for clients, you might not even care about failing back. At this point, your primary concern would be fixing the core issue (e.g., replacing the failed load balancer). Once that is back online and functioning, some clients will start using it, while others might remain operational through the second datacenter.
Exchange 2013 also provides functionality that enables administrators to deal with intermittent failures. An intermittent failure is where, for example, the initial TCP connection can be made, but nothing happens afterwards. An intermittent failure requires some sort of extra administrative action to be taken because it might be the result of a replacement device being put into service. While this repair process is happening, the device might be powered on and accepting some requests, but not really ready to service clients until the necessary configuration steps are performed. In this scenario, the administrator can perform a namespace switchover by simply removing the VIP for the device being replaced from DNS. Then during that service period, no clients will be trying to connect to it. Once the replacement process has completed, the administrator can add the VIP back to DNS and clients will eventually start using it.
Microsoft Exchange Server 2013 continues to innovate in the areas of storage, high availability, and site resilience, with its plethora of new, innovative features, such as:
It’s important to understand that major architectural changes had to take place in Exchange 2013 in order to enable these features. That means that while the Exchange 2010 design guidelines can apply to an Exchange 2013 organization, the additional enhanced Exchange 2013 design guidelines cannot be applied to Exchange 2010. All of the goodness above around new behaviors and design options applies to Exchange 2013 only.
Great post! Well explained
beautiful series
Awesome ! Thanks, Scott.
|
http://blogs.technet.com/b/scottschnoll/archive/2012/11/01/storage-high-availability-and-site-resilience-in-exchange-server-2013-part-3.aspx
|
CC-MAIN-2014-41
|
refinedweb
| 1,398
| 56.18
|
Good Day I need your Help!!! I have a problem on ionic 1 and I encountered a problem, I’m using codeigniter for my backend and when I post data it returns forbidden on my app I don’t know what to do I also added app transport security in Xcode, but yet still not working. Source: AngularJS
Category: https
Failed to connect socket using https in nodejs
While developing a chat application using nodejs,angular i am trying to connect with socket with the help of namespace using http , it was perfectly working.While i am running the same application with https, it was not connecting to socket code. server require(‘./libs/socketioCode.js’).sockets(https); var options = { key: fs.readFileSync(‘privkey.pem’), cert: fs.readFileSync(‘cert.pem’) }; var server = http.createServer(app).listen(3000); var server1 = https.createServer(options, app).listen(3443); var io = require(‘socket.io’).listen(server1); socket module.exports.sockets = function(https){ io = socketio.listen(https); I tried this […]
AngularJS $http request issue in HTTP and HTTPS
I have a problem in my angularjs $http request. When I send request to the API it was blocked by the browser like: ERROR IN FIREFOX : Blocked loading mixed active content “” ERROR IN CHROME: Mixed Content: The page at ‘‘ was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ‘‘. This request has been blocked; the content must be served over HTTPS. How can I fixed this problem? Any idea is accepted. […]
Recent Comments
|
https://angularquestions.com/category/https/
|
CC-MAIN-2018-09
|
refinedweb
| 245
| 57.98
|
0
Hi i've been set this assignment to design a Craps game for Java, i know this has been done lots before but i seem to be going round and round with this code....very frustrating!
This is the code i've written so far:
public class CrapsGame { public static void main(String[] args) { int die1 = (int) (Math.random()*6 + 1); int die2 = (int) (Math.random()*6 + 1); int dice = die1 + die2; System.out.println("You rolled " + dice); if (dice == 7 || dice == 11){ System.out.println("We have a winner"); } else if (dice == 2 || dice == 3 || dice == 12){ System.out.println("CRAPS!"); } else { System.out.println("Marker is "+dice); int die3 = (int) (Math.random()*6 + 1); int die4 = (int) (Math.random()*6 + 1); int dice2 = die3 + die4; while(dice2 != dice || dice2 != 7){ System.out.println("You rolled "+dice2); } } //Else } //Main } //Class
I'm very aware this isnt the finished article at all but any help would be greatly appreciated!
|
https://www.daniweb.com/programming/software-development/threads/313776/craps-game-help
|
CC-MAIN-2016-50
|
refinedweb
| 160
| 66.64
|
Hello, I have a problem with inheritance in Java classes.
I really need an expert who can communicate in plain english rather than technical language.
The extends keyword doesn't seem to be working.
I am in the process of creating a java program which stores details of songs from music cds. As you can probably guess I am practising using multiple classes and inheritance. The program so far consists of 3 classes; 1 introductory class called YourTracks, 1 Superclass called Tracks, 1 subclass called StoringTracks, I have used the "extends" keyword on the StoringTracks class. The code for these classes can be found via these links: The YourTracks java file compiles successfully into a class file no problem. However, for some reason, whenever I try to compile the Tracks and StoringTracks java files into class files (using Command Prompt) I get error messages, saying "cannot find symbol" as if nothing is being inherited from the superclass into the subclass. The computer does seem to find each file okay, it's only when I try to specify a package that it gives an error, so my computer must be configured to automatically look in the same directory. I cannot emphasise enough that I am still learning and I need an expert who can explain in plain english rather than technical language. I look forward to hearing from anyone who can help, Thank you, XXXXX XXXXX
Hello, thank you very much for your response - I've been waiting all day for someone to reply like you have!
I've tried your suggested adjustment, however now it's saying I've got to declare the textfield names as final because they're now accessed from within an inner class. That shouldn't be a problem though, I'm about to correct that.
However, I still need help with inheritance. Since I posted my question I tried the simplest way I could think of to practise inheritance (just declaring a text variable inside a superclass then trying to print it from a subclass and STILL it's saying variable not found.
Is there any reason the extends keyword wouldn't be working, or is my computer configured wrong?
I can't find anyone else on the internet having this problem.
I'd appreciate any help you can give,
Thank you
James
Thank you, XXXXX XXXXX sense. Now please can you tell me how to make the following variable name, cdtrackfield, final
Here is the line of code:
JTextField cdtrackfield = new JTextField("Number",5);
I need to do the same for all 4 text fields.
I know how to normally declare an integer or String variable as a final, but not the likes of JFrame components.
I've tried
"final JTextField cdtrackfield"
and
"JTextField final cdtrackfield"
but I keep on getting the response "identifier expected" and other frustrating error messages.
Any help would be greatly appreciated!
I know what you mean about the final keyword, I very rarely use it, only if I have to.
In this case, I was only using it because the names of the textfield objects I created were being used inside an inner class(the action listener's class) therefore when I tried to compile it I got an error message saying those varialbes (the textfield names) needed to be declared as final.
But since I wasn't going to use those textfields for anything else, just that one purpose I went ahead and tried it (I remember reading somewhere that you can make a reference to an object final, you just can't make the object itself final).
This seems to be working fine now, which is good, there's just one more thing I'd like to know which is related to my code.
If I wanted to add more buttons and consequently more actionlisteners to my second frame (the frame with the textfields),
how would I specify which button is for which actionlistener?
I would prefer not to use anonymous classes for each button.
Imagine I had 2 buttons in the Tracks class, just call them button1 and button2 activating method1 and method2 to keep it simple.
What would be the code for adding one actionlistener at a time
(you can just specify one of them, I'll follow that example.)
Sorry to bother you again, but this is the last thing I have a query on for now....
You've been great so far!
It's not a bother. This is what I do all day.
Insofar as I understand it, you'll need to add the action listener to each button independently, like so:
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
button1.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent event){
//method1() code goes here
}
});
button2.addActionListener(new ActionListener(){
//method2() code goes here
In both cases, your method is anonymous, although you should be able to call a method from an object created from a class (a handler) you declare elsewhere. If you go this route, I'd declare the handler class within the body of the class that is adding the item listener, then use it like this:
public class HandlerClass implements ActionListner {
private SomeClass localInstance;
public HandlerClass(SomeClass dummyInstance) {
localInstance = dummyInstance;
public void actionPerformed(ActionEvent e) {
// actual code for the handler goes here, using the lButton object, which represents the object instance that this is the handler for
} JButton button1 = new JButton("Button1");
button1.addActionListener(new SomeClass(nameOfInstanceToPassIn));
Forgive my formatting. Tight controls on this are hard here. I'll edit it later, if it gets too messy.
Thank you for your efforts, I've never used a "handler" before.
Please can you tell me what they are and how they are an advantage?
In simple terms if you can,
|
http://www.justanswer.com/computer-programming/7ge52-hello-problem-inheritance-java-classes-i.html
|
CC-MAIN-2015-48
|
refinedweb
| 960
| 58.72
|
RAIL_FrameType_t Struct Reference
Configures if there is a frame type in your frame and the lengths of each frame.
#include <
rail_types.h>
Configures if there is a frame type in your frame and the lengths of each frame.
The number of bits set in the mask determines the number of elements in frameLen. A maximum of 8 different frame types may be specified.
Definition at line
1208 of file
rail_types.h.
Field Documentation
◆ addressFilter
A bitmask that marks if each frame should have the address filter applied.
Frame type 0 corresponds to the least significant bit in addressFilter.
Definition at line
1237 of file
rail_types.h.
◆ frameLen
A pointer to an array of frame lengths for each frame type.
The length of this array should be equal to the number of frame types. The array that frameLen points to should not change location or be modified.
Definition at line
1214 of file
rail_types.h.
◆ isValid
A bitmask that marks if each frame is valid or should be filtered.
Frame type 0 corresponds to the lowest bit in isValid. If the frame is filtered, a RAIL_EVENT_RX_PACKET_ABORTED will be raised.
Definition at line
1232 of file
rail_types.h.
◆ mask
A bitmask of the frame type field, which determines a number of frames expected based on the number of bits set.
No more than 3 bits can be set in the mask and they must be contiguous ones. For example, if the highest three bits of the byte specified by offset constitute the frame type, then mask should be 0xE0, which has 3 bits set, indicating 8 possible frame types.
Definition at line
1226 of file
rail_types.h.
The documentation for this struct was generated from the following file:
- common/
rail_types.h
|
https://docs.silabs.com/rail/2.8/struct-r-a-i-l-frame-type-t
|
CC-MAIN-2020-34
|
refinedweb
| 289
| 66.33
|
I discussed the possibilities of CPU sampling and instrumentation data collection in the previous articles and now it is time to benchmark the application performance indicators that target the memory.
To test this feature out, I created another sample application. This time, it works with files and I tried to create a simulation of a memory-consuming process.
The setup
It is a simple C# Console Application with only one method – Main. All the code is executed inside that method and no calls to external libraries are made. Here is what it looks like:
using System;
using System.IO;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string[] fileList = Directory.GetFiles(@"D:\Temporary");
foreach (string file in fileList)
{
Console.WriteLine("Getting bytes for " + file + "...");
Console.WriteLine("Bytes for " + file + ": " + File.ReadAllBytes(file).Length);
}
Console.Read();
}
}
}
What this code does is it gets the file paths (given a specific source folder) and then reads the file contents for each file separately to a byte array. For large files, this process will allocate quite a bit of memory, so that is a perfect way to demonstrate the capacities of built in profiling tools when it comes to memory allocation benchmarking.
As you can see from the code I am showing here, I am referencing a path that points to a folder called Temporary. To test it out, I copied a set of small and not so small files over there (a bunch of large texture files and a movie). And that is pretty much everything that is needed to simulate intensive memory consumption.
Trying it out – getting and analyzing the results
To start the process, go to Analyze > Launch Performance Wizard and select .NET Memory Allocation (Sampling):
I am going to use the default sampling settings, so I am not changing any values in the wizard. Once the process starts, the application will run and might slow down your computer, if very large files are processed.
Once done, let’s take a look at the results. As with the previous methods, there is a graph that shows the CPU load during the execution.
There CPU is pretty loaded for a process like I started and there are some critical spikes as well. But this is not the metric I am looking for.
Functions Allocating Most Memory
The first indicator that interests us for this profiling session. The only thing about it is that it is a bit biased. The ReadAllBytes method of course consumes a lot of memory, but not 100%. So why is the percentage so high then? Due to the fact that it got to read a large file, it consumed so much memory that other method calls are considered insignificant memory-wise. To demonstrate this fact, I am going to delete the large file from the folder and run the profiling process again. Here is what I got after all:
This looks more realistic - although the amounts are really insignificant, those aren’t really equal to zero.
If you click on one of the methods, you will be able to review the data in a more detailed view.
First of all, you are able to see directly in the code snippet the amount of memory allocated for specific calls. The most expensive call is highlighted in red. Now change the view to Inclusive Allocations:
Now the code is highlighted a bit differently, in addition highlighting two additional lines:
Based on the sampling frequency, the call that requested the biggest amount of allocations is highlighted in red, the next one (by the next biggest number of allocations) is highlighted in bright yellow and the third one (also with one of the biggest number of allocations) is highlighted with a lighter shade of yellow. This is an effective way to visually understand what parts of the code might require optimization.
Types With Most Memory Allocated
This indicator represents the data types that used the most of allocated memory for this session. Let’s take a look at what this indicator looks like for the sample application (with the large file present in the testing folder at the time of profiling):
Obviously the byte array is allocating the most of possible memory used by the application, since that’s what I am using to store the file contents. But same as with the previous indicator, the data here doesn’t really correspond to reality. Other data types do allocate specific amounts of memory, and if I run the application while skipping the large file, here is what I get:
Although very small, the amounts of memory are once again different than zero. Sometimes this rounding can be inconvenient (when you need to know exactly the amounts of allocated memory), but for general cases it saves the developer from seeing values like 0.0001 (considering the proportions given by other data types).
However, even given that the values shown could be 0.00, the developer is still able to review the actual values, no matter how small those are. To do this, click on a listed type.
The table that shows up describes in detail the number of exclusive and inclusive allocations (and bytes) for each data type, even for those that weren’t in the initial list. For string (listed as 0.00% in the initial list) we can see that there were 17,802 inclusive (end exclusive) bytes.
NOTE: These values are the same because during a memory sampling, the values are generalized to a global sum of a type inside a single method - in my case, it was Main andI didn't have any external calls or assignments.
To compare, there are 780,715,158 bytes used by the byte array. In this case, the percentage for string would be 0.0022%. The reason for rounding the value to zero is clear here.
Types With Most Instances
If the previous indicator was based on the number of bytes, this one is based on the number of allocations. Let’s take a look at what’s recorded for the current session:
This indicator is standalone and doesn’t vary as to see visible modifications if I change the application running conditions. As an example of a method that generates multiple string instances that influence this indicator I can name Console.WriteLine.
Conclusion
Memory allocation should be carefully tracked because chances are, in larger projects there are parts in code that consume memory the wrong way, for example by storing too many instances of an object. Being able to find these issues as soon as possible will help you avoid issues connected to freezes and crashes later on, when the application will be used in a different environment.
Related Reading
Memory Management in .NET
Inspect and Optimize Your Program's Memory Usage with the .NET Profiler API
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/profiling-application-visual-1
|
CC-MAIN-2018-09
|
refinedweb
| 1,148
| 60.55
|
RECOMMENDED: If you have Windows errors then we strongly recommend that you download and run this (Windows) Repair Tool.
Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation.
Error In Bthprops Cpl. Aug 4,
JOptionPane (Java Platform SE 7 ) – Oracle Help Center – Creates an instance of JOptionPane to display a message with the specified message type, icon, and options. None of the options is initially selected.
Conditional logic in Java. Getting to grips with IF statements.
Is this static println function in out class from System namespace? namespace System { class out { static println. } How can I interpret this name? And where.
Unlike C++, Java gives error messages and helps you define what is wrong with your. Computer science can be difficult because many words look familiar but.
Apr 19, 2012. We can tell you what frequently encountered messages mean and how to fix them!. Errors typically appear as Java Error xxx or App Error xxx.
Looking for Java resources? Check out the Java Coffee Break directory! Top Ten Errors Java Programmers Make (How to spot them. How to fix/prevent them.)
What does the Java compiler error message "<identifier> expected" mean?. Java error: <identifier. What does a "Cannot find symbol" compilation error.
Sometimes, error messages can strike fear into the heart of even the bravest programmer. Fortunately some helpful, calming advice is here — advice to help you solve.
Jun 20, 2017. The “StringIndexOutOfBoundsException” Java software error message usually means the index is trying to access characters that aren't there.
Error Invoking Cfc Autosuggest This code works; <cfinput name= sfCname#counter# id= sfCname#counter# size= 40 autosuggest= cfc:400comps.tsijobads.getCompanies({cfautosuggestvalue. experts-exchange.com/questions/22900668/cf8-cfinput-spry-autos. db:: 3.47::Error Invoking CFC. but it's there! I see it! 81 autosuggest="cfc: art.lookupArt. (I think that this is an AJAX error) Error invoking CFC /Art.cfc : Not Found. Is it right that cfc's cant be found in
Now let’s show you an example of a client side error. By client side error we mean error within the web or mobile web. If the retailer is using lots of client side logic through Java Script then they need to pay attention to this metric.
Obfuscation is a term applied general to the protection of program code not general data. It has gained interest in recent years because computer programs written in newer languages such as Java. same exact message has a great deal.
With all of this in mind, let’s quickly check that you have the Java Development.
Try Okta to add social login, MFA, and OpenID Connect support to your Java. the general meaning of the exception and the situations in which it might occur. The.
What does this JDK error message means? Ask Question. (try to) decompile a Java program does NOT mean that there aren't closed-source Java programs: a).
Oct 3, 2012. A better way to define Java error codes. Consider these error codes:. private final int id; private final String msg; MyExceptionCodes(int id,
error messages : Java Glossary – mindprod.com – Canadian Mind Products Java & Internet Glossary : error messages
RECOMMENDED: Click here to fix Windows errors and improve system performance
|
http://visionsonore.net/java-error-message-meaning/
|
CC-MAIN-2018-13
|
refinedweb
| 547
| 60.82
|
On Sun, Oct 5, 2008 at 11:26 PM, Carl Johnson <carl at carlsensei.com> wrote: > I noticed something based on some code in the other thread, but it's not > really related to it. Is there a reason for this not working: > >>>> i = 0 >>>> def f(): > ... nonlocal i > ... i += 1 > ... return lambda: i > ... > SyntaxError: no binding for nonlocal 'i' found > > Versus: > >>>> i = 0 >>>> def f(): > ... global i > ... i += 1 > ... return lambda: i > ... >>>> > > This was probably already discussed at the time "nonlocal" was invented, but > is there a specific reason that "nonlocal" can't be used in cases where the > next scope out is the same as "global"? Because nonlocal is not global. The whole point of nonlocal is it falls between global and global. > I naively assumed that you could use > them almost interchangeably if you were at the top level of a module. > ("Almost" because "global" adds the variable to the module namespace if it's > not already there, whereas "nonlocal" doesn't blithely add variables to > other scopes, but just goes looking for existing ones.) Why force me to > switch to "global" when I cut and paste a function out of a class or > whatever and put it at the top level of my module? Is it just so that > TOOOWTDI? Or was it an oversight? Or is there some other reason? > You said it already: "cut and paste". Having nonlocal != global helps catch some potential bugs. Plus you just don't gain anything worth losing that assistance in finding coding errors by having nonlocal act like global. -Brett
|
https://mail.python.org/pipermail/python-ideas/2008-October/002154.html
|
CC-MAIN-2016-40
|
refinedweb
| 262
| 73.98
|
On Mon, 2004-04-26 at 09:51, Sylvain Wallez wrote:
> Bruno Dumon wrote:
>
> >On Sun, 2004-04-25 at 15:10, Sylvain Wallez wrote:
> >>Note that I'd like also that <wi:styling> could be written in the definition
also, as defining the styling in the widget definition can be a productivity boost with widget
repositories!
> >>
> >>
> >
> >Should be trivial to store this in the form definition.
> >
> >
>
> Yep. But this brings some namespace-related questions: "styling" is
> obviously in the instance namespace ("fi"), but if we introduce some
> "fi:" in the definition, what about "label"? The CForms machinery does
> nothing with it except copying it in the template output, so we may
> consider moving it also to the "fi" namespace.
+1
label has been put in the definition only because it was thought to be
convenient.
--
Bruno Dumon
Outerthought - Open Source, Java & XML Competence Support Center
bruno@outerthought.org bruno@apache.org
|
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200404.mbox/%3C1082969987.2642.12.camel@23.13%20%09yum.ot%20%09yum
|
CC-MAIN-2016-22
|
refinedweb
| 152
| 56.39
|
table of contents
NAME¶rcsfile - RCS file format
DESCRIPTION¶An RCS file's contents are described by the grammar below.
The text is free format: space, backspace, tab, newline, vertical tab, form feed, and carriage return (collectively, |phrase production ^L (formfeed). A further restriction (for all programs) is that the integrity value must not contain @. delta nodes form a tree. All nodes whose numbers consist indicates the default branch (or revision) for most RCS operations. If empty, the default branch is the highest branch on the trunk.
All delta nodes whose numbers consist of 2n fields (n≥2) (e.g., 3.1.1.1, 2.1.2.2, etc.) are linked as follows. All nodes whose first 2n-1 number fields are identical are linked through the next field in order of increasing numbers.point. / \ / \ / \ /
IDENTIFICATION¶Author: Walter F. Tichy.
Manual Page Revision: 5.9.4; Release Date: 2019-02-10.
SEE ALSO¶ci(1), co(1), ident(1), rcs(1), rcsclean(1), rcsdiff(1), rcsmerge(1), rlog(1)..
|
https://manpages.debian.org/buster/rcs/rcsfile.5.en.html
|
CC-MAIN-2021-49
|
refinedweb
| 169
| 68.87
|
HTTPService Request and Actionscript Issuesalice_data Oct 22, 2008 5:24 AM
Hi,:
This content has been marked as final. Show 13 replies
1. Re: HTTPService Request and Actionscript IssuesGregory Lafrance Oct 22, 2008 9:28 AM (in response to alice_data)Anytime you receive a result from an HTTPService you can process that result in the result event handler, and so in that handler you could put the returned data in an XMLListCollection, ArrayCollection, Array, Object, etc.
So without changing your HTTPService you could possibly make minor modifications to your result handler and be in a position to do what you desire.
2. Re: HTTPService Request and Actionscript Issuesalice_data Oct 22, 2008 9:40 AM (in response to Gregory Lafrance)Hi,
Now I think I am kind of confused, but I think I will try again here to explain further on what I tried to do.
Currently, whatever I have generated from this HTTPService is something like {simulation.lastResult.simulation.status} so that I can extract the value and have it output to the screen.
Say that I have two values to output on the screen from the HTTPService based on my previous post, {simulation.lastResult.simulation.status} and {simulation.lastResult.simulation.number} , and I want to say output a new value of {simulation.lastResult.simulation.status} - {simulation.lastResult.simulation.number} instead of having this processed in my PHP file as in the HTTPService, but in the Actionscript. What are the possible measures I have to take without using URLLoader()?
Thanks again for your help.
Alice
3. Re: HTTPService Request and Actionscript Issuesm_hartnett Oct 22, 2008 10:25 AM (in response to alice_data)You want to do as Greg stated. Your HTTPService request can define a result and fault method handlers such as:
<mx:HTTPService id="simulation"
url=""
useProxy="false"
showBusyCursor="true"
result="someResultFunctionName"
fault="someErrorFunctionName:
<mx:request
<market>{market.text}</market>
<pop>{pop.text}</pop>
<length>{length.text}</length>
</mx:request>
</mx:HTTPService>
The returned data is available in the result handler method. In this method you can manipulate the data anyway you would like. The result handler method gets executed automatically when the HTTPService call is completed and it is passed the data returned from the server.
For example, here is the call:
<mx:HTTPService
Here is the method that handles the result.
private function loginResultHandler(e:ResultEvent) : void {
your return data is in the variable e.result.
}
4. Re: HTTPService Request and Actionscript IssuesGregory Lafrance Oct 22, 2008 11:09 AM (in response to alice_data)Yeah, most of the time you want to use a result handler, not lastResult when processing your HTTPService results.
5. Re: HTTPService Request and Actionscript Issuesalice_data Oct 22, 2008 1:12 PM (in response to Gregory Lafrance)Thanks for the suggestions, guys. I have revised my code to do most of what I meant to do, except that I have a final step where I hope that the code would help me process some of the values without the help of the additional processing using PHP through HTTPService.
Right now the result refuses to calculate using the existing declared values I have using Actionscript. The other lines that are supposed to print out variables do get printed out, except for the one in the following that is being processed in the Actionscript snippet. Could anyone please help me with what I might have done wrong here?
Thanks for your help.
The code snippet is provided below:
6. Re: HTTPService Request and Actionscript IssuesGregory Lafrance Oct 22, 2008 1:25 PM (in response to alice_data)What is happening, an error?
Could it be that the data is being returned as strings and you need to do something like:
var remaining= int(total_buy)-int(total_sell);
7. Re: HTTPService Request and Actionscript Issuesalice_data Oct 22, 2008 1:43 PM (in response to Gregory Lafrance)Hi,
So you are suggesting that the syntax is accurate? I tried what you suggested, but it still did not give me anything.
To prove that the function is correctly called, the snippet <mx:Label is bringing back the accurate value.
However, I get no error messages even when I run the debug mode for what I have with what you have suggested, and therefore the place where it is supposed to have some number from <mx:Label gives a blank.
Could I be doing something wrong here?
Thanks for your help.
Alice
8. Re: HTTPService Request and Actionscript Issuesm_hartnett Oct 22, 2008 2:21 PM (in response to alice_data)I notice that you have a couple HTTPService calls defined here. One in MXML and one in actionscript. It looks like you are using the actionscript one to make the call. Is that correct?
In your result handler method, the 'remaining' variable is a local variable to the method. Do you want to define that variable at the object level so that your window can use the variable as well?
9. HTTPService Request and Actionscript Issuesalice_data Oct 22, 2008 6:46 PM (in response to m_hartnett)Hi,
I think what you said here about what I tried to do is accurate. I have some values I would like to extract from the httpservice request, and have them output to the page, plus some values I would like to additional manipulate using Actionscript processing to print them on the screen.
The remaining variable is one of them that I would like to process based on the values output from the HTTPService. I have modified my code so that it processes the function declaration from the Actionscript, <mx:Button, but now I get errors near the labels where I intend to display the variables I have declared, such as total_buy, and I get this error message at the following line:
<mx:Label
1120: Access of undefined property total_buy
Have I done something wrong here?
Thanks for your help.
Alice
10. Re: HTTPService Request and Actionscript Issuesm_hartnett Oct 23, 2008 5:48 AM (in response to alice_data)So when you execute this code you are calling simulation.send(parameters) (the MXML version) and never executing useHttpService? In that case you could eliminate the actionscript code. Either call would be fine. However I notice that you are binding the MXML url to the service.destination (url="{service.destination}") so if you get rid of the actionscript code you need to make sure the MXML url is set to. However executing either method would be fine.
The httpResult method will receive the data from PHP. The form of the data should be in XML because the resultFormat of the MXML service call is set to that. However your resultFormat can return other types than XML. Take a look at the api doc for the HTTPService.
Once that service returns it executes your method
public function httpResult(event:ResultEvent):void {
var result:Object = event.result;
var total_buy= event.result.root.total_buy;
var total_sell=event.result.root.total_sell;
var remaining= total_buy-total_sell;
}
This method looks fine and if you are correctly getting the values for the total_buy and total_sell then you know that the data is comming back from PHP fine. If you are trying to bind the 'remaining' variable to some field, it is defined as a local variable to this method and will not be bindable to something outside this method. You should either make the remaining variable and instance variable or set the text item directly like textRemaining.text = total_buy-total_sell.
<mx:Label
The last possible issue I see here is that the variables dont specify a type. Change them to (give them an int type)
var total_buy:int= event.result.root.total_buy;
var total_sell:int=event.result.root.total_sell;
var remaining:int= total_buy-total_sell;
11. Re: HTTPService Request and Actionscript Issuesalice_data Oct 23, 2008 6:03 AM (in response to m_hartnett)Hi,
Thanks for the explanations. I have changed the submit process to <mx:Button, and removed the entire Actionscript portion for useHTTPService().
What astounds me is that even when I did define the three variables and attempted to have the result give me the output of remaining variable, it never did. I don't get any errors from type errors at the moment after putting in the type of each variable with your fixings. Your reply shows that I should treat the remaining variable as its own by defining it as text, but I get an error that says Access of undefined property when I tried to do this.
I hope I am getting closer to getting the remaining variable output to the screen. Everything else is working at the moment.
Thanks again for your help.
Alice
12. Re: HTTPService Request and Actionscript Issuesm_hartnett Oct 23, 2008 6:55 AM (in response to alice_data)Try this example. It uses a XML file from my site as the source data and does not use PHP for any processing but it gives the basics.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
//define your variables at instance level and make sure they are bindable
[Bindable]private var totalBuy:int = 0;
[Bindable]private var totalSell:int=0;
[Bindable]private var remaining:int=0;
private function resultHandler(e:ResultEvent) : void {
//This returns XML data your data may be different.
//You will see that it is XML returned. Your code will change here
//depending on what is being returned.
var xmlLst : XMLList = new XML(e.result).children();
Alert.show(xmlLst.toXMLString(),"Return Values");
totalBuy = xmlLst[0];
totalSell = xmlLst[1];
remaining = totalBuy - totalSell;
}
private function faultHandler(e:FaultEvent) : void {
Alert.show(e.message.toString(),"Error Occured");
}
private function runService() : void {
dataService.send();
}
]]>
</mx:Script>
<mx:HTTPService
<mx:Label
<mx:Label
<mx:Text
<mx:Text
<mx:Label
<mx:Text
<mx:Button
</mx:Application>
13. Re: HTTPService Request and Actionscript Issuesalice_data Oct 23, 2008 10:44 AM (in response to alice_data)Hi,
Thanks for the reply and the example. This really helped, and after slight modification of my original code, everything is now working.
Alice
|
https://forums.adobe.com/message/969816
|
CC-MAIN-2018-43
|
refinedweb
| 1,672
| 54.52
|
CRI-0 1.10 beta 1 released
We are happy to announce the 1.10 beta 1 release of CRI-O. This is the first version of CRI-O supporting kubernetes 1.10. It has support for the features added to the kubernetes CRI (Container Runtime Interface) in 1.10.
Notable features that were added are:
- Per pod pid namespace setting: This supports the feature in CRI where one can optionally enable pid namespace sharing for all the containers in a pod. This feature is gated by a kubelet flag.
- Container log reopen support: This CRI API allows kubelet to copy the container logs and then request CRI-O to reopen the log files so kubelet can manage the rotation and preservation of container logs.
- CRI stats API: We added support for the stats API in CRI. CRI-O still uses cadvisor by default but we encourage users to test this out.
Besides these, we added more tests and bugs and stability fixes.
CRI-O community has been growing healthily and we are now at 75 contributors and many users.
Please try out the new release and let us know of any issues.
|
https://medium.com/cri-o/cri-0-1-10-beta-1-released-fc28a898f593
|
CC-MAIN-2018-22
|
refinedweb
| 193
| 72.87
|
#include <RTOp_SparseSubVector.h>
Struct for a (sparse or dense) sub-vector.
The stride member
vec.value_stride may be positive (>0), negative (<0) or even zero (0). A negative stride
vec.value_stride < 0 allows a reverse traversal of the elements in
vec.values[]. A zero stride
vec.value_stride == 0 allows
If
vec.sub_nz == 0 then it is allowed for
vec.indices == NULL. If
vec.sub_dim > vec.sub_nz > 0 then
vec.indices != NULL must
The member
vec.local_offset is used to shift the values in
vec.indices[] to be in range of the local sub-vector. In other words:
1 <= vec.local_offset + vec.indices[vec.indices_stride*(k-1)] <= vec.sub_nz for k = 1...vec.sub_nz
The member
vec.value_stride may be positive (>0), negative (<0) or zero (0). However, the member
vec.indices_stride may be may be positive (>0) or negative (<0) but not zero (0). Allowing
vec.indices_stride == 0 would mean that a vector would have
vec.sub_nz nonzero elements with all the same value and all the same indexes and non-unique indices are not allowed. Allowing non-unique indexes would make some operations (e.g. dot product) very difficult to implement and therefore can not be allowed. A sparse vector where
vec.value_stride == 0 is one where all of the nonzeros have the value
vec.values[0]. If
vec.sub_nz == 0 for a sparse vector then it is allowed for
vec.values == NULL 118 of file RTOp_SparseSubVector.h.
Definition at line 120 of file RTOp_SparseSubVector.h.
Definition at line 122 of file RTOp_SparseSubVector.h.
Definition at line 124 of file RTOp_SparseSubVector.h.
Definition at line 126 of file RTOp_SparseSubVector.h.
Definition at line 128 of file RTOp_SparseSubVector.h.
Array (size min{|
indices_stride*sub_nz|,1} if not
NULL) for the indices of the nonzero elements in the vector (sparse vectors only)
Definition at line 133 of file RTOp_SparseSubVector.h.
Definition at line 135 of file RTOp_SparseSubVector.h.
Definition at line 137 of file RTOp_SparseSubVector.h.
Definition at line 139 of file RTOp_SparseSubVector.h.
|
http://trilinos.sandia.gov/packages/docs/r10.6/packages/moocho/browser/doc/html/structRTOp__SparseSubVector.html
|
CC-MAIN-2014-35
|
refinedweb
| 333
| 54.69
|
The CSS and web font files to easily self-host the “Alex Brush” font. Please visit the main Fontsource monorepo to view more details on this package.
Fontsource assumes you are using a bundler, such as Webpack, to load in CSS. Solutions like CRA, Gatsby and Next.js are prebuilt examples that are compatible.
yarn add @fontsource/alex-brush // npm install @fontsource/alex-brush
Then within your app entry file or site component, import it in. For example in Gatsby, you could choose to import it into a layout template (
layout.js), page component (
index.js), or
gatsby-browser.js.
import "@fontsource/alex-brush" // Defaults to weight 400.
Fontsource allows you to select weights and even individual styles, allowing you to cut down on payload sizes to the last byte! Utilizing the CSS unicode-range selector, all language subsets are accounted for.
import "@fontsource/alex-brush/500.css" // Weight 500. import "@fontsource/alex-brush/900-italic.css" // Italic variant.
Alternatively, the same solutions could be imported via SCSS!
@import "~@fontsource/alex-brush/index.css"; // Weight 400. @import "~@fontsource/alex-brush/300-italic.css";
These examples may not reflect actual compatibility. Please refer below.
Supported variables:
[400]
[normal]
Finally, you can reference the font name in a CSS stylesheet, CSS Module, or CSS-in-JS.
body { font-family: "Alex Brush"; }
In the rare case you need to individually select a language subset and not utilize the CSS unicode-range selector, you may specify the import as follows. This is especially not recommended for languages, such as Japanese, with a large amount of characters.
import "@fontsource/alex-brush/latin-ext.css" // All weights with normal style included. import "@fontsource/alex-brush/cyrillic-ext-500.css" // Weight 500 with normal style. import "@fontsource/alex-brush/greek-900-normal.css" // Italic variant.
[latin,latin-ext].
Google Fonts License Attributions
Font version (provided by source):
v12.
Feel free to star and contribute new ideas to this repository that aim to improve the performance of font loading, as well as expanding the existing library we already have. Any suggestions or ideas can be voiced via an issue.
|
https://openbase.com/js/fontsource-alex-brush
|
CC-MAIN-2022-40
|
refinedweb
| 351
| 60.31
|
you have to manually change the wiper position, In case of digital potentiometer wiper position is set according to the signal given to potentiometer using any microcontroller or microprocessor.
FIG. MC41010 IC pinout
MC41010 is an 8 pin dual in line package IC. Just like any analog potentiometer this IC comes in 5k, 10k, 50k, and 100k. In this circuit 10k potentiometer is used
MC4131 have following 8 terminals:
Pin no. Pin Name Little description
1 CS This pin is used to select the slave or peripheral connected to arduino. If this is
Low then MC41010 is selected and if this is high then MC41010 is deselected.
2 SCLK Shared/Serial Clock, arduino gives clock for initialization of data transfer from
Arduino to IC and vice versa.
3 SDI/SDO Serial data is transferred between arduino and IC through this pin
4 VSS Ground terminal of arduino is connected to this pin of IC.
5 PA0 This is one terminal of the potentiometer.
6 PW0 This terminal is wiper terminal of the potentiometer( to change resistance)
7 PB0 This is another terminal of the potentiometer.
8 VCC Power to IC is given through this pin.
This IC contains only one potentiometer. Some IC have at most two potentiometer inbuilt. This
The value of the resistance between wiper and any other terminal is changed in 256 steps, from 0 to 255. Since we are using a 10k resistor value of resistor is changed in steps of:
10k/256= 39 ohms per step between 0 and 255
COMPONENTS
We need following components for this project.
1. ARDUINO
2. MC41010 IC
3. 220 OHM RESISTOR
4. LED
5. CONNECTING WIRES
Make connections as shown in fig.
1. Connect cs pin to digital pin 10.
2. Connect SCK pin to digital pin 13.
3. Connect SDI/SDO pin to digital pin 11.
4. VSS to ground pin of arduino
5. PA0 to 5v pin of arduino
6. PB0 to ground of arduino
7. PWO to analog pin A0 of arduino.
8. VCC to 5 v of arduino.
PROGRAM CODE 1
This code prints the voltage change across wiper terminal and ground on Serial Monitor of Arduino IDE.
#include <SPI.h>
int CS = 10 ; // initialising variable CS pin as pin 10 of arduino
int x ; // initialising variable x
float Voltage ; // initialising variable voltage
int I ; // this is the variable which changes in steps and hence changes resistance accordingly.
void setup()
{
pinMode (CS , OUTPUT) ; // initialising 10 pin as output pin
pinMode (A0, INPUT) ; // initialising pin A0 as input pin
SPI.begin() ; // this begins Serial peripheral interfece
Serial.begin(9600) ; // this begins serial communications between arduino and ic.
}
void loop()
{
for (int i = 0; i <= 255; i++)// this run loops from 0 to 255 step with 10 ms delay between each step
{
digitalPotWrite(i) ; // this writes level i to ic which determines resistance of ic
delay(10);
x = analogRead(A0) ; // read analog values from pin) ;
}
delay(500);
for (int i = 255; i >= 0; i--) // this run loops from 255 to 0 step with 10 ms delay between each step
{
digitalPotWrite(i) ;
delay(10) ;
x = analogRead);
}
}
int digitalPotWrite(int value) // this block is explained in coding section
{
digitalWrite(CS, LOW);
SPI.transfer(B00010001);
SPI.transfer(value);
digitalWrite(CS, HIGH);
EXPLAINING CODE 1:
To use digital potentiometer with arduino you need to include SPI library first which is provided in arduino IDE itself. Just call the library with this command:
#include <SPI.h>
In void setup, pins are assigned as output or input. And commands to begin SPI and serial communication between arduino and ic is also given which are:
SPI.begin(); and Serial.begin(9600);
In void loop, for loop is used to change the resistance of digital pot in total 256 steps. First from 0 to 255 and then again back to 0 with 10 milliseconds delay between each step:
for (int i = 0; i <= 255; i++) and for (int i = 255; i >= 0; i--)
digitalPotWrite(i) function writes theese value to change resistance at particular address of ic.
Resistance between wiper and end terminal can be calculated using these formulae:
R1= 10k*(256-level)/256 + Rw
And
R2= 10k*level/256 + Rw
Here R1= resistance between wiper and one terminal
R2= resistance between wiper and other terminal
Level = step at a particular instant ( variable “I” used in for loop)
Rw= resistance of wiper terminal ( can be found in datasheet of the ic )
Using digitalPotWrite() function the digital potentiometer chip is selected by assigning LOW voltage to CS pin. Now as the ic is selected, an address must be called on which data will be written. In the last portion of code :
SPI.transfer(B00010001);
Address is called which is B00010001 to select the wiper terminal of the ic on which data will be written. And hence for loop’s value i.e, i is written to change the resistance.
CIRCUIT WORKING:
As long as value of i keeps changing input to A0 pin of arduino also keeps changing between 0 and 1023. This happens because wiper terminal is directly connected to A0 pin, and other terminal of potentiometer are connected to 5volt and ground respectively. Now when resistance changes so do voltage across it which is directly taken by arduino as input and thus we get a voltage value on serial monitor for a particular value of resistance.
SIMULATION 1:
These are some simulation pictures for this circuit at various values of i:
Now just connect an led in series with 220ohm resistor to wiper terminal of IC as shown in figure.
CODE 2:
#include <SPI.h>
int CS = 10;
int x;
float Voltage;
int i;
void setup()
{
pinMode (CS , OUTPUT);
pinMode (A0, INPUT);
SPI.begin();// this begins Serial peripheral interfece
}
void loop()
{
for (int i = 0; i <= 255; i++)// this run loops from 0 to 255 step with 10 ms delay between each step
{
digitalPotWrite(i);// this writes level i to ic which determines resistance of ic
delay(10);
}
delay(500);
for (int i = 255; i >= 0; i--)// this run loops from 255 to 0 step with 10 ms delay between each step
{
digitalPotWrite(i);
delay(10);
}
}
int digitalPotWrite(int value)// this block is explained in coding section
{
digitalWrite(CS, LOW);
SPI.transfer(B00010001);
SPI.transfer(value);
digitalWrite(CS, HIGH);
}
EXPLAINING CODE 2:
This code is similar to code 1 except that there are no serial commands in this code. So no values will be printed on serial monitor.
WORKING EXPLANATION
Since led is connected between wiper terminal and ground as resistance changes so do voltage across led. And hence as resistance across which led is connected rises from 0ohm to maximum so do brightness of led. Which again slowly fade away due to decrease in resistance from maximum to 0v.
Simulation2
Simulation3
sir is there any ic or cheap circuit which has clock timing features.that thing should have following features.. uninterrupted timing system like watch am pm everything, programmable one or more output which give signal at perfect predefined tym by me .
i dont want ic like 555timer i want timing circuit like watch clock.
i hope u got it what i want.
Gurmel, you can use IC 4060 and configure it with a crystal, that will enable the IC to oscillate with precise clocks.
|
https://www.homemade-circuits.com/using-digital-potentiometer-mcp41xx-with-arduino/
|
CC-MAIN-2019-35
|
refinedweb
| 1,212
| 61.26
|
PHP 7.
Trailing commas in function calls are specifically useful for variadic functions:
// unset( $one, $two, $three, ); return view('posts.show', compact( 'post', 'author', 'comments', ));
Importantly, this change only affects call syntax, not function declaration! The following syntax is still illegal in PHP 7.3:
// Still illegal syntax public function __construct( $apiClient, array $options = [], ) { }
Trailing Commas in PHP Arrays
Using trailing (sometimes referred to as dangling) commas is nice and clean when you want to rearrange an array or append new values.
The trailing comma in PHP arrays has been legal forever (I am not sure when they were introduced) and might be your only exposure to trailing commas in PHP apart from making it legal in grouped namespaces since PHP 7.2.
One argument of why trailing commas are beneficial, and why some teams have been enforcing this code style in arrays, is cleaner diffs. When you want to append a new array item, when you add a comma to the last line to append another value, the diff now affects both lines:
// Before $points = [ 1, 5, 7 ]; // After $points = [ 1, 5, + 7, + 9 ];
With the trailing comma, only the appended line shows up in the diff, nice an clean!
// Ahh better $points = [ 1, 5, 7, + 9, ];
Trailing Commas in Other languages
JavaScript
Trailing commas in JavaScript array literals have been allowed since the beginning. Starting in ECMAScript 5, trailing commas in object literals are legal, and in ECMAScript 2017 trailing commas in function parameter lists are legal:
var numbers = [ 1, 2, 3, ]; // ECMAScript 5 var stats = { rebounds: 9, fouls: 2, points: 15, }; // ECMAScript 2017 function track( eventName, eventValue, ) { // ... }
In JavaScript trailing commas are also allowed in destructuring assignments:
var { rebounds, points, assists, } = stats;
Ruby
Here’s an example of a trailing comma on a hash and an array:
ruby_hash = { first: '1st', second: '2nd', third: '3rd', } ruby_array = [ '1st', '2nd', '3rd', ]
Python
The Python examples look identical to ruby:
countries = [ 'China', 'India', 'Mexico', ]
An interesting tidbit, if you were to omit the trailing comma, and accidentally add another item to the array, here’s what the result would be:
countries = [ 'China', 'India' ] // Later you added a new item but forgot the comma countries = [ 'China', 'India' 'Mexico' ] // The result would be... ['China', 'IndiaMexico']
Haskell
Haskell is known for its style of the “trailing comma” called the “Haskell style”:
data Settings = -- The user settings { has_sound :: Bool , has_power :: Bool , has_graphics :: Bool , user_name :: String , user_password :: String , user_email :: Email , stylesheet :: Style }
The example comes from this StackOverflow answer; and no, I don’t know Haskell.
Because trailing commas can cause cross-browser issues in JavaScript, you might have seen a similar style to this in JavaScript as well:
var stats = { rebounds: 9 , fouls: 2 , points: 15 };
Learn More
You can learn all about the most prominent features coming to PHP 7.3 in our post announcing the PHP 7.3 Alpha 1 release last week. PHP 7.3 will hit General availability (GA) later this year!
Also, read through the RFC for allowing a trailing comma in function calls for full details on the proposal coming to PHP 7.3.
The author Sammy Kaye Powers did an excellent job conveying the proposal. If you read carefully, you can learn about how this RFC communicates the difference between this 7.3 proposal and a previously rejected 7.2 version. The 7.2 RFC vote combined both function calls and definitions in a single vote and was narrowly rejected.
Newsletter
Join the weekly newsletter and never miss out on new tips, tutorials, and more.
Laravel Breadcrumbs Package
Laravel Breadcrumbs is a package by Dave James Miller that makes adding breadcrumb navigation to your application (re…
Laravel JSON – A Simple Wrapper Around JSON for Catching Errors
When we wrote “PHP 7.3: A Look at JSON Error Handling,” Jan Östlund mentioned a package he wrote called L…
|
https://laravel-news.com/php-trailing-commas-functions
|
CC-MAIN-2019-04
|
refinedweb
| 639
| 52.43
|
Feedback
Getting Started
Discussions
Site operation discussions
Recent Posts
(new topic)
Departments
Courses
Research Papers
Design Docs
Quotations
Genealogical Diagrams
Archives
I just had this argument crystallize for me after a conversation with Manuel Simoni:
I'm realizing I'm pretty far-out liberal on Steve Yegge's spectrum of programmers, so I'd love to hear reactions from people here -- who seem to be from all over the spectrum.
I'd say this is pretty much what I have to say about object oriented programming... First it seems like you can code on a higher abstraction level, then you suddenly get struck by 120+ character identifier names claiming you have done some kind of type error with a parameter you have never heard of. Oh well, if you try the Boost library for C++ I guess you asked for it.
I've come to the conclusion that you shouldn't use object oriented programming, you should use object oriented thinking. Objects and classes will do fine when reasoning about stuff, but for actual implementation there are other stuff that are better at making things modular. Some languages actually call them "modules".
Don't twist this as an FP vs. OOP argument. C++ sucks on its own level with non-modular type checking, you can totally have modular type checking in a OOP language.
As for the OP, abstractions invariably leak, but we just have to deal with that. There is definitely a cost to reusing a library, and the benefit you gain from reuse should outweigh that cost; if it doesn't, don't use the library.
This is basically it -- the cited problem is with type-checking C++ templates. Lacking "concepts" or a similar mechanism, template errors are identified at the deepest possible level rather than the shallowest possible level. Taking that and turning it into a criticism of "libraries" is definitely a bridge too far.
Words like abstraction and reuse and cost/benefit have long led me astray.
Units of reuse aren't made in one big-bang moment. They evolve. You write code for one use case. Then maybe you find it works in another, and another. The organic process of reuse requires a lengthy gestation period. But our language and our libraries obscure this fact.
We imagine our job as programmers is to create abstractions. It is not. It is to understand the code surrounding us, that we interface with and use to create new things. Our job is to *understand* abstractions that have come before and proved themselves and maybe, occasionally, if we're very good and a little lucky, to create an abstraction that others will find useful. The conventional way we view libraries obscures this fact. It makes it seem like creating a unit of reuse is just a matter of running gcc/ar/ranlib. And so we're awash in libraries with prematurely ossified interfaces.
I still don't know what you are getting at, your thoughts are a bit too abstract. I think it might be related to Joel Spoleky's "Abstractions Leak" or the "Duct Tape Programmer" posts.
I'm mostly just working things out for myself, and looking for feedback on the process. What I have so far -- and what this post tried to summarize -- was that the world would be a better place if we all know a little bit more about our dependencies.
I think this is consistent with Joel Spolsky's posts. Part of the reason jwz is such a good programmer (and also part of Feynman's prowess) is this willingness to bounce between the two sides of abstraction boundaries. To truly understand that all abstractions leak is to be willing to learn about their internals, and if everyone did this we might even end up building less leaky abstractions rather than shackling ourselves to their leakier initial drafts.
I didn't have any twist in mind, I merely saw two cases that seemed to share a common type of problem: A promise of abstraction that bogs you with implementation details.
It might be C++ specific when it comes to OOP, though I'd say the problems are there for Python as well except the error messages are a bit easier to decrypt. Apart from that I don't have experience of other OO languages.
This reminds me of the approach to early rigorous mathematics education where you're not allowed use a theorem until you've proven it yourself. In areas where there are deep but fundamental theorems this can send you down some pretty long rabbit holes. With CS, the situation seems even worse -- isn't your OS just a library? If you can't use a modern filesystem without understanding how it's implemented, I foresee a low productivity future for you.
If a part of your codebase never kicks up an issue, it doesn't matter whether you understand it or not :) I tried to allude to pragmatic considerations when I said start with lowest-maturity/highest-risk.
---
And oh, guilty as charged, I'm pretty low-productivity. Productivity is over-rated.
The way I read this is that we should not become so dependent on our libraries that when they fail we cannot fix them. Libraries can fail due to licensing, bugs, inflexibility, or poor hierarchy. Understanding the internals increases our own ability to use the library, as well as increases the life of the library, should a maintainer go away, or an owner choose to no longer distribute it, etc.
With hindsight, perhaps the names I've used are confusing. Libraries aren't bad if you learn how they work. But in today's world they mostly seem to discourage poking inside them. We're more concerned with some speculative future issue like, "If I make a change how will I merge it upstream? I'll be maintaining my hack forever." Don't worry about that for now, just go understand how it works.
Thanks for working with my incompetence and taking the trouble to figure out what I meant :)
What I have discovered for what it's worth is that standard libraries are mostly excellent and third-party libraries mostly suck.
The distinction is mostly about maturity of design and implementation.
A library's maturity grows, IMO, with about the order of magnitude of the number of projects it's been used in and debugged relative to. The standard libraries of the language are used in tens of thousands to hundreds of thousands of programming projects -- possibly millions. So you get library maturity of, say, four, five or six. A third-party library, usually, has been used in hundreds or maybe thousands of projects -- maybe tens of thousands if it's something popular like boost. So you have maturity of, say, two or three, possibly four.
This is important, because level-one maturity is usually a first-cut design and often has categorical mistakes that make it impossible to do some broad categories of useful tasks. Level-one maturity usually also has unnecessarily complex interfaces, unnecessary or undocumented dependencies, portability or build problems, and lots and lots of bugs.
Usually around maturity level two or three, implementations whose designs are informed by the flaws and shortcomings of previous implementations become available, and these are better (simpler interfaces and no unnecessary or undocumented dependencies) but you'll be fighting with obsolete or misleading documentation, bugs in the new implementations, and sometimes significant incompatibilities between library versions. At level three or four, you'll still be looking at incompatibilities in different versions of the library, but by now they'll be minor, and the documentation will be catching up.
Once something has maturity level five or six, I expect it to be well designed, completely and usefully documented, consistently implemented, and don't expect to encounter any significant bugs in it. Mature libraries are a joy to work with - they save you tons of implementation effort and have already had (and fixed!) the mistakes you were going to make.
But most libraries, aside from the language runtime libraries specified by the standard, never reach that point.
Ray
I'd just add that maturity = #users * time.
I almost feel we need a different name for immature libraries (which are now the vast majority of all libraries). That allows users to set expectations about the level of churn in the interface, and frees up library writers to correct earlier missteps. I think the Go language did this well, and lots of other projects do think about gradually firming up interfaces. But many projects also stay on one side or other of that divide. My impression is that open-source C++/java projects have historically cared about compatibility too soon, and the rails eco-system cares about compatibility too little. 6 years in, fairly standard gems are still constantly in a state of flux.
Another side-effect of a new name for immature libraries: it would utterly invalidate the title of my article.
This is less important and more subjective, but I think we also need more attention to deprecation and deletion from mature libraries. Mature libraries tend to be great from a stability or performance perspective, but bad APIs do creep in. Libc and the java standard libraries and Common Lisp have lots of ugly warts that don't look like they'll ever be excised. (Is this just because they were prematurely ossified back in the day?)
My)).
So I'd replace (eq a b) in Common Lisp with something like (equal (addr a) (addr b)).
... and then people would just write
(defun (eq a b) (equal (addr a) (addr b)))
and mutter vaguely insulting questions about why you didn't provide it for them. And when enough of them had done so, people would say, "hey, look, there are dozens of definitions of this thing, it ought to be a standard item."
a) That isn't what actually happened. In reality eq came first, in an era more miserly of compute cycles.
b) It *could* happen for some features, but you don't know that for sure. Short-circuiting the gradually-clarifying need for something is a recipe for bloat.
c) If it *did* happen, I'd argue the system was working as designed. That's kind of my whole point: that things should prove themselves before we freeze them..
I think languages should provide opinionated defaults and empower users to change them if necessary. Wart lets you override the default equality comparison to simulate eq, or extend it to do so just for specific types or in specific scenarios.
Python's "eq" is the "is" operator. Ruby's "eq" is, confusingly, named "equal?". (I'm a fan of Baker's "egal" predicate, myself.)
I was corrected elsewhere as well.
I don't care directly about abstraction, but I do care to act in ways that will keep on giving. The pursuit of reuse leads me to abstract away any non-portable details, until mathematical argument and computation are some of the only dependencies left. That's why I end up programming.
Understanding one's dependencies is useful, but so is black-box modularity, i.e. designing a subsystem so that it's reusable across a wide range of possible interacting subsystems. This kind of design comes in handy as the developer communication cost and reengineering cost rise. Our current systems may not always give us perfect black-box modularity, but we probably use them because their cost is low enough to compete with the costs of the alternatives.
Personally, I'm concerned about how the communication cost and reengineering cost will rise once I'm no longer around to maintain what I've made. Source code documentation would make reengineering another option here, but not if the "I'm no longer around" is actually "I'm focused on another project and I'd rather not take a detour to redesign the language I'm building it on." So black-box modularity is important to me even on a solitary developer basis. :)
(Disclaimer: Kartik and I have debated this topic for quite a while now.)
It's been a while since we debated, but if I recall correctly we aren't really disagreeing, just focusing on different parts of the state space. I'm totally fine with black box modularity for mature libraries as long as we pay attention to the process of gestation, and don't treat all libraries as equally mature.
I'd also prefer to leave a little escape hatch for even seemingly-mature libraries -- just in case we find a better API or something :) But that should be covered by the usual deprecation best practices.
This is a specification and quality control problem. In computing, we have become used to an environment where library vendors are not held responsible for non-compliance with their own specifications. Libraries suck because they are allowed to suck.
There are exceptions, and they are not cheap. See the International Mathematical and Statistical Libraries (IMSL). Each mathematical subroutine comes with a signed statement by a mathematician about the accuracy and limitations of the subroutine.
Many years ago, during the heyday of Ada, I ordered an Ada compiler, with an purchase order specifying a validated Ada compiler. The product showed up with a sheet of paper saying that the compiler did not pass validation and a validated version would follow. I was at an aerospace company at the time, and simply turned the package over to incoming quality control. The package was marked with a large red tag - REJECTED by Incoming Inspection - Does Not Conform To Specification. The vendor had to refund $40,000, was put on quality watch by purchasing, and a competing product was procured.
Aerospace still has that attitude. If A won't properly interoperate with B, you check the spec to see who's wrong. The non-compliant vendor gets a reject and has to fix their side. If the spec isn't specific enough to decide who's wrong, the spec is defective. This is why you can unbolt a Pratt and Whitney engine off a jetliner, bolt on a Rolls-Royce engine, and go fly.
Part of the problem is what I refer to, for want of a better symbol, as the tragedy of the commons. To some extent such tragedies are unavoidable in society. The trajectory of bureaucracies made such patterns hard to see -- you had to watch them closely over decades. Software is great because we can see dysfunction laid out over a period of months. Since the problems are easier to spot, I tend to be optimistic that we'll be able to do better with free software. You get a lot from free software in exchange for a certain amount of "doesn't validate completely against spec." I just think we don't squeeze out all the benefit we could because of these mental shackles, these imaginary constraints on the changes we can make.
Programmers manage abstraction boundaries, that's our stock in trade. Managing them requires bouncing around on both sides of them. If you restrict yourself to one side of an abstraction, you're limiting your growth as a programmer[1].
Don't manage labor; eliminate it.
You are not describing abstraction boundaries, you are describing technical contradictions, and programmers who find solutions to such contradictions are not merely programmers but society changers. Solving a technical contradiction requires innovation. Frequently, those who solve the puzzle don't waste time bouncing around from one contradiction to the opposing contradiction. Rather, they see something nobody has seen before, and they design and code it.
Well there's something to be said for looking at both sides of an abstraction during development (if that were never necessary then we'd never write any functions in the first place).
But I think that maybe what you're saying here is that, when a software problem is found, we shouldn't have to pierce multiple layers of abstraction to find it, but rather the bug should manifest as a specification error (and if bugs are otherwise possible, it's a failure of the specification that should have excluded such a possibility).
If that's what you're getting at, I agree completely. Programs should be correct by construction.
If that were to become true then yes, my entire point might be moot. Can you point me to any papers on 'correct by construction'?
I'm not sure why you use the qualifier 'during development'. Do you mean during development of the abstraction? I'm pushing for 'always'. Or 'during any development I do'.
My post was deliberately agnostic of language or platform. But I suppose I don't know much about the life of say a Haskell programmer.
So much as a bad process. But another saying besides my credo, "Don't manage labor; eliminate it", is also "One fact, one place, one time". Things work best if a specification is the single point of change.
Consider manually writing DAOs, DTOs, manually ferrying the data to domain objects, manually encoding visitors, manually doing change tracking, etc. There's a lot of points of failure in such a process.
Suppose an underlying field changes, or the order of serialization changes. How do you permanently avoid such issues? Such synchronicity issues in code can be handled through macro-expressivity or a custom DSL equivalent to a macro, and many additional safe ways, although one would ideally subsume all others.
It's a theory of organizations, which can be automated by computers acting on behalf of humans.
Don't repeat yourself, then?
I've definitely had some success, in the working world, formalizing hairy problems enough that the repetitive error-prone parts are mechanically derived from a formal spec, as you say.
Kartik's article misses the real problem, entanglement, which happens when choice of abstraction is tightly coupled to a particular implementation. This problem is common due to import by name (cf. modularity without a name and ban on imports). The same problems are experienced - e.g. with respect to failure modes, and monolithic dependencies - whether we import libraries by name or bind specific services by URLs.
The surface of any service involves many abstractions: authorities and responsibilities, roles and contracts, protocols and workflows, APIs and data schemas. The same can be said of the surface of a library, excepting that many PLs are poor for expressing the full range of service abstractions - cannot effectively address instancing, sessions, concurrency, maintenance, auditing, authority, persistence, extension, resource management. A consequence of this weak expressiveness of PLs is that many libraries become monolithic frameworks that Greenspun a fair portion of a PL themselves and require an awful lot of boiler-plate to integrate.
I've long advocated that PLs should better address decomposition of apps into services and composition of services into apps. If your PL does not effectively address services-as-libraries, then "libraries suck" is a property of your PL.
Once you accept service-based decomposition as part of a PL design, we can address important questions such as "good" models and modularizations of services - expressing and enforcing service-level abstractions; controlling binding and entanglement; addressing concerns of security, safety, extensibility, upgrade, concurrency, auditing, distribution, persistence, partial-failure, resilience, etc.
... is not imports or names. Import polymorphism is a real problem, as Gilad discussed. But imports are fine just so long as you remember they are only for interaction with people (to aid with binding resolution). Imports are fuzzy. Imports should be dev time.
Yes, this is something I learned when I did Jiazzi. That the external configuration of imports in units/modules/components wasn't really that great of a feature, that all the use cases for configuration connections were either contrived or I was abusing the system to do something else that wasn't really related to modules (open classes).
Specific use-cases can reveal meany problems. But they are a biased lens. Many systemic problems cannot be observed through use-cases, especially when those use-cases are influenced by or described in terms of integration with an existing system. Issues such as software reuse, reconfiguration, and securable composition are unlikely to be observed in use-cases for any particular project. And yet there is great value in addressing them.
Wonderful, but I'm commenting on today's world. If you simply make module import from Java-like languages externally configurable, you aren't doing much because imports are almost always made with specific implementations in mind. If we are talking about alternatives to type parameters, then ya, there is a use case we can address with external linking. But the two concepts are very different.
Even if we use imports "only for interaction with people", that's enough to lead developers straight to dependency hell.
An individual has the time and energy to directly maintain a number of relationships that is relatively small compared to the population as a whole. In a group of N people, there are N^2 potential communication relationships. That simple law is why we need hierarchies and bureaucracies. And it has a significant impact on modular organization of software.
Relationships with people are subject to variations over time and space, shifting in response to markets, resources, and requirements. If the number of relationships is small, we could perhaps maintain all these relationships concretely, by hand at dev-time. But, in general, we must specify policies and roles and manage relationships and "interactions with people" - including imports - automatically.
If you don't handle it in the PL, you'll end up hacking it (horribly) with tools like autoconf, cpp, and cmake.
David, if I understand correctly, you're saying that hierarchies arise to organize a certain kind of decision so that large numbers of people are in sync and can work together.
Another possible solution: the population converges on using a specific solution over time. It requires individuals to be more conservative in the dependencies they rely on, and to grow an immune system that can assess new dependencies and choose between competing ones that provide overlapping functionality. Individuals may also go out of sync with the herd for short or long periods.
I used darcs for a couple of years but now I'm on git. That required me to learn to migrate my repos, something that an organization might delegate to one specialized little team in the basement.
I glimpse an analogue to the CAP theorem here. The 'market solution' allows individuals to go out of sync for periods of time in hopes of increased flexibility, and the ability to manoeuvre more quickly in response to changes in the environment. Hierarchies try to keep everyone in sync all the time, 'protecting' individuals who haven't grown an immune system yet, in hopes that obviating the need for redundant immune system management will provide efficiencies at scale. Both seem plausible as responses to the quadratic explosion you describe. Which is better depends on how much manoeuvring the environment requires.
In science fiction terms, we're talking about Star Trek vs Cyberpunk worldviews.
I did not mean to suggest a preference for global hierarchy, or whatever it is you're imagining with the "Star Trek worldview".
I'm quite fond of system heterogeneity and data model independence. I see heterogeneity as natural and valuable for evolving systems, relationships, and markets. I make much effort to address and support integration of heterogeneous systems in PL designs. (And heterogeneity benefits greatly from effective automation of relationships and imports.)
Hierarchy is typically a local structure in a larger, heterogeneous system. E.g. a company may have a hierarchy, but there are many different companies and the relationships between them aren't really part of any hierarchy. In secure modular software systems, small hierarchies will tend to exist in the resource models and distribution of authority.
A point to consider: even to "assess new dependencies and choose between competing ones" can become a O(N^2) effort if the number of competing solutions is proportional to the number of people or companies. (The prevalent "Not Invented Here" philosophy makes this a not unreasonable assumption.) More importantly, often the choice of competing solutions is a property of a relationship, not well isolated to any group.
The Enterprise is just one starship among many :) (Ok, I think that analogy's outlived its usefulness.)
Empirically it doesn't seem to me that there's quadratic explosion in competing choices. Do you see that differently? It also seems intuitively reasonable: there's just so many different problems. If everyone in the world was working on todo list apps or erlang compilers I'm sure there'd be a lot more todo list apps or erlang compilers. But fortunately the world seems to need both, and a zillion other things besides.
I'm trying hard not to characterize either side as a strawman. Let me know if my biases are betraying me. Our world is a lot more driven by hierarchies than people realize. My sense is that after favoring large organizations for a couple of hundred years, the pendulum is swinging back a bit toward many more, smaller organizations. That shift has implications for software that I'm trying to work out.
There is a roughly linear increase in competing products with population. The quadratic explosion happens in the number of comparisons needed to choose the best one (re: the effort to "assess new dependencies and choose between competing ones"). Similarly, integration code tends to grow quadratic with heterogeneous choices.
That you don't see quadratic explosions directly is because there are already practices and mechanisms to mitigate them. Packaging of decisions (e.g. Ubuntu comes with Gedit, no need for each user to consider the many text editors). Compilers often use intermediate languages or representations (to support multiple front-end languages independent of multiple back-end optimizers).
Competition is further mitigated by the general fact that, in any competition, there are usually a few clear leaders to choose between. The rest are mostly ignored, yet are still important for the health of the system (new leaders must come from somewhere).
While there aren't many Erlang compilers, that's mostly because (relative to more popular languages) there aren't many Erlang users. :)
(Trying to return to the original topic..)
Ubuntu and compilers are responsible for taking some set of possible configurations and testing them to make sure they work. I am assuming that such testing will always be necessary. At any point the integrator will choose between a handful of choices -- and support some small subset of them -- for every component of the system he's providing. This doesn't seem like a problem to me.
This my core disagreement (or difference in emphasis), I think: PL techniques will never suffice for avoiding DLL hell. You'll always need to be mindful of your (transitive) dependencies. That's a social issue, an education issue.
PL techniques will never suffice for avoiding DLL hell. You'll always need to be mindful of your (transitive) dependencies. That's a social issue, an education issue.
Hmm. I don't make a strong distinction. Cf. my article social aspects of PL design. We're really in the business of programming experience design (PXD) - a term coined by Sean McDirmid in a discussion with Jonathon Edwards in An IDE is not enough.
A wise PL designer will consider various social acts that contribute to development, dependencies, deployment, configuration, integration, maintenance, extension. Even if the vision is mostly of a solitary programmer, addressing rare social elements can improve the programming experience. A PL designer with a great interest in social experience or CSCW might pursue concepts like ubiquitous programming and micro-programming (cf. my article on ubiquitous programming with pen and paper).
Similar to social aspects, a PL designer can consider didactic aspects. Curl language, for example, was carefully designed to address issues such as a smooth learning curve and avoiding discontinuity spikes. My own efforts address those plus additional didactic concerns: compositional properties as a formal basis for intuition, a smooth progression from UI to PL and back so people gain useful programming intuitions without being aware of them, object capabilities as a means to formally graduate authority of a growing developer, support for revocation and resilience so people can perform exploratory programming and recover from mistakes. (I describe a few of these in a recent LtU comment regarding the motivations for RDP.) Bret Victor recently describes Learnable Programming, which certainly benefits from various PL design elements.
I vaguely remember that I once thought as you seem to - that PL design as something so distinct from various social, didactic, CSCW, and UX aspects. That view is encouraged by many programming languages. But it is not essential. Today, programmers experience a great canyon between PX and UX. But, like most canyons, we can find some places that are easy to bridge, and even find their ends if we walk far enough along their edges. If you seek a smooth live programming experience, I think that leads quite handily to regions of the design space where the distinction between PX and UX is only a fuzzy line on a political map.
I agree that developers will always need to concern themselves with dependencies, relationships, integration. The question is: how much will the PL help? When I consider possibilities such as stone soup programming I think the PLs can help a great deal in addressing various aspects - social and otherwise - of dependency management.
Many thanks!
My science fiction comment was based on your motivations for RDP :)
Is there a need in a large scale system for automatic selection of components? Perhaps. I'm not really convinced of that, but I'm not arguing against it either.
What I am arguing here is that this shouldn't have anything to do with 'import'. Importing symbols should just be about namespace management. e.g. when you write 'import MP3Player', you should just be bringing in symbols defined in that namespace.
Look at your "import by need" idea from your link. It suffers from two additional problems to the ones you have listed:
- It resolves look-up after dev-time via a name. That's bad. Variables should be declared. Name look-up post dev-time is bad.
- You have some ad hoc assertion mechanism that specifies some properties the import is to have and you have to specify them every time you import that function.
Note that even C-style header files didn't have those problems. The main problem we had with C-style header files (ignoring the fact that it was a terrible pre-processor hack) is that they required each declared symbol to have a single global implementation. The solution, IMO, is to instead track such partially specified symbols as parameters and leave imports to namespace management.
Loading symbols or specifications I don't have a problem with, so long as it happens in a structured manner to control entanglement and coupling. My articles modules divided: interface and implement and user-defined syntax each describe structured use of names for loading symbols, specifications, or even full syntax.
I disagree with your "that's bad" assertions. Since you make no attempt to justify those assertions, I am unsure what assumptions you're making... but I doubt I share them. Look-up of behaviors after dev-time by shared symbols is the heart of OOP, row polymorphism, and other disciplines for modularity. More broadly, runtime lookups are quite useful for service brokering, hyperlinking, mime-types and app extensions, mobile code, etc.
That aside, nothing about import-by-need requires it happen "after dev-time". Much can be resolved statically. A language designer can address concerns for enforcing when certain dependencies are resolved, whether at dev-time or at deployment-time or even some later time. So long as we have clear stages, the timing of dependency resolution can be quite orthogonal to the mechanism for dependency resolution.
The problem of specifying on every import can itself be modularized. I did address that in the linked article. I agree that one might more conveniently address it with named interface modules, at a moderate cost to flexibility and uniformity.
Your "modules divided" article seems reasonable and along the lines of what I'm suggesting/doing. You still seem to be coupling import with interface, whereas I think it's simpler to allow people to import whatever they want (interface, implementation, new types, etc.). The important bit is that importing gets you exactly what's there statically at import time -- not also a promise to link to some other implementation. Linking is parameter substitution, and should be an orthogonal mechanism to namespace management.
I don't understand why you say that 'import by need' can be resolved at dev-time. In some cases I'm sure it can, but, in general, implementations need not even be dev-ed yet when you import an interface. What am I missing?
I didn't offer too much detail for why post-dev name resolution is bad other than to compare it to declaring variables. I still won't, because I think the advantages of static binding are well known and the analogy is pretty strong. You say that "shared symbols" are the heart of OOP, etc., but I was careful to refer to "names". The heart of OOP is dispatch on messages, but static binding of names to messages is consistent with OOP, commonly done, and is IMO a good thing. The same applies to row polymorphism or "other disciplines of modularity".
You're assuming we must support a "general case", but you seem to be forgetting that general cases don't happen unless we want them to. A language designer can ensure, for example, that validation tests on import are either pure or constrained in authority according to stage.
Re: You say that "shared symbols" are the heart of OOP, etc., but I was careful to refer to "names".
I noticed your use of names. But your careful use of names ("It resolves look-up after dev-time via a name. Name look-up post dev-time is bad.") was inappropriate when describing the problems with import-by-need, which uses shared symbols but does not use names. So, with that context, I assumed you have not seen or experienced much of a difference between the two (which is not unusual).
it's simpler to allow people to import whatever they want
If by simple you mean uniform, yes. But it's simplistic. It leads to complex entanglement issues. Consider your reaction to the assertion: "it's simpler to allow people to mutate whatever they want".
That said, by 'interface' I'm envisioning something close to an ML module signature, perhaps with some behavioral contracts. Support for types descriptions or a few fully constrained definitions would not be unreasonable.
The important bit is that importing gets you exactly what's there statically at import time -- not also a promise to link to some other implementation. Linking is parameter substitution, and should be an orthogonal mechanism to namespace management.
No, no, no. That is exactly wrong.
The important bit is that importing DOES NOT tightly couple you what is available at import time (whether that time is static or otherwise). This decoupling provides the wiggle room to avoid entanglement, enables orthogonal code upgrades, supports adaptation to different environments or resources, enables users to leverage preferences and policies.
Namespaces are not essential for computation or scalable programming. At best, they're a convenience. Linking of modular components, whether via substitution or unification or some other means, is the essential and important bit.
After reading your other post, I don't think we're in nearly as much disagreement as this new post implies. The most important issue semantically is linking, which I agree can be more than just vanilla parameter substitution (unification or lightweight constraint integration are fine) even though I still think of it as just substitution.
But...
The important bit is that importing gets you exactly what's there statically at import time
No, no, no. That is exactly wrong.
The important bit is that importing DOES NOT tightly couple you what is available at import time (whether that time is static or otherwise). [...]
The important bit is that importing gets you exactly what's there statically at import time
The important bit is that importing DOES NOT tightly couple you what is available at import time (whether that time is static or otherwise). [...]
The mechanism for avoiding tight coupling is linking. You specify that your component has a certain freedom (a generalized "parameter" that could be refined through unification / constraint solving) and then that "parameter" can be substituted/refined at a later link time.
Nothing in the preceding paragraph requires or has anything to do with imports! The only reason 'import' is related to any of this is that library producers will generally deliver an implementation and a specification and library clients will generally import the specification. And the specification should be imported verbatim.
And I see no reason to limit importing any kind of value or type. Any such restriction would just be annoying and serve no clear purpose. It's not like mutability at all in that regard. I guess you could argue that by forcing programmers to only import abstractions you are nudging them in the right direction, but I'd hate such a rule. To me that's just as arbitrary and annoying as a rule that functions can only be 100 lines long. No thanks. Just get rid of the obstacles that would make me reticent to use abstraction wherever appropriate and I won't need any prodding from a nanny language.
As a reason for why I will sometimes want to import an implementation rather than an interface, I believe that you should import enough specification that you can, in principle, prove the correctness of your local component. Finding a useful abstraction that specifies all of the properties a client will need is non-trivial. In cases where you're not going to bother abstracting (no parameterization), it's often better to just depend on the full implementation (at least until you have time to find a good abstraction).
Finally keep in mind the context: I'm responding to your claims that imports are bad. I'm not trying to prove that namespaces or packages must be present in a language. I'm only arguing for the existence of clean approaches to imports (orthogonal to linking) that don't have the entanglement issues you're worried about.
The phrase "correctness of your local component" is a contradiction in terms. Correctness is always contextual, never local. I.e. a function is correct with respect to a type or spec; a type is correct with respect to some larger context. (This is also why correctness is not compositional.) But you can prove partial correctness up to a partial specification and context.
It's not like mutability at all in that regard. [...] won't need any prodding from a nanny language.
Many of your complaints have been uttered before (with similar pathos) by people who don't see issues with pervasive mutability, who believe their personal discipline, experience, and foresight are reliable at scale. They don't like the idea of nanny languages, either.
You say you "see no reason", but I think that's an issue of perspective. Try a different one.
We prevent pervasive mutability for reuse, reasoning, and sanity of downstream developers. Controlling entanglement is similarly in support of downstream developers, who may wish to extricate part of a project or take most of a project code but with a few extensions or tweaks to fit a new context (and hence a slightly different notion of 'correctness'). To that downstream developer, your close-minded efforts to import implementation details is cause for much frustration.
Much of the time, you are a downstream developer. Designs that benefit downstream developers benefit you. Therefore, you have much reason to favor nanny languages that 'nudge' upstream developers, though you may not initially appreciate them when writing your own bits of code.
We have "don't pollute the river" laws because, no matter how much you believe you can depend on your own discipline, you can't depend on the discipline of every industry upstream.
I'm only arguing for the existence of clean approaches to imports (orthogonal to linking) that don't have the entanglement issues you're worried about.
You have yet to present an argument that the importing of implementation details and ad-hoc values and types won't have entanglement issues.
Correctness is always contextual, never local. I.e. a function is correct with respect to a type or spec; a type is correct with respect to some larger context.
So? That you need details of the context was my point. Bind to the details you need. If you don't have an abstraction in mind, bind to the implementation if it's convenient. Yes, having implementation details scattered afar isn't good. So don't do that. IMO the ball is in your court to explain why namespace boundaries are a good place to enforce abstraction boundaries.
I'm going to abandon the discussion of which metaphor is most appropriate. That's getting a little too indirect. Except to say that I intend to prevent river pollution by filtering it out periodically at hydroelectric plants in my language.
So? That you need details of the context was my point. Bind to the details you need.
If you "bind to the details you need" and "you need details of the context", then the result is unreusable, inflexible code - i.e. code that is bound to a specific context, entangled with it.
IMO the ball is in your court to explain why namespace boundaries are a good place to enforce abstraction boundaries.
I did describe how I reached this conclusion in the linked article on modules divided so I did not see any reason to repeat it. I'll repeat the most immediately significant points for the lazy:
The articles also provide an objective, operating definition of entanglement, in terms of the number of modules that must be copied to use a particular subprogram in a new project (new context).
Interfaces can provide some simple values (primitives, records, etc.), but nowhere near "any kind of value or type" simply because it cannot arbitrarily import other interfaces. But I don't see how implementations can ad-hoc import implementations while still controlling entanglement! I don't consider namespaces a "good place to enforce abstraction boundaries". Rather, I consider them a bad place to bind implementation details or context, for reasons of entanglement.
True, but there's no general way to avoid that. Proving that you're using some value in a way that produces the desired result usually requires additional specification of that value over and above e.g. the HM type. It doesn't need to make the code any more brittle or entangled because the code can be usable even if the proofs are broken. But there definitely seems to be some pressure to postpone proofs to later when things are somewhat stabilized in order to avoid breaking proofs repeatedly as things evolve (similarly, there's pressure to delay optimizations).
Dependencies between interfaces must be very tightly constrained in their dependencies to control entanglement.
To support effective reuse of specification code, interfaces may derive from one another and support limited parameterization.
I don't see anything about namespaces in that list. The reason it's difficult for me to follow the argument from your blog is that your imports do two things, and it's not clear to me which parts of the argument you think would still apply to the factorization I've been discussing.
[Interfaces] cannot arbitrarily import arbitrary other interfaces.
This doesn't make sense in my terminology. Interfaces don't import anything. Importing is namespace management. Do you have in mind that someone could write 'import windows.h' and suddenly everything they write has thousands of dependencies? That's not how my system works, for example.
Rather, I consider them a bad place to bind implementation details or context, for reasons of entanglement.
Namespaces are just for code organization. I should be able to organize my code any way I please. I don't want to be told that I can't split up my code along a boundary because that would violate some arbitrary rule. Organizational units are not abstraction units.
The module system I described leverages constraints to complete the links, I.e. construction by proof. This is a general way to address additional proofs (beyond HM types) without hurting flexibility or adaptability to contexts. (Actually, while enhancing flexibility and adaptability to contexts.)
I described interfaces in the article quite precisely. Why do you substitute your own terminology? Roughly, an interface is a module signature, ML style. It can serve as a namespace, albeit a closed namespace (as opposed to the cross-file C++ namespaces).
Your position that you should be able to organize code any way you please is contradicted if you have a goal to control entanglement. Entanglement is primarily an issue of organization, not abstraction, but I do not find it surprising that organizational constraints impact abstraction (cf. the earlier discussion of services). You've made your position and desires clear, but never justified them as wise.
This conversation is too broken to fix easily. Maybe we can revisit this when I have something that I can share and point to and ask "where's the entanglement?"
Organizational units are not abstraction units.
This seems a rather extraordinary claim to make in passing.
I think if I made a list of organizational units, the vast majority are would directly correspond to abstractions. Consider just a few: directory, text file, paragraph, service, module, DLL, record, function, role, group, account.
Might a more rational position be just the opposite? Organizational units are the heart of many useful abstractions. What is a cloud? an organization of water vapor. What is bicycling? an organization of man, device, and motion. What is a monad? a structure that organizes code to compose in a sequence. Even broad abstractions - space, time, water, grass - get measured, divided, sometimes named into useful structures and organizations.
Entanglement is an organizational issue. I do not find surprising that constraints on organization (e.g. to control entanglement) can impact abstraction. I do find it surprising that you assume organization and abstraction to be separate issues. If you've some great revelation that will make your position as obviously correct as you assume it to be, I'd be happy to hear it.
What is bicycling? an organization of man, device, and motion.
This seems a rather extraordinary claim. Bicycling is a form of exercise and sport! Motion is an abstraction and can't be part of an organization! Women use bicycles, too!
If you've some great revelation that will make your position as obviously correct as you assume it to be, I'd be happy to hear it.
I'm not claiming that I'm going to going to shock and awe you into agreeing with me. I'm just hoping to provide enough context that we can communicate effectively.
I'm just hoping to provide enough context that we can communicate effectively.
Then could you make a habit of justifying more of your assertions? Your arguments tend to consist of assertions I find dubious ("Name look-up post dev-time is bad.", "Importing symbols should just be about namespace management.", "I should be able to organize my code any way I please.", "Organizational units are not abstraction units.") presented without any explanation or justification. I suppose you believe them to be self-evident. When I ask for justification ("I am unsure what assumptions you're making", "Might a more rational position be just the opposite?") I'm simply rebuffed or ignored.
I don't know how you hope to provide any context except through communication. Perhaps you should blog some of your ideas or examples, so that you can link to them for extra context. It won't help for the lazy people who can't be bothered to follow links, of course, but they'd have no right to complain about lacking context.
What's becoming clear to me is that some heavy infrastructure is needed to support all the compile-time, link-time, and runtime functionality you need in order to fully integrate interfaces, contracts, capabilities, and unit tests with modules and imports.
A "types-only interface specification" tells you the HM types of arguments and return values for a set of functions. A "contract" names a set of semantics those functions are supposed to have and a set of capabilities which they are not supposed to exceed. These two together are an "interface" as I'm thinking of it.
The contract is answered by a corresponding assertion in the unit that it conforms to a named contract. Next you have a "unit test" that verifies conformance to the contract for at least a few dozen cases, while profiling the proposed import to see about its performance and to see how much of its code gets exercised by the test cases.
Ideally the unit test reports 100% code coverage (meaning no unrelated functionality is hidden in the unit) and contract conformance. In practice 100% code coverage is hard to achieve when you don't compose the unit test while looking at the proposed implementation, so you will probably configure your system to prefer whichever potential import has the greatest code coverage (and speed) within the unit test, and may extend the unit test by generating "random" cases to test (at the expense of potentially long test runs) to try to get code coverage higher. Alternatively, in full paranoia mode, you may configure your system to "stub out" any code not exercised by the unit test with a jump to an error handler.
The unit tests go with the contract, and may require as much code or more code than the unit being imported! Their only virtue in terms of saving development effort is if the contracts themselves are standardized, and the unit tests may therefore be part of a standard library. In this case an implementation of the functionality could also have been part of the standard library, so, um, why not?? Because maybe the import integrates with something hairy or performs better? So, unit tests may include a known-valid but somehow undesirable implementation of the functionality itself to check the potential import against.
Each potential import may carry with it additional contracts (and unit tests) for subcontractor interfaces/libraries that *it* needs. The capability limitations you specified with the original contract that a unit must fulfil, are transitive and must be applied to these subcontractor units as well. If subcontractor libraries contain code not exercised by your unit tests of the library they're subcontracting for in the case of your program, you may need to auto-stub that code as well. This is because the unit tests for subcontractor units in untrusted code are themselves untrusted; you don't know that they're checking the right thing, so you can't accept their word that something conforms as testimony that the conforming thing is relevant or conformant to your own requirements.
Selecting the units that your build will use means selecting imports such that the transitive closure of all imports starting with those needed by your program is small/manageable/fast/has other desirable characteristics.
Eventually you identify a set of imports that will "complete" your program, and you link them all together. Now you have to compile in the capability management, valid-return assertions, and checks for any type information you couldn't prove statically, that you got from the program and from every subcontracting unit.
If you imported something in full-paranoia mode and inserted jumps to a handler rather than trusting un-exercised code, you have to add the handler, and the handler ought to record the set of arguments that led to testing the unchecked code, extending your unit test. If your unit test included a known-correct but undesirable implementation of the functionality, your handler may be able to jump to that implementation and retry, assuming it doesn't require state information that exists in a form stored by and only available to the imported code.
In all of this, you have to distinguish "trusted" code -- ie, code that someone you have paid money to and have a contract with accepts specific liability for, or locally-developed code that doesn't merit fully paranoid checking because you know you didn't put anything malicious into it, from "found" code -- ie, downloaded-from-somewhere code from someone you don't have any business relationship with, that requires full paranoia even at the expense of runtime checks.
Is this a reasonable description of the infrastructure you need to make this "interchangeable imports via contracts and capabilities" model a reality?
I've been interested in techniques that might allow developers to express general contracts then use those to automatically generate a mix of tests and local proofs. This allows simple assertions to cover large numbers of tests, while allowing us to move forward with high confidence that might be less than 100%. I've seen systems that are good for proofs, and I've seen systems for automatic generation of tests, but I've not seen a system that provides smooth interpolation between the two.
I think 'auto-stubbing' to remove untested code is an awful idea. Even if code is untested or incorrect with respect to the domain model, it may still be protecting more global properties (type safety, duration coupling, etc.) that are easy to validate or enforce structurally but cannot be generically achieved via stub. Similarly, injecting runtime tests is dubious if the only thing you can do upon failing a test is violate abstractions a bit earlier.
Now you have to compile in the capability management
Why would you need to do this?
Of the capability models I've studied, object capabilities are the only ones worth learning and knowing. Object capabilities describe first-class, tight coupling of designation and authority. Developers must explicitly manage their object capabilities, and explicit management is a significant aspect of their value for secure interaction design - ensuring visibility, awareness, and that the path of least resistance is to grant least authority.
Using ocaps, you don't need to pass tests or type-checks to protect the important abstractions and services. You only need memory-safety, which is easy to ensure generically. Incorrect code is constrained in the damage it can cause by the object capability model. Developers can readily mix trusted and untrusted code.
Even better if your programming language also enforces real-time properties. (Batch processing tasks can always be modeled via incremental state manipulation with real-time increments.) If you have both ocaps and real-time properties, you're additionally protected against denial of service attacks and most timing-based covert channels.
You can have a healthy paranoia without elevating it to insanity.
No. You can do a better job with simpler mechanisms.
Many of my comments that involve 'should' should be read as 'the way I think this should work' rather than as an assertion that I can prove these preferences are optimal. I do, of course, have reasons for my preferences.
Why do I think that unsupervised binding of names is bad? For one, it's a security problem. As I recall, Z-Bo's link has examples of what can go wrong. When I type a name, almost always, I'm attempting to reference a specific entity (even if that entity is a parameter). I want my IDE to make any ambiguity clear, allow me to resolve it, and have it easy for me to inspect what I've referenced. That requires it to happen at dev-time. For the same reasons that it's good for security, it's good for avoiding certain bugs.
Regarding 'organizational boundaries are not abstraction boundaries', I think it's useful to be able to import some but not all of the symbols defined in an abstraction, to rename symbols and give them local aliases, and even to split an abstraction between several namespaces (though that's probably rare). I'm not arguing that this is the one true way (though obviously I prefer it), but I am arguing that I don't see any entanglement issues. You claim you've demonstrated the entanglement issues on your blog, but then you summarize the argument in a way that doesn't mention name importing or namespaces at all.
The entanglement issue that I understand you to be describing has to do with failure to abstract properly, leading to dependencies of abstractions on things that should be implementation details. If names are semantically part of your abstractions then, yes, you can run into entanglement issues from failing to abstract from the names. But since I'm the one arguing that names and organization should not be semantically meaningful, I have a hard time understanding why you think my approach leads to entanglement.
The reason I am tempted to bail on this discussion is that it doesn't seem to be getting anywhere and because I do think that it will be much easier for me to explain my position with a little IDE for my language and some documentation rather than trying to figure out what set of concepts we're not using the same words for.
There are insecure approaches to binding of names. There are also secure approaches. It isn't clear to me that `unsupervised` is the relevant distinction. (If you depend heavily on supervision for computer security, you're doing it wrong.)
Use of names for 'specific entities' seems either rarer or less specific than you've been implying. For example, it is unlikely that you're using version numbers or hashes in your names. But I agree with a goal to understand and control ambiguity and resolution, both at dev-time and run-time.
Where you speak of current practice ("When I type a name, almost always [...]"), I note that you're constrained by current languages. It's difficult to appreciate other possibilities without experiencing them. I expect your habits would change if you had more options readily available.
The entanglement issue that I understand you to be describing has to do with failure to abstract properly
Entanglement is strictly an organizational issue.?" Entanglement nearly always exists. The issue is controlling entanglement (e.g. with a big-O constraint or an asymptotic bound), not preventing it.
Entanglement isn't about abstraction. However, organization has a significant impact on expression of abstraction. It is necessary to constrain organization to control entanglement. Those constraints WILL impact abstractions.
Your "importing symbols from namespaces" does not control entanglement in any way. At the very least, you'll end up entangling the code that lists symbols from each namespace.
It isn't clear to me that `unsupervised` is the relevant distinction. (If you depend heavily on supervision for computer security, you're doing it wrong.)
Well, it seems we agree on the problems and some of the goals. This subthread started with my criticism of your proposed technique of import by need. That criticism was based on a particular understanding of what you had in mind, that perhaps was not correct. If that's the case, then I don't mind retracting my criticism, but I still haven't understood the details that would lead me to believe that's the case.
It's difficult to appreciate other possibilities without experiencing them.
It depends, but it's not that difficult in my experience. It's difficult to appreciate them without understanding them, though.
I don't have trouble understanding this. I understand that I'm speaking to my personal viewpoints, even if it's not always clear, for expedience, in every sentence. You're the one that blogs about the non-existence of whole classes of solutions. When I speak up that I think you've missed a possibility in the design space, you insist that I consult your proof to the contrary.
For example, it is unlikely that you're using version numbers or hashes in your names.
Usually when I'm developing a module, the specific intention I have in mind with a symbol is "the most current version of this construct". Occasionally, I do intend "thisspecific version of this construct", and support for that is in the works.?"
In my system you will be able to export precisely what you need, regardless of how things are organized. And what you need is strictly about how well you've abstracted the dependencies. I have never claimed importing symbols from namespaces addressed entanglement - merely that it doesn't cause it.
Precise control of export is valuable. It can prevent accidental bindings. But I've yet to encounter or design a PL or architecture where it appreciably controls entanglement. Relevantly, programs become entangled due to lots of fine-grained, short sighted, intentional bindings.
"the most current version of this construct".
Oh? And do you mean that globally? (Is there even a total ordering on versions?) Or is there also some implicit constraint on where you look for this version? And where do half-completed versions fit?
My intended approach is actually more precise and formal about the sort of linker magic traditional languages leave to ad-hoc tooling. My motivation had a lot to do with understanding and modeling names (esp. Nominative types) in open distributed live programs where multiple versions must coexist.
Oh? And do you mean that globally? (Is there even a total ordering on versions?) Or is there also some implicit constraint on where you look for this version? And where do half-completed versions fit?
-- Version 1 source:
x = 1
y = x
-- Version 2 source:
x = 2
y = x
a = y -- a = 2
b = y@ver1 -- b = 1
Syntax is made up. The point is that no annotation means "the version that exists in the current version", but there is some way of bringing in older versions from source control.
I would be much happier if you were to take no annotation to mean 'automatically annotate as requiring the version tested against'. 'Current' or 'latest' version is far too ambiguous, far too dangerous.
Any open-ended handling generally suggests ambient authority, which will either be abused, misused, or hard for programmers to understand the effects thereof. See a related point I made a long time ago: A little harder to get right than you might think.
But imports are fine just so long as you remember they are only for interaction with people (to aid with binding resolution).
A crucial innovation of bondi and its underlying Pattern Calculus is that the pattern variables used for reduction are separate from the binding variables used to control scope. In terms of usability, how would you say the various techniques in Haskell grade out for "interaction with people"?
Imports are fuzzy. Imports should be dev time.?
Consider my question in light of how you might implement configuring a system's run-time implementation.
I found your clarifying follow-up useful, Z-Bo.?
What if the answer was the subject is required to explicitly present the capabilities that it wants to use with each request?
Build the system configuration out of rights amplification primitives, such as sealer/unsealer pairs and sibling communication. Alternatively, you could use an EQ operator, but using EQ is antithetical to this whole subthread since it ruins developing a good equational theory for a language.
Also, encourage developers to learn sound patterns for secure configuration, such as Grant Matcher.
Another big implication is that anything globally accessible must be transitively immutable.
anything globally accessible must be transitively immutable
In live programming, we must acknowledge that the entire program is mutable. Every function, constant, module, etc. is mutable, and we do access those. But authority to cause this mutation should be pretty well controlled - e.g. in many cases, it is not and should not be an authority held by the program itself. So I'd tend to weaken that constraint a bit. Try, instead: "authority for mutation must not be globally accessible".
A capability-secure program can be deeply mutable. But there must not be any hidden channels for communication between subprograms.
There are (at least) two major concerns with importing libraries. And I contend that most posts here are ignoring at least one of them.
First, there is the question of how to determine *what* to import. Usually this is done by naming libraries and then looking for a matching named library to import.
Other schema are possible - for example looking for something that provides a named/specified interface, finding potentially several, and picking one to import. If you find several possible imports satisfying your interface requirement, you have the ability to pick, eg, the one that runs fastest, creates the fewest *additional* requirements, or requires the least additional space -- any of which can be valuable. If you do this, though, you must make absolutely sure you're importing something that *DOES* what you think it does; the interface must be checked against contracts and heavy use of assertions.
The second major concern, however, is the question of what an imported library is *allowed* to do - is it "mobile code" that needs to be sandboxed or is it trusted code that you don't need to protect your runtime from? Can it be permitted to access the local filesystem, access the network (and if so to which specific hosts and using what protocols)? Can it "see" or manipulate resources not passed to it as arguments generally? Can it be permitted to read or modify the local environment at the call site? Can it longjmp() to a call frame created by a completely different library, or by your runtime itself? Can it be permitted to treat expressions in its arguments syntactically (as, eg, a lisp macro does) rather than as subexpressions to be evaluated before it starts (as procedure calls in every eager language do)?
The above, even the insane things, are a big and incomplete list of things that executable machine code can in many circumstances do; if you're importing executable machine code that's going to run with access to non-virtualized hardware, it can completely rape your runtime access guarantees and language call semantics. Remember, raw machine code is not constrained to obey your runtime guarantees and may have been composed in raw binary completely bypassing your compiler and its "correct by construction" efforts.
Here is my point; if you make imports at all ambiguous in resolution -- that is, if just anybody can substitute one service for another and relink, or if there's any chance that a service will be chosen without human input -- then you're going to get malicious services that try to fulfill whatever interface requirements they need to fulfill in order to get selected and linked, but also try to install spyware or snoop the user's cache or send spam or whatever. In fact we're already seeing this to some extent with bogus and "snoopy" libraries, some of them from major media vendors.
The more flexible and powerful your procedure calls are -- whether that takes the form of high abstraction levels like lisp macrology or the form of low abstraction levels like raw machine code with non-virtualized hardware access -- the more imported procedures have a corresponding ability to *break* abstraction barriers if misused or malicious. Thus, the more you will have to exercise control over what imported procedures are allowed to do.
No set of assertions ensuring that the named interface is fulfilled correctly can assure that nothing else is done; you can't prove a negative. Therefore it becomes needful to strictly limit what imports are *allowed* to do, at the level of primitives or at the level of capabilities.
Bear
if there's any chance that a service will be chosen without human input -- then you're going to get malicious services
To be fair, human input doesn't really make a difference. Humans lack any real ability to inspect any code for obfuscated malicious intent. It's hard enough to spot accidental malign bugs and security holes that nobody is trying to hide. A human will do what humans always do: favor some sources over others based on who they decided to trust a long time ago (which updates slower than it should due to decision fatigue). In terms of code, that might be based on signatures or shared private registries. If we want to express anything stronger than a weak or moderate trust preference, the onus is ultimately on the machine.
Eliminating ambient authority is certainly useful for controlling and reasoning about what an import can do. I depend heavily on object capability model and a few simple patterns (involving fine-grained registries) to control what an import can do.
Proving any theorem about code will tend to eliminate both malicious and buggy code. As Benjamin Pierce notes in Types Considered Harmful, it doesn't much matter which theorems you attempt to prove. So proof-carrying code is also a great way to ensure safe and secure code. Type systems, linear types, etc. are ways of providing lots of small theorems to prove.
I just wrote a follow-up in an attempt to synthesize several conversations I had here and elsewhere, and to clarify some of the fog in the original post. (I'm especially interested in your reactions to the paragraph on reuse; that might be a fertile source of disagreement.)
|
http://lambda-the-ultimate.org/node/4636/
|
CC-MAIN-2021-49
|
refinedweb
| 11,692
| 54.22
|
Working with COM port in windows and linux
Once upon a time I was making an application that was supposed to run from Windows and Linux and connect to the board with STM32 via UART. This article can be useful for beginners who program in C ++ (use the compilers GCC and MinGW) and who need COM port support under two OSes at once, and which laziness to google and you need ready-made code.
here . To connect to your project, you need to add just two files: xserial.cpp and xserial.hpp .
Example of using [/b]
#include
#include "xserial.hpp"
using namespace std;
int main () {
/* initialize the available COM port, without checking the parity bit,
with 8-bit data bits and one stop bit. * /
const int baudRate = 115200; //port speed
const int dataBits = 8; //the length of the data is
xserial :: ComPort serial (
.baudRate,
.xserial :: ComPort :: COM_PORT_NOPARITY,
dataBits,
.xserial :: ComPort :: COM_PORT_ONESTOPBIT);
if (! serial.getStateComPort ()) {//If the port did not open
cout "Error: com port is not open!" endl;
return 0;
}
//output the list of available ports
serial.printListSerialPorts ();
//get the text before the symbol n
cout "Test getLine () " endl;
serial "Test 1n";
cout serial.getLine () endl;
//check the function of checking the number of bytes received
cout "Test bytesToRead () " endl;
serial.print ("Test 2n");
int k = serial.bytesToRead ();
cout "bytes to read =" k endl;
while (k < 6) {
.k = serial.bytesToRead ();
}
.cout "bytes to read =" k endl;
.
//check the read function
char data[512];
.cout "Test read () "endl;
.series.read (data, 7);
.cout data endl;
.
//check the function of reading the word
serial.print (" Bla Bla Blan ");
cout "Test getWord (), print Bla Bla Bla" endl;
cout "word 1:" serial.getWord () endl;
cout "word 2:" serial.getWord () endl;
cout "word 3 : "serial.getWord () endl;
.
return 0;
}
The class also added the function getListSerialPorts to get a list of available COM ports.
Nuances of using COM port
Under Windows, there may be problems when writing to the COM port if the Nucleo STM32 board is used as the USB-UART adapter. Often the problem occurs after the port is reinitialized, sometimes it only helps reboot the laptop.
P.S.
It is assumed that anyone who needs to "google" the code can now simply download something already working and continue to use in their small project, to change for themselves, as they please.
It may be interesting
7-09-2018, 23:15Publication Date
- Views: 344
|
https://habrahabr.info/development/development-under-windows/4674-working-with-com-port-in-windows-and-linux.html
|
CC-MAIN-2020-40
|
refinedweb
| 401
| 66.64
|
Python requests module is used to make HTTP requests easily. It makes the HTTP requests very easy without detailed request parameters. In this tutorial, we will learn how to import the requests module and use it for HTTP requests.
Install requests Module
The requests module is provided via the PyPI repository and can be installed with the pip command like below.
python -m pip install requests
Import requests Module
In order to use the requests module it should be imported with the import statement like below.
import requests
Make HTTP Request with requests Module
The get() method of the requests module can be used to make HTTP request. If required extra parameters can be also provided. In the following example we will make an HTTP get request to the “
import requests r = requests.get('
The returned response can be displayed with the text attribute of the returned response.
print(r.text)
|
https://pythontect.com/import-and-use-request-module-in-python/
|
CC-MAIN-2022-21
|
refinedweb
| 151
| 63.29
|
Registered users can ask their own questions, contribute to discussions, and be part of the Community!
Registered users can ask their own questions, contribute to discussions, and be part of the Community!
I have a csv that contains 2 datasets arranged vertically (one below the other) in it -
1. Header
2. Body
After parsing these 2 datasets using prepare recipe, they need to be joined together.
However, there is no common key between these 2 datasets.
One way is to enrich these 2 datasets during prepare recipe step with the csv filename and then join the 2 datasets using this filename as the key.
I am unable to find any option in DSS that can help identify/ extract the uploaded file's name.
Please help.
Hi,
In a prepare recipe you should be able to use: Misc > Enrich record with context information. Where you can add the filename and join based on that.
Please note there could some limitations for other file types besides txt or csv.
See :...
Let me know if this would work for you.
Thanks,
Unfortunately, I don't see this option in my version of DSS, any other suggestions please.
Dataiku DSS
Version 6.0.1
If you are unable to upgrade.
One possible suggestion would be to use a managed folder to upload all your files to. Use a python recipe to add the file name and output to another managed folder from which you can build create your datasets.
import dataiku import pandas as pd, numpy as np from dataiku import pandasutils as pdu import os input_folder = dataiku.Folder("PAcVjikK") paths = input_folder.list_paths_in_partition() output_folder = dataiku.Folder("MLpqB40C") # Iterate through files, check if they fit certain regex condition, and write them to output managed folders accordingly. x=0 for paths[x] in paths: with input_folder.get_download_stream(paths[x]) as f: data = pd.read_csv(f) filename= paths[x][1:] print(filename) data['filename_column'] = filename print(data) output_folder.upload_stream(filename, data.to_csv(index=False).encode("utf-8")) x +=1
|
https://community.dataiku.com/t5/Using-Dataiku/How-do-I-extract-filename-of-file-uploaded-using-Dataset-gt/m-p/18171/highlight/true
|
CC-MAIN-2022-27
|
refinedweb
| 332
| 67.15
|
Hello,
I have a question re print options in P6.
When I print view (layout) with the Gantt Chart and columns I always have black frame (line) around the printout, which wraps up the header, footer and rest of the content.
Is there a way to get rid of this frame somehow? or change color?
I don't see any option which does that, but maybe someone knows the trick?
Thanks,
Karol
To be honest, I do not think this black frame can be disabled from printing.
Thanks AMA.
Another question re Printing. Seems impossible for me to have text Arial 6pt in header / footer. Size available in P6 from drop-down list is between 8 - 36.
I managed to copy and paste from MS Word text Arial size 6 but when I apply - P6 change it to Times New Roman or similar. Sometimes when I paste the text (font 6), change font to e.g. Arial Black and then back to Arial again - xml code appears on printout as part of the text: <?xml:namespace. Is it something wrong with my Database (sql 2008 R2) or its a P6 issue.
Thanks.
Karol
|
https://community.oracle.com/message/11139923
|
CC-MAIN-2015-48
|
refinedweb
| 193
| 82.14
|
#include <gromacs/analysisdata/analysisdata.h>
Handle for inserting data into AnalysisData.
This class provides an interface for adding data frames into an AnalysisData object. After a handle is obtained from AnalysisData::startData(), new frames can be added using startFrame(). Then values for that frame are set using provided methods (see below), and finishFrame() is called. After all frames have been added, finishData() (or AnalysisData::finishData()) must be called.
For simple (non-multipoint) data, within a frame values can be set using selectDataSet(), setPoint() and setPoints(). Setting the same column in the same data set multiple times overrides previously set values. When the frame is finished, attached modules are notified.
Multipoint data works otherwise similarly, but requires finishPointSet() to be called for each set of points for which the modules need to be notified. Each point set starts empty (after startFrame() or finishPointSet()), and values can be set using setPoint()/setPoints(). A single point set can contain values only for a single data set, which must be selected with selectDataSet() before setting any values. finishPointSet() must also be called for the last point set just before finishFrame().
This class works like a pointer type: copying and assignment is lightweight, and all copies work interchangeably, accessing the same internal handle. However, normally you should only keep one copy of a handle, i.e., treat this type as movable. Several handles created from the same AnalysisData object can exist concurrently, but must currently operate on separate frames.
Constructs an invalid data handle.
This constructor is provided for convenience in cases where it is easiest to declare an AnalysisDataHandle without immediately assigning a value to it. Any attempt to call methods without first assigning a value from AnalysisData::startData() to the handle causes an assert.
Does not throw.
Finish data for the current frame.
Finish data for the current point set.
Must be called after each point set for multipoint data, including the last (i.e., no values must be set between the last call to this method and AnalysisDataStorage::finishFrame()). Must not be called for non-multipoint data.
Selects a data set for subsequent setPoint()/setPoints() calls.
After startFrame(), the first data set is always selected. The set value is remembered until the end of the current frame, also across finishPointSet() calls.
Does not throw.
Set a value for a single column for the current frame.
If called multiple times for a column (within one point set for multipoint data), old values are overwritten.
Does not throw.
Set a value and its error estimate for a single column for the current frame.
If called multiple times for a column (within one point set for multipoint data), old values are overwritten.
Does not throw.
Set values for consecutive columns for the current frame.
Equivalent to calling setPoint(firstColumn + i, values[i], bPresent) for i from 0 to count.
Does not throw.
Start data for a new frame.
Each
index value 0, 1, ..., N (where N is the total number of frames) should be started exactly once by exactly one handle of an AnalysisData object. The frames may be started out of order, but currently the implementation places some limitations on how far the index can be in the future (as counted from the first frame that is not finished).
|
https://manual.gromacs.org/current/doxygen/html-lib/classgmx_1_1AnalysisDataHandle.xhtml
|
CC-MAIN-2021-17
|
refinedweb
| 545
| 58.69
|
Sometimes while programming, we stumble upon a condition where we want to use a value or a small piece of code many times in a code. Also there is a possibility that the in future, the piece of code or value would change. Then changing the value all over the code does not make any sense. There has to be a way out through which one can make the change at one place and it would get reflected at all the places. This is where the concept of a macro fits in.
A Macro is typically an abbreviated name given to a piece of code or a value. Macros can also be defined without any value or piece of code but in that case they are used only for testing purpose.
Lets understand the concept of macros using some example codes.
Defining Macros without values
The most basic use of macros is to define them without values and use them as testing conditions. As an example, lets look at the following piece of code :
#include <stdio.h> #define MACRO1 #define MACRO2 int main(void) { #ifdef MACRO1 // test whether MACRO1 is defined... printf("\nMACRO1 Defined\n"); #endif #ifdef MACRO2 // test whether MACRO2 is defined... printf("\nMACRO2 Defined\n"); #endif return 0; }
- So, the above code just defines two macros MACRO1 and MACRO2.
- As clear from the definition, the macros are without any values
- Inside the main function, the macros are used only in testing conditions.
Now, if we look at the output, we will see :
$ ./macro MACRO1 Defined MACRO2 Defined
Since both of the macros are defined so both the printf statements executed.
Now, one would question where are these testing macros used. Well, mostly these type of testing macros are used in a big project involving many source and header files. In such big projects, to avoid including a single header more than once (directly and indirectly through another header file) a macro is defined in the original header and this macro is tested before including the header anywhere so as to be sure that if the macros is already defined then there is no need to include the header as it has already been included (directly or indirectly).
Defining Macros through command line
Another use of testing macros is where we want to enable debugging (or any other feature) in a code while compilation. In this case, a macro can be defined through compilation statement from command line. This definition of macro is reflected inside the code and accordingly the code is compiled.
As an example, I modified the code used in example of the last section in this way :
#include <stdio.h> #define MACRO1 int main(void) { #ifdef MACRO1 // test whether MACRO1 is defined... printf("\nMACRO1 Defined\n"); #endif #ifdef MACRO2 // test whether MACRO2 is defined... printf("\nMACRO2 Defined\n"); #endif return 0; }
- So now only MACRO1 is defined
- While MACRO2 is also being used under a condition.
If the above program is now compiled and run, we can see the following output :
$ ./macro MACRO1 Defined
So we see that since only MACRO1 is defined so condition related to MACRO1 executed. Now, if we want to enable or define MACRO2 also then either we can do it from within the code (as shown in first example) or we can define it through the command line. The command for compilation of the code in that case becomes :
$ gcc -Wall -DMACRO2 macro.c -o macro
and now if we run the code, the output is :
$ ./macro MACRO1 Defined MACRO2 Defined
So we see that MACRO2 got defined and hence the printf under the MACRO2 condition got executed.
Macros with values
As discussed in the introduction, there are macros that have some values associated with them. For example :
#define MACRO1 25
So, in the above example, we defined a macro MACRO1 which has value 25. The concept is that in the preprocessing stage of the compilation process, the name of this macro is replaced with macros value all over the code. For example :
#include <stdio.h> #define MACRO1 25 int main(void) { #ifdef MACRO1 // test whether MACRO1 is defined... printf("\nMACRO1 Defined with value [%d]\n", MACRO1); #endif return 0; }
So in the code above, a value of 25 is given to the macro MACRO1. When the code above is run, we see the following output :
$ ./macro MACRO1 Defined with value [25]
So we see that the macro name (MACRO1) was replaced by 25 in the code.
NOTE: For more on the compilation process, please refer to the article : Journey of a C program to Linux executable
Defining macros with values from command line
Not only the macros can be defined from command line (as shown in one of the sections above) but also they can be given values from command line. Lets take the following example :
#include <stdio.h> int main(void) { #ifdef MACRO1 // test whether MACRO1 is defined... printf("\nMACRO1 Defined with value [%d]\n", MACRO1); #endif return 0; }
In the code above, the macro MACRO1 is being tested and its value is being used but it is not defined anywhere. Lets define it from the command line :
$ gcc -Wall -DMACRO1=25 macro.c -o macro $ ./macro MACRO1 Defined with value [25]
So we see that through the command line option -D[Macroname]=[Value] it was made possible.
Macros with piece of code as their values
As discussed in the introduction part, macros can also contain small piece of code as their values. Those piece of code which are very small and are being used repetitively in the code are assigned to macros. For example :
#include <stdio.h> #define MACRO(x) x * (x+5) int main(void) { #ifdef MACRO // test whether MACRO1 is defined... printf("\nMACRO Defined...\n"); #endif int res = MACRO(2); printf("\n res = [%d]\n", res); return 0; }
- So, In the code above we defined a parametrized macro that accepts a value and has a small piece of code associated with it.
- This macro is being used in the code to calculate value for the variable ‘res’.
When the above code is compiled and run, we see :
$ ./macro MACRO Defined... res = [14]
So we see that a parametrized macro (that has a small piece of code logic associated with it) was used to calculate the value for ‘res’.
Get the Linux Sysadmin Course Now!
{ 14 comments… read them below or add one }
Just a suggestion. In the last example replace the macro in this way:
#define MACRO(x) (x) * ((x)+5)
Explaining that the x should be put between brackets to avoid errors like this one:
yourMACRO(3+2) -> 3+2*(3+2+5)=23
myMACRO(3+2)-> (3+2)*((3+2)+5)=50
Can you also discuss about string concatenation with Macro, as well as dynamic code generations with Macros.
Very good article !!!
May I know that if we redefine a macro with new value, which is already defined in source file with a value, by command-line (as told in post), then why we get the value provided in source file rather than command-line ? and how to redefine it by value specified by command-line ??
Thanks
and please provide more information regarding macros like macro operators in another post, if possible..
Hi,
Thanks a lot,
if possible, explain macro operators in next post
Great Article,
It would be great if you provide some more examples.
The macro is used to comparing with 2 or more various like this
#define max( (a), (b) ) (a) > (b) ? (a) : (b)
I hope it is useful
string concatenation:
#define concat(x,y) x ## y
#include
#define FIRST 7
#define LAST 5
#define ALL FIRST + LAST
int main()
{
printf(“%d”, ALL*ALL);
return ALL;
}
What will be the output of the above program….
Option:
1. 47
2. 144
3. 35
4. 12
Please give the appropriate answer with explanation..
Hi Ansarul,
The output for ur code is 47.
bcoz “ALL” means “FIRST”+”LAST” is 7+5
so, the expression ALL*ALL is defined as 7+5*7+5 =7+35+5=47 (According to Operator precedence, first multiplication takes place after that addition takes place.)
Thanks a lot supraja……
I also hav some other queries…..will be posting very soon….hope i will get the very positive output from you……again thanx a lot……
#include
#define PRODUCT(x) (x*x)
int main()
{
int i=3,j,k,l;
j=PRODUCT(i+1);
k=PRODUCT(i++);
l=PRODUCT(++i);
printf(“%d%d%d%d”,i,j,k,l);
return o;
}
plz provide ad answer wit xplanation..thanks:)
very nice explaination
its awesome yaar………u have explain everything very well……..and make it very understanble
|
http://www.thegeekstuff.com/2012/05/c-macros/
|
CC-MAIN-2013-48
|
refinedweb
| 1,444
| 69.82
|
Back to index
#include "bzlib_private.h"
Go to the source code of this file.
{ \ Int32 zz, yy, tmp; \ zz = z; tmp = heap[zz]; \ while (True) { \ yy = zz << 1; \ if (yy > nHeap) break; \ if (yy < nHeap && \ weight[heap[yy+1]] < weight[heap[yy]]) \ yy++; \ if (weight[tmp] < weight[heap[yy]]) break; \ heap[zz] = heap[yy]; \ zz = yy; \ } \ heap[zz] = tmp; \ }
Definition at line 84 of file huffman.c.
Definition at line 210 of file huffman.c.
{ Int32 pp, i, j, vec; pp = 0; for (i = minLen; i <= maxLen; i++) for (j = 0; j < alphaSize; j++) if (length[j] == i) { perm[pp] = j; pp++; }; for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0; for (i = 0; i < alphaSize; i++) base[length[i]+1]++; for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1]; for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0; vec = 0; for (i = minLen; i <= maxLen; i++) { vec += (base[i+1] - base[i]); limit[i] = vec-1; vec <<= 1; } for (i = minLen + 1; i <= maxLen; i++) base[i] = ((limit[i-1] + 1) << 1) - base[i]; }
Definition at line 103 of file huffman.c.
{ /*--; } } }
|
https://sourcecodebrowser.com/lightning-sunbird/0.9plus-pnobinonly/huffman_8c.html
|
CC-MAIN-2017-51
|
refinedweb
| 185
| 66.41
|
I have two lists of equal length, one is a data series the other is simply a time series. They represent simulated values measured over time.
I want to create a function that removes a set percentage or fraction from both lists but at random. I.e. if my fraction is 0.2, I want to randomly remove 20% of the items from both lists, but they have to be the same items (same index in each list) removed.
For example, let n = 0.2 (20% to be deleted)
a = [0,1,2,3,4,5,6,7,8,9]
b = [0,1,4,9,16,25,36,49,64,81]
a_new = [0,1,3,4,5,6,8,9]
b_new = [0,1,9,16,25,36,64,81]
import random a = [0,1,2,3,4,5,6,7,8,9] b = [0,1,4,9,16,25,36,49,64,81] frac = 0.2 # how much of a/b do you want to exclude # generate a list of indices to exclude. Turn in into a set for O(1) lookup time inds = set(random.sample(list(range(len(a))), int(frac*len(a)))) # use `enumerate` to get list indices as well as elements. # Filter by index, but take only the elements new_a = [n for i,n in enumerate(a) if i not in inds] new_b = [n for i,n in enumerate(b) if i not in inds]
|
https://codedump.io/share/DClCYVn20mBS/1/how-to-randomly-remove-a-percentage-of-items-from-a-list
|
CC-MAIN-2018-09
|
refinedweb
| 239
| 72.66
|
0
printf(" "); //output a blank space when if not true
You say "if not true" in the comment but you don't actually do any test to make it happen that way. That
printf will be happening every time through the loop. It is making the top and bottom of your box twice as long as they should be because it is printing a
'*' and a
' ' for each column.
0
thanks man it was more of a rectangle before but now its a box based on input.
#include <stdio.h> #include <conio.h> //This program a box pattern int main() { int r,c; int bx; printf("\nEnter size of box "); scanf("%d",&bx); printf("\n"); for (r=0; r<bx/2+1; r++) // Loop runs half of user input +1 { for (c=0; c<bx; c++) //Controls printing accross { if(r==0 || r==bx/2) //output top and bottom of box { printf("*"); } else if(c==0 ) printf("*"); // output when c at 0 (Left column) else if(c==bx-1) printf("*"); // output (Right Column) else printf(" "); //output a blank space } printf("\n"); //goes to a newline after main loop } getch(); }
You
This article has been dead for over six months: Start a new discussion instead
|
https://www.daniweb.com/software-development/c/threads/446345/newbie-problem
|
CC-MAIN-2015-18
|
refinedweb
| 204
| 66.41
|
Would it make sense to install the following patch to GNU tar? The idea here is that I suspect that GNU tar won't work well if random system calls fail with errno == EINTR, and this change would help insulate tar from that issue, on platforms that support SA_RESTART. This change affects tar's behavior only if the --totals=SIG option is specified, for some signal SIG. diff --git a/src/tar.c b/src/tar.c index 6d37044..f0d8f5b 100644 --- a/src/tar.c +++ b/src/tar.c @@ -956,10 +956,13 @@ static void stat_on_signal (int signo) { #ifdef HAVE_SIGACTION +# ifndef SA_RESTART +# define SA_RESTART 0 +# endif struct sigaction act; act.sa_handler = sigstat; sigemptyset (&act.sa_mask); - act.sa_flags = 0; + act.sa_flags = SA_RESTART; sigaction (signo, &act, NULL); #else signal (signo, sigstat);
|
https://lists.gnu.org/archive/html/bug-tar/2011-09/msg00088.html
|
CC-MAIN-2019-35
|
refinedweb
| 129
| 77.53
|
Odoo Help
This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.
How to run python function when editing a product
Hello,
I'm trying to run a python function when I click on "Save" in a product page but I don't know what is the function I have to inherit from product.product or product.template.
Please, help me ! Thank you in advance.
def create() if it is a new record
def write() if it is an existing record.
You can find nice informations in the documentation of odoo about the ORM :
product.product if you are in a product variant view
product.template if you are on a product view.
You can find easily in the url the active_model.
When you click on "Save" button below two method you have to inherit...
def create(self, cr, uid, ids, context=None):
--
--
res = super(sale_order, self).create(cr, uid, ids, context=None)
--
--
return res
or
def write(self, cr, uid, ids,vals, context=None):
--
--
res = super(sale_order, self).create(cr, uid, ids, vals,context=None)
--
--!
|
https://www.odoo.com/forum/help-1/question/how-to-run-python-function-when-editing-a-product-103734
|
CC-MAIN-2016-44
|
refinedweb
| 196
| 76.52
|
Given a string of digits, I am trying to insert a - in-between odd numbers and a * in between even numbers. The solution below is very convoluted, and I was wondering if I could do something like this:
"99946".gsub(/[13579][13579]/) {|s,x| s+"-"+x}
def DashInsertII(num)
num = num.chars.map(&:to_i)
groups = num.slice_when {|x,y| x.odd? && y.even? || x.even? && y.odd?}.to_a
puts groups.to_s
groups.map! do |array|
if array[0].odd?
array.join(" ").gsub(" ", "-")
else
array.join(" ").gsub(" ", "*")
end
end
d = %w{- *}
puts groups.join.chars.to_s
groups = groups.join.chars
# Have to account for 0 because Coderbyte thinks 0 is neither even nor odd, which is false.
groups.each_with_index do |char,index|
if d.include? char
if (groups[index-1] == "0" || groups[index+1] == "0")
groups.delete_at(index)
end
end
end
groups.join
end
This will work for you:
"99946".gsub(/[13579]+/) {|s| s.split("").join("-") } # => "9-9-946"
It's roughly similar to what you tried. It captures multiple consecutive odd digits, and uses the gsub block to split and then join them separated by the "-".
This will include both solutions working together:
"99946".gsub(/[13579]+/) {|s| s.split("").join("-") }.gsub(/[02468]+/) {|s| s.split("").join("*") } # => "9-9-94*6"
|
https://codedump.io/share/Y1eW35b6mxkC/1/ruby-gsub-match-concatenation
|
CC-MAIN-2017-13
|
refinedweb
| 210
| 72.42
|
The competition
Who can enter?
All registered members of Uncyclopedia are encouraged to enter (so long as they are not judging that category). You may enter only once for every category for which you are eligible. If you wish to collaborate with other eligible contestants, you may do so, but that will count as your one entry in the category. Collaborative efforts will have to decide who is the "team leader," who will house the article on his/her name space and recieve the prize if your collaboration wins, at which point (it is assumed) s/he will distribute the winnings among the other members of the team. If a user wishes to enter in more than one category (for which s/he is eligable), s/he is welcome to do so, either collaborating or alone, but may only enter one per category. Two collaborations do not count as one entry, they count as two.
What is the Poo Lit Surprise?
A writing competition held twice a year. The winners recieve Poet Lowrate awards, an award of $25, and the hatred and jealousy of the rest of the entire Uncyclopedia community.
When is the PLS !!! going to be held?
- From Jan 14 - Jan 27, entries will be accepted. (Note: ARTICLES POSTED TO UNCYCLOPEDIA BEFORE JAN 14 WILL NOT BE ELIGIBLE TO WIN)
- From Jan 28 - Feb. 10, entries will be locked and judged.
- From Feb. 11 - Feb. 17, winners will be announced, honorable mentions will be moved into the main space, and all entries will be unlocked.
- Feb. 18, we will all get on with our lives.
Where should I put my entry?
The article should be place on your namespace. Between Jan 14 - and Jan 27, you should put a link to your article on the "entry" page. You should post a link to your page and sign as you would a forum post or vote. It should look somewhat like this:
- User:Bradaphraser/yahoo--<<
>> 21:03, 17 December 2006 (UTC)
or, in the case of collaboration:
Why are we doing this?
The PLS is a competition designed to jump-start writing quality at Uncyclopedia. After the previous two competitions, a significant number of featured articles for the following month were from the PLS, and it could be argued that the overall quality of featured articles increased. Aside from that, it's nice to get money for something that generally is solely done on a volunteer basis.
How are you gentlemen?
All your base are belong to us. You are already on the way to destruction. You have no chance to survive, make your time. HAHAHAHA!
(Translation: Plagiarism is bad. If we discover your work is not original, you will be disqualified.. Thank you for understanding.)
Judges
Best Article
Note: All users may enter this category (except for the judges, of course)
Best Article by a N00b
Note: All users who's first contribution is after November 10, 2006 may enter this category.
Best Pictures
Note: All users may enter this category (except the judges). The entries will primarily be judged on how the pictures add to the humor of the page.
Best Rewrite
Note: All users may enter this category (except for the judges). Entries must be based on an article that is already on Uncyclopedia and will remain so through the PLS competition (so entrants are encouraged to choose the articles they rewrite wisely). Entries will be judged on both final quality and improvement over original article's quality.
Need Ideas?
Try UN:VITAL, Special:Wantedpages, Category:Rewrite, Uncyclopedia:Requested Articles, or Image Request, depending on what category you're entering.
Current Entries
Don't post stuff here yet, as anything posted before Jan. 14 will not be eligible to win diddly squat.
|
http://uncyclopedia.wikia.com/wiki/Uncyclopedia:Poo_Lit_Surprise?diff=next&oldid=1025823
|
CC-MAIN-2014-52
|
refinedweb
| 626
| 64.81
|
Save multiple matplotlib figures in single PDF file – Python
In this tutorial, we will look into how multiple plots can be saved in a single pdf file. In many cases, we require our output to be in a particular format, which we can easily obtain using the following way in Python.
Firstly we will import the required libraries for performing this task.
import pandas as pd from matplotlib import pyplot as pplot import seaborn as sns
After importing the required libraries we will insert the CSV file, here I have provided the link to the CSV file which contains the data set that I want to use for performing this task.
dataframe=pd.read_csv("E:\M.PLAN\Code Speedy\PT-OD-Survey .csv")
After loading the data I have displayed the first n rows of the dataset, which by default will show us the first 5 rows.
dataframe.head()
Here firstly for plotting the data on a graph we need to specify the size of the graph. Here the size of the graph is shown by specifying the length of the x and y-axis. After specifying the size we will plot the subplots. Using the subplot function we will first specify the rows and columns that we need to plot and then the order of the plot. After that, we will be using the savefig function to save the plots in a single pdf. Here we can also specify other file formats using the savefig function. The output displayed here is the pdf we got after saving the plot.
pplot.figure(figsize=(10,7)) pplot.subplot(1,2,1) sns.countplot('Mode used for Egress',hue='Sex', data=dataframe) pplot.subplot(1,2,2) sns.countplot('Mode used for Egress',hue='Income per Month (Rs)', data=dataframe) pplot.savefig('Practice.pdf')
You can also read:
|
https://www.codespeedy.com/save-multiple-matplotlib-figures-in-single-pdf-file-python/
|
CC-MAIN-2021-43
|
refinedweb
| 306
| 61.67
|
On Thu 3 May 2007 09:30, Greg Ungerer pondered:> Robin Getz wrote:> >.Put the patch back, since I added some new cc' > diff -Naur linux-2.6.21/fs/namei.c linux-2.6.21-uc0/fs/namei.c > --- linux-2.6.21/fs/namei.c 2007-05-01 17:12:53.000000000 +1000 > +++ linux-2.6.21-uc0/fs/namei.c 2007-05-01 17:16:18.000000000 +1000 > @@ -120,12 +120,14 @@ > int retval; > unsigned long len = PATH_MAX; > > +#ifdef CONFIG_MMU > if (!segment_eq(get_fs(), KERNEL_DS)) { > if ((unsigned long) filename >= TASK_SIZE) > return -EFAULT; > if (TASK_SIZE - (unsigned long) filename < PATH_MAX) > len = TASK_SIZE - (unsigned long) filename; > } > +#endif > > retval = strncpy_from_user(page, filename, len); > if (retval > 0) {> >>>> >>>)>> Probably too:>> asm-sh/processor.h:#define TASK_SIZE 0x7c000000UL>> which has some parts with MMU.>> There have been others out of tree that have it like this to.>> > I'm happy to learn we are doing something wrong, but I think that we just> > copied the arm/frv setup.>> That is one way to handle it. Have you followed all the other> uses of TASK_SIZE and verified it is not a problem?No, I assumed that Russell/David were smarter than we were, and that doing so would not be a problem :)Not looking at ./arch or ./include TASK_SIZE looks like it is only used in fs/hugetlbfs/inode.cfs/binfmt_elf.cfs/namespace.cfs/binfmt_aout.cfs/namei.ckernel/kexec.cmm/mremap.cmm/mempolicy.cmm/memory.c mm/nommu.c mm/mmap.cI poked through some, and from first glance, it mostly looked OK with setting TASK_SIZE to CONFIG_DRAM_SIZE or memory_end.-Robin-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
|
https://lkml.org/lkml/2007/5/4/296
|
CC-MAIN-2016-26
|
refinedweb
| 293
| 58.69
|
We. Although the post is a bit long, I hope you’ll be pleasantly surprised by how uncharacteristically simple it is going to be
Traditionally, the identity features of our libraries are mainly projections of protocol artifacts in CLR types. Starting with the venerable Web Services Enhancements, going through WCF to WIF, you’ll find types representing tokens, headers, keys, crypto operations, messages, policies and so on. The tooling we provide protects you from having to deal with this level of detail when performing the most common tasks (good example here), but if you want to code directly against the OM there is no way around it. Sometimes that’s exactly what you want, for example when you want full control over fine grained details on how the library handles authentication. Heck, it is even fairly common to skip the library altogether and code directly against endpoints, especially now that authentications protocols are getting simpler and simpler.
Some other time, though, you don’t really feel like savoring the experience of coding the authentication logic and just want to get the auth work out of your way ASAP and move on with developing your app’s functionality. In those cases, the same knobs and switches that make fine grained control possible will likely seem like noise to you, making harder to choose what to use and how.
With AAL we are trying something new. We considered some of the common tasks that developers need to perform when handling authentication; we thought about what we can reasonably expect a developers knows and understand of his scenario, without assuming deep protocol knowledge; finally, we made the simplifying assumption that most of the scenario details are captured and maintained in a Windows Azure AD tenant. Building on those considerations, we created an object model that – I’ll go out on a limb here - is significantly simpler than anything we have ever done in this space.
Let’s take a look about the simplest model a developer might have in his head to represent a client application which needs to securely invoke a service and relying on one identity as a service offering like Windows Azure AD.
…and that’s pretty much it. When using the current API, in order to implement that scenario developers must achieve a much deeper understanding of the details of the solution: for example, to implement the client scenario from scratch one developer would need to understand the concepts covered in a lengthy post, implement it in details, create UI elements to integrate it in your app’s experience, and so on.
On the server side, developers of services might go through a fairly similar thought process:
Wouldn’t it be great if this level of knowledge would be enough to make the scenario work? Hence, our challenge: how to enable a developer to express in code what he or she knows about the scenario and make it work without requiring to go any deeper than that? Also, can we do that without relying on tooling?
If you are in a hurry and care more about what AAL can do for you than how it works, here there are some spoilers for you: we’ll resume the deep dive in a moment.
The Windows Azure Authentication Library is meant to help rich client developers and API authors. In essence, the Windows Azure Authentication Library helps your rich client applications to obtain a token from Windows Azure Active Directory; and it helps you to tell if a token is actually from Windows Azure Active Directory. Here there are some practical examples. With AAL you can:
Those are certainly not all the things you might want to do with rich clients and API, but we believe that’s a solid start: in my experience, those scenarios take on the fat part of the Pareto principle. We are looking into adding new scenarios in the future, and you can steer that with your feedback. All of the things I just listed are perfectly achievable without AAL, as long as you are willing to work at the protocol level or with general purpose libraries: it will simply require you to work much harder.
The main idea behind AAL is very simple. If in your scenario there is a Windows Azure AD tenant somewhere, chances are that it already contains most of the things that describe all the important moving parts in your solution and how they relate to each other. It knows about services, and the kind of tokens they accept; the identity providers that the service trusts; the protocols they support, and the exact endpoints at which they listen for requests; and so on. In a traditional general-purpose protocol library, you need to first learn about all those facts by yourself; then, you are supposed to feed that info to the library. With AAL you don’t need to do that: rather, you start by telling to AAL which Windows Azure tenant knows about the service you want to invoke.
Once you have that, you can ask directly to the Windows Azure AD tenant to get for you a token for the service you want to invoke. If you already know something more about your scenario, such as which identity provider you want to use or even the user credentials, you can feed that info in AAL; but even if all you know is the identifier of the service you want to call, AAL will help the end user to figure out how to authenticate and will deliver back to your code the access token you need.
Let’s get more concrete. The Windows Azure Authentication Library developer preview is a single assembly, Microsoft.WindowsAzure.ActiveDirectory.Authentication.dll,
It contains both features you would use in native (rich client) applications and features you’d use on the service side. It offers a minimalistic collection of classes, which in turn feature the absolute essential programming surface for accomplishing a small, well defined set of common tasks.
Believe it or not, if you exclude stuff like enums and exception classes most of AAL classes are depicted in the diagram below.
Pretty small, eh? And the best thing is that most of the time you are going to work with just two classes, AuthenticationContext and AssertionCredential, and just a handful of methods.
Let’s start with the client. AuthenticationContext is what you use for identifying the Windows Azure AD tenant that knows about your target service. Once initialized, you can use its Acquirexxx methods to obtain a token for the target service. Occasionally you’ll do so by feeding in an instance of one class in the Credential hierarchy (more details in the scenario section). Upon successful authentication, Acquirexxx will return an instance of AssertionCredential, which contains the access token for the target service as returned by Windows Azure AD. At that point, it is up to you to decide how to use it: if you want to use OAuth2 AssertionCredential offers a nice method CreateAuthorizationHeader, which will create a string of the form “bearer …” ready to be put in the HTTP Authorize header; if you want to use any other protocol, you can get the raw bits of the token directly from AssertionCredential and use them according to whatever protocol schema you deem most appropriate. Want to see that in code? There you go:
1: AuthenticationContext _authContext =
2: new AuthenticationContext("");
3: AssertionCredential theToken =
4: _authContext.AcquireUserCredentialUsingUI("urn:InteractiveAuthentication");
5:
6: HttpWebRequest request =
7: WebRequest.Create("") as HttpWebRequest;
8: request.Method = "GET";
9: request.Headers["Authorization"] = theToken.CreateAuthorizationHeader();
10: request.ContentType = "application/json";
11: HttpWebResponse response = request.GetResponse() as HttpWebResponse
There are only 3 lines of AAL code here, I just had to break them down to fit the silly theme of this blog (I’ll have to change it one of these days).
That’s all there is to do on the client! Of course I am looking forward to hear your feedback about whether this fits the bill in term of ease of use, however here there’s why I am optimistic about this being actually a pretty usable solution:
That’s right! The concepts exposed by the object model live at the same level of abstraction you can expect from a developer without domain-specific knowledge; and thanks to the Identity as a Service approach, we can operate approximately at that level and still get things done without having to leak the abstraction.
Before moving to describe how AAL tackles the service side, I’d like to add a couple of forward-looking details:
The service side is, in the best case, even simpler. The task that AAL helps you to perform as services and API author is validating an incoming token and, upon successful authentication, provide you with a representation of the user. Once again, you start by specifying which Windows Azure AD tenant is responsible for issuing tokens for your service, by initializing an AuthenticationContext. Done that, the absolute minimum extra info you need to provide is the identifier of your service: you need to ensure that the request was really intended for you. You can’t get that automatically form the tenant because the tenant itself might be protecting many different services at the same time, and cannot know which specific service you are working on right now. The good news is that, in the best case, now you already have all you need to validate requests to your service. In code:
1: var authenticationContext =
2: new AuthenticationContext("");
3: authenticationContext.Options.Audiences.Add(
4: "urn:InteractiveAuthentication"});
5: Thread.CurrentPrincipal =
6: authenticationContext.AcceptToken(token);
Once again, just three lines broken in 2 for formatting purposes. Details:
Wait, did I say ClaimsPrincipal? Yes I did. On the service side AAL represents identities as ClaimsIdentity, just like WIF. In fact, the developer preview has a dependency on WIF 1.0 runtime (though if you only develop on the client you might never realize it, given that the only type from Microsoft.IdentityModel instantiated by AAL is exactly for the claims principal.
At this point I should raise that the way in which the AAL developer preview handles the service side of scenarios does not precisely reflect where we want to be going forward. To be more specific: we are absolutely convinced that we need to deliver on the ease of use and simplicity you see here, which is why you are getting this feature in the preview today. However we would like to be able to release service side features and client side features in independence, and reduce as much as we can interdependencies that might make things more difficult for you: which is why moving forward you might see us delivering service side features as WIF extensions, and keep AAL as a client-only deliverable.
As you might have guessed, achieving this level of simplicity comes with some tradeoffs. One such tradeoff – which you might find unusual if you are an identity expert and used to work with protocol libraries – is the near total absence of extensibility points. We are very serious about usability, and felt that adding extensibility would have made difficult to maintain the abstraction level we achieved and would have degraded the signal/noise ratio in AAL’s API surface. Luckily, if you want something that AAL does not offer out of the box you are anything but stuck. In fact, you have many options:
Finally, in the future you’ll have one more option. We are planning to release future drops of AAL under an open source license, which will allow you to fork and tweak the code as needed.
At its heart, the developer preview of AAL is written in native code. Microsoft.WindowsAzure.ActiveDirectory.Authentication is a mixed mode assembly, compiled for a specific “bitness”: that’s why AAL comes in two NuGets, in x86 and x64 flavors.That will require some attention when choosing which package is right for your application, your development environment and whether you need to switch package before deploying to machines with different architectures. Also, that means that wherever you go you’ll need to bring with you the VC runtime.
In the developer preview AAL has a native core because it shares some code with other libraries that are being used for claims-enabling other products: however that’s only a temporary situation, future drops of AAL will be fully managed and all the constraints mentioned earlier will disappear.
One last thing on the object model. If by any chance you read the 22 printed pages tome I wrote when we first released the Windows Azure AD developer preview, you already know that right now there are differences in how ACS namespaces and Directory tenant operate: available identity providers, available endpoints, format used for specifying realms and issuers, and so on. I am very happy to say that AAL uses the exact same object model to work with both tenant types: the only differences are in the strings that you’ll use for representing the tenant itself, the target service realm, and so on. You can easily see thins for yourself: the AAL developer preview samples come with instructions which show how you can point the solution to work with an ACS namespace or a directory tenant, and that does not require any AAL code changes.
That said, there are still differences in term of capabilities that will somewhat surface through your application’s behavior: for example, a rich client targeting a service which trusts a directory tenant will only be able to authenticate against directory tenants and won’t have access to the IPs that are available on ACS.
The good news is that the capabilities of the two tenant types are converging, and that you can handle the interim directly in your code (for example by creating more than one AuthenticationContext and connecting to multiple tenants of different types)
Here I’d like to give you a hint of the main scenarios we are demonstrating in the AAL samples on MSDN. Every sample comes with detailed readmes, and I’ll come back to the topic in the next days; hence I won’t get too deep. Also, I’ll concentrate on the client (as in requestor) side of the scenario as it is the newest. I’ll talk of the service side in more details in future posts.
Here there’s a succinct decision diagram which illustrates pretty much all the main ways you can use AAL to code authentication for a client application:
The next three sections will look at the three branches, breadth first.
If you want to invoke your target service as the interactive user of your application, but you have no direct knowledge of their credentials or even of which identity provider they should authenticate to, then you are on the red branch of the flowchart. This also happens to be the case I used for explaining the object model, so you know almost everything about this flow already although you are still missing a very important piece: what exactly was shown to the user during the call AcquireUserCredentialUsingUI?
In what we sometimes call the interactive mode, AAL pops out a dialog from the calling application. That dialog is used for rendering the list of identity providers that Windows Azure AD knows are suitable for accessing the target service. The flow in the figure shows two possible authentication experiences, one with a local ADFS and the other thru Google, which are fully driven by the end user’s choices. From the developer perspective, that’s still just one line of code. The use of a browser grants incredible flexibility to all the parties involved. For example, the identity providers can decide to change their way of gathering credentials or add extra consent steps: thanks to this approach they are free to make those changes available instantly to all their clients, without pushing out updates if their experience would be handled by a native UI. If you want to know more about the advantages of this approach, read the intro of this.
FI you want a 20,000ft view, the general arch of this scenario looks like the following:
The flow is pretty straightforward. The only caveat in the preview is that you either use an ACS namespace (which give you all the usual IPs but not directory tenants) or a directory tenant (which gives you the exact opposite). For example, the experience for one directory tenant would look like something of this find:
The sample showing this scenario in action is here. It is pre-provisioned to use an ACS namespace, but there are all the instructions you need to point it to a directory tenant if you want to.
If you are still accessing the target service as your user, but this time you do have access to the user credentials, you are in the green branch of the flowchart.
The scenario always starts with creating the AuthenticationContext; however it is then followed by creating a CredentialObject of the right time, that is to say a UsernamePasswordCredential or a KerberosCredential. That credential must be scoped to the identity provider that is competent to validate it; however you don’t need to know the exact endpoint, you just need to know the domain that is being used to represent that IP in ACS. Once you created that Credential, you pass it to the AutenticationContext in the AcquireToken, together with the target service realm as in the interactive case. From that point on, it’s business as usual. Diagram:
You’ll occasionally hear me referring to this scenario as the “non-interactive” one, because AAL itself does not drive any user experience. Of course your app can be interactive, for example by showing a dialog of your own making which gathers username and password, hence this definition is confusing and I am trying to stop using it; however I just know I will occasionally use it so I prepared you just in case
The sample showing this scenario is here.
Now, who says that in order to be a client one has to run on a client? There are many scenarios in a server side process - say a long running process polling some service – which are clients of other services. That’s the orange branch of the decision flowchart. Operatively, this is exactly the same as the scenario we just described: the only difference is that in this case the client application does not invoke a service as a user, but as itself. That requires the use of specific kind of credentials, as established by service identities (for ACS tenants) and service principals (for directory tenants) but modulo the types the drill is exactly the same,
Our sample demonstrating this scenario is here. The solution has some moving parts which deserve a closer look, please make sure to read the readme and if you still have questions I’ll do a blog post just on it.
Interestingly, the Graph API in itself is an excellent example of server to server authentication. In fact, few days ago we got together with Ed and updated his sample to use AAL instead of custom protocol code: we basically ended up saving almost 700 lines of code that made my day!
Well, for an introductory post I’d say we covered a lot of ground! We’ll keep talking about AAL: here I just mentioned the main cases, but there are few others that albeit less common I believe will be interesting to touch. Also, here I almost totally neglected the service side and that definitely needs fixing!
For the time being, I’d encourage you to check out the resources in the developer preview, read the docs in MSDN and especially hit the Windows Azure AD forums with lots and lots of feedback. We are trying something new here, and your feedback is especially important. Thanks in advance and happy AAL coding!
Great work Vittorrio !! This makes ACS a whole lot simpler.
It will save me a lot of work if this will be running on Windows Phone 7 too. But as I read through the deepdive the word 'Phone' is not mentioned and the NuGet AAL won't install on a Windows Phone project. Can you comment on this?
Richard.
Great article. But any inputs on using this library on windows 7 phone?
|
http://blogs.msdn.com/b/vbertocci/archive/2012/08/01/windows-azure-authentication-library-a-deep-dive.aspx?Redirected=true
|
CC-MAIN-2015-06
|
refinedweb
| 3,408
| 54.76
|
#include <SDKsound.h>
That's the way C++ works :) The .h files define the interface while the .cpp implement it. The separation is there as compiling large chunks of code can take quite some time (as compared to languages like C#). Technically .cpp can be included just like .h files but this might result in global variable clashes and not really worth it anyway.
Rather than trying to get all of this to work manually, there is an easier way. Start the DirectX Sample Brower application. Scroll down to the Empty Project sample. Click "Install Project". You will be prompted for a name for your project. It will then generate a project complete with all of the files you need to use DXUT. The SDKsound* files are actually installed as DXUTsound*, but the classes are the same.
If you do that, you won't need to mess around with trying to get all the right .h/.cpp files into your project and you should be able to just compile and run the stub application. Then you can add whatever code you want in the appropriate stubs and away you go.
I just followed the instructions I gave you and I was able to successfully compile and run the project using both VS 2005 and VC++ 2008 Express. So, there appears to be an issue with your configuration.
The reason you can't jusst link to SDKsound with #include <SDKsound.h> is because #include doesn't "link" to anything. It just provides declarations and nothing else. All of the classes declared in SDKsound.h are defined (implemented) in SDKsound.cpp. So, while any of your source files that need to use SDKsound classes need to #include the header file, you still have to include the implementation of those classes (in the form of SDKsound.cpp) in your project.
This is further complicated by the fact that SDKsound has other SDK/DXUT dependencies. So, once you've added SDKsound.h/SDKsound.cpp to your project, you then find that you are missing some other .h/.cpp pair. That's why the EmptyProject template is included. It takes care of setting all of that up so you don't have to.
As for DirectSound bugging you, your fight isn't with DirectSound. Your fight is with DXUT.
David Hunt:there appears to be an issue with your configuration.
David Hunt:As for DirectSound bugging you, your fight isn't with DirectSound. Your fight is with DXUT.
|
http://forums.xna.com/59970/ShowThread.aspx
|
crawl-001
|
refinedweb
| 413
| 77.03
|
HTML::FormsDj - a web forms module the django way
use HTML::FormsDj; use Data::FormValidator; # a custom DFV constraint. You may also use one # of the supplied ones of Data::FormValidator sub valid_string { return sub { my $dfv = shift; $dfv->name_this('valid_string'); my $val = $dfv->get_current_constraint_value(); return $val =~ /^[a-zA-Z0-9\-\._ ]{4,}$/; } } # our route, we act on GET and POST requests any '/addbook' => sub { my $form = new HTML::FormsDj( # the form, we maintain 2 form variables, title and author field => { title => { type => 'text', validate => valid_string(), required => 1, }, author => { type => 'text', validate => valid_string(), required => 1, }, }, name => 'registerform' ); if ( request->method() eq "POST" ) { # a POST request, fetch the raw input and pass it to the form my %input = params; # "clean" the data, which means to validate it my %clean = $form->cleandata(%input); if ($form->clean() ) { # validation were successfull, so save the data # you'll have to put your own way of data saving # here of course &savebook($clean{title}, $clean{author}); redirect '/booklist'; } else { # nope, something were invalid, put the user # back to the form. his input will be preserved return template 'addbook', { form => $form }; } } else { # a GET request, so just present the empty form template 'addbook', { form => $form }; } };
In your template (views/addbook.tt):
<form name="addbook" method="post" action="/addbook"> <% form.as_p %> <input type="submit" name="submit" value="Add Book"/> </form>
That's it. Here's the output:
<form name="addbook" method="post" action="/addbook"> <p class="formfield" id="id_formfield_author"> <label for="id_formfield_author_input">Author</label> <input type="text" id="id_formfield_author_input" name="author" value=""/> <span class="fielderror" id="id_formfield_author_message"></span> </p> <p class="formfield" id="id_formfield_title"> <label for="id_formfield_title_input">Title</label> <input type="text" id="id_formfield_title_input" name="title" value=""/> <span class="fielderror" id="id_formfield_title_message"></span> </p> <input type="submit" name="submit" value="Add Book"/> </form>
The HTML::FormsDj module provides a comfortable way to maintain HTML form input. Its main use is for Dancer but can be used with other perl application servers as well, since it doesn't require Dancer to run at all.
HTML::FormsDj aims to behave as much as Django's Forms system with the excpetion to do it the perl way and without a save feature.
It works as follows: You create a new form and tell it which form variables it has to maintain and how to validate them. In your template you can then put out the generated form. HTML::FormsDj will put back user input into the form if some of the data were invalid. This way your user doesn't have to re-enter anything.
You can tweak the behavior and output as much as possible. You can add your own CSS classes, CSS id's, error messages and so on.
To create a form, you have to instanciate an HTML::FormsDj object. Any parameters have to be passed as a hash (of hashes) to new().
The most important parameter is the field hash. Here you tell the form, which form variables it has to maintain for you, of which type they are and how to validate them.
my $form = new HTML::FormsDj( field => { variablename => { type => 'text', validate => some_validator_func(), required => 1, }, anothervariable => { # .. and so on } } );
A variable can have the following types:
text: onelined text fields
password: same as above but for passwords
textarea: multilined text fields (for blobs etc)
choice: a select list
option: a checkbox option list
The validate parameter requires a Data::FormValidator constraint function. Refer to the documentation of this module, how this works. HTML::FormsDj will just pass this constraint to Data::FormValidator.
The required parameter tells the form, if the variable is - obviously - required or not.
As you may already have realized, we are missing something here. A form variable on a web page requires a label. And what about styling?
Enter meta.
Using the meta hash parameter to new() you can tell HTML::FormsDj how to do the mentioned things above and more.
Ok, so let's return to our book example from above and add some meta configuration to it:
my $form = new HTML::FormsDj( field => { title => { type => 'text', validate => valid_string(), required => 1, }, author => { type => 'text', validate => valid_string(), required => 1, }, }, name => 'registerform', meta => { fields => [ { field => 'title', label => 'Enter a book title', message => 'A book title must be at least 4 characters long', classes => [ qw(titlefield) ], }, { field => 'author', label => 'Enter an author name', message => 'A book title must be at least 4 characters long', classes => [ qw(authorfield) ], }, ] } );
So, what do we have here? meta is a hashref which contains a hashkey fields which points to an arrayref, which consists of a list of hashrefs.
Easy to understand, isn't it?
If you disagree here - well, please hang on. I'll explain it deeper :)
Ok, to put it simply: meta is a hash (because in the future there maybe more meta parameters available) with one element fields which points to a list of fields.
Please note: the order of appearance of fields does matter!
Fields will be displayed in the generated HTML output in this order.
Each field must have a field parameter, which is the name of the field and has to correspond to the form variable name of the field you defined previously in new().
All other parameters are optional. If you omit them, or if you omit the whole meta parameter, HTML::FormsDj will generate it itself using reasonable defaults based on the variable names.
Parameters of a field hash are:
As mentioned above, the name of the form variable.
A label which will be put before the input field.
A message, which will be shown if there are some errors or if the field were missing.
A list (arrayref) of CSS class names to apply to the field.
A CSS id you may assign to the field.
Sometimes a plain list of fields may not be sufficient, especially if you have to render a large input form. You may use a fieldset instead of a field to better organize the display of the form.
Again, using the example used above, you could write:
my $form = new HTML::FormsDj( field => { title => { type => 'text', validate => valid_string(), required => 1, }, author => { type => 'text', validate => valid_string(), required => 1, }, }, name => 'registerform', meta => { fieldsets => [ { name => 'titleset', description => 'Enter book title data here', legend => 'Book Title', fields => [ { field => 'title', label => 'Enter a book title', message => 'A book title must be at least 4 characters long', classes => [ qw(titlefield) ], }, ] }, { name => 'authorset', description => 'Enter book author data here', legend => 'Book Author', fields => [ { field => 'author', label => 'Enter an author name', message => 'A book title must be at least 4 characters long', classes => [ qw(authorfield) ], }, ] }, ] } );
Ok, this looks a little bit more complicated. Essentially there is just one more level in the definition. A fieldset is just a list of groups of fields. It is defined as a list (an arrayref) which contains hashes, one hash per fieldset.
Each fieldset hash consists of some parameters, like a name or a legend plus a list of fields, which is exactly defined as in the meta parameter fields as seen above.
The output of the form is just devided into fieldsets, which is a HTML tag as well. Each fieldset will have a title, the legend parameter, an (optional) description and a name.
This is the very same as the META subclass in django forms is working.
Please note: you cannot mix a field list and fieldsets!
Only one of the two is possible.
If you omit the meta parameter at all, HTML::FormsDj will always generate a plain field list.
IN some cases you'll need to put some defaults for form variables, eg. for choices or options.
You can do this by adding a default parameter to the field definition in your meta hash.
For text type variables this can just be a scalar. For choices and options you can supply a hash- or an array reference.
An example for a choice:
# other fields , { field => 'redirect', label => 'Redirect to page', default => [ { value => 1, label => '/home' }, { value => 2, label => '/profile' } ], } , # other fields
In this example we've a choice which contains two values for the generated select form tag. Here we've used an array, which is the preferred way since this preserves order.
However, you might also supply a hash:
# other fields , { field => 'redirect', label => 'Redirect to page', default => { 1 => '/home', 2 => '/profile' } } , # other fields
To display the form, you have a couple of choices.
The easiest way is to use the as_p method. Usually you'll call this method from your template.
In the Dancer world you have to do it this way:
Pass the form to the template:
template 'addbook', { form => $form }
And in your template 'addbook.tt' you call as_p:
<% form.as_p %>
You have to take care of the HTML form tag yourself. A complete HTML form would look like this:
<form name="addbook" method="post" action="/addbook"> <% form.as_p %> <input type="submit" name="submit" value="Add Book"/> </form>
As you can see, you have to put the submit button yourself as well. This is because some people might add Javascript to the button or don't want to use such a button at all.
This display method generates a HTML table. Calling it works the very same as as_p:
<% form.as_table %>
Instead of letting HTML::FormsDj do the rendering of the form, you may render it in your template yourself. You can access the fields (or fieldsets containing fields, if any) from a forms object from a template.
Let's render the form for our book author example manually:
<form name="addbook" method="post" action="/addbook"> <% FOREACH field = form.fields %> <p id="<% form.id %>"> <% field.label %>: <input type="text" name="<% field.field %>" value="<% field.value %>"/> <span style="color: red"><% form.message %></span> <br/> </p> <% END %> <input type="submit" name="submit" value="Add Book"/> </form>
That's pretty easy. Of course you need to check for the field type in your template, because different field types require different html output. You can check for field.type, eg:
<% IF field.type == 'textarea' %> <textarea name="<% field.field %>"><% field.value %></textarea> <% END %>
This is in fact no display method, it rather just returns the normalized meta hash and NO HTML code. You can use this to generate the HTML yourself, perhaps if the provided methods here are not sufficient for you or if you have to output something different than HTML (e.g. JSON or XML).
The structure returned will look like this (based on our example above with some data filled in by a user):
{ 'fields' => [ { 'classes' => [ 'formfield' ], 'value' => 'Neal Stephenson', 'default' => '', 'type' => 'text', 'id' => 'id_formfield_author', 'label' => 'Author', 'field' => 'author' }, { 'classes' => [ 'formfield' ], 'value' => 'Anathem', 'default' => '', 'type' => 'text', 'id' => 'id_formfield_title', 'label' => 'Title', 'field' => 'title' } ] };
Or, if it contains validation errors:
{ 'fields' => [ { 'classes' => [ 'formfield' ], 'value' => '', 'default' => '', 'type' => 'text', 'id' => 'id_formfield_author', 'label' => 'Author', 'field' => 'author', 'message' => 'missing input', 'error' => 'missing input', }, { 'classes' => [ 'formfield' ], 'value' => 'Ana', 'default' => '', 'type' => 'text', 'id' => 'id_formfield_title', 'label' => 'Title', 'field' => 'title', 'message' => 'invalid input', 'error' => 'valid_string', } ] };
To validate the user input just fetch the HTTP POST data and pass them to the form. The Dancer way:
my %input = params; my %clean = $form->cleandata(%input);
cleandata now generates based on your configuration Data::FormValidator and calls its check method to let it validate the input data.
It returns a plain perl hash containing the VALID data. This hash maybe incomplete if there were validation errors or required fields were not filled in by the user.
Therefore, you'll have to check if validation were successfull:
Use the method clean to check if validation had errors. It returns a true value if not.
Example:
if ($form->clean() ) { # save the data and tell the user } else { # put the same form back to the user again # so the user has to retry }
Beside the described validation technique you may also supply your own clean() method to the form, which may do additional checks, such as if a user exists in a database or the like.
You can do this by supplying a closure to the clean parameter (not method!) when you instantiate the form.
Example:
my $form = new HTML::FormsDj( .., clean => sub { my (%clean) = @_; my $user = $db->resultset('User')->find({login => $clean{user}}); if($user) { return (0, 'user exists'); } else { return (1, ''); } }, .. );
In this example we're doing exactly this: we check if a user already exists.
The closure will get the %clean hash as a parameter, which contains the clean validated form data.
Note: This closure will only called if all other validations went successfull!
The closure is expected to return a list with two values: true or false and an error message.
The underlying validator module Data::FormValidator supports a couple of attributes which can be used to change its behavior.
You can supply such attributes to the form, which will be handed over to Data::FormValidator, eg:
my $form = new HTML::FormsDj( .., attributes => { filters => ['trim'] }, .. );
The attributes parameter is just a hashref. Everything inside will be supplied to Data::FormValidator::new(). Refer to its documentation which attributes could be used here.
Usually HTML::FormsDj generates the DFV Profile used by the Data::FormValidator::check() method. Sometimes you might want to supply your own, for instance if you need multiple validators per variable or ir you want to modify the messages which will be returned on errors and the like.
You can do this by using the dfv parameter:
my $form = new HTML::FormsDj( .., dfv => {} .. );
Refer to Data::FormValidator#INPUT-PROFILE-SPECIFICATION how to specify/define the dfv profile.
In case you've got supplied a dfv profile, the form will not generate its own and just use the one you supplied and it will not check for errors or if it matches the field hash definition.
This technique is not recommended for the average user.
You can use the form method dumpmeta, which dumps out the META hash, in your template to see what happens:
<% form.dumpmeta %>
Beside errors per field there is also a global error variable which can be put out using the error method:
<% form.error %>
This feature is experimental.
HTML::FormsDj provides CSRF attack protection. Refer to to learn what it is.
To enable CSRF protection, you'll set the csrf parameter to a true value:
my $form = new HTML::FormsDj( .., csrf => 1 .. );
If enabled, the form will generate a unique token for the form based on the field names, some random number and current time.
This token must be set as a COOKIE during the GET request to your form and the very same token has to exist as a HIDDEN VARIABLE in the form.
Since HTML::FormsDj doesn't depend on Dancer (or any other perl app server), you are responsible for setting and retrieving the cookie.
On POST request the value of the cookie must match the value of the hidden variable. If one of them doesn't exist or the two are not the same, clean() returns FALSE. In addition no cleandata will be returned and no validation will be done.
First, enable it using the parameter mentioned above:
my $form = new HTML::FormsDj( .., csrf => 1 .. );
In your route for the GET request set the cookie. You can retrieve the actual cookie value by using the csrfcookie method:
cookie csrftoken => $form->getcsrf, expires => "15 minutes"; template 'addbook', { form => $form };
Put this in your code where you're handling the GET request of the form.
In your code for the POST request, you'll have to retrieve the cookie and tell the form about it. This has to be done BEFORE you call clean:
if ( request->method() eq "POST" ) { my %input = params; $form->csrfcookie(cookie 'csrftoken'); my %clean = $form->cleandata(%input); if ($form->clean() ) { ..
That's it. If you're using as_p or as_table you are done and protected from this kind of attacks.
If you're creating your html form manually, you'll have to put the hidden value into your template this way:
<% form.csrftoken %>
The forms module might not sound as the right place where to do such things. Maybe a Dancer plugin for this would be the better choice to implement such a feature.
However, my idea was, if I am already maintaining forms, why not doing it in a secure way?
I recommend you to read the following documents, which are supplied with Perl:
perlreftut Perl references short introduction perlref Perl references, the rest of the story perldsc Perl data structures intro perllol Perl data structures: arrays of arrays
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See rt.cpan.org for current bugs, if any.
None known.
To debug HTML::FormsDj use the Perl debugger, see perldebug.
HTML::FormsDj depends on the module Data::FormValidator. It can be used with Dancer, but this is no requirement.
T. Linden <tlinden |AT| cpan.org>
0.03
|
http://search.cpan.org/dist/HTML-FormsDj/lib/HTML/FormsDj.pm
|
CC-MAIN-2016-18
|
refinedweb
| 2,797
| 61.46
|
#include <bayesian_motion_filter.h>
#include <bayesian_motion_filter.h>
Collaboration diagram for bj::BayesianMotionFilter:
BayesianMotionFilter implements a bayesian filter that tracks any motions in an image sequence. The measurement input is supposed to be a gray-scale image whose pixel is black when there is no motion and white when the pixel difference between consecutive images is big.
Currently, it supports only the constant position model due to the limitation of computing power.
320
240
10
A constructor.
A destructor.
[inline]
Retrieve the PDF of the belief map.
Retrieve the grid size.
Retrieve the number of grids on the vertical axis.
-1
Initialize a bayesian map.
Retrieve the current error of a measurement model.
Retrieve the current position error of an action model.
Set the error of a measurement model.
Set the position error of an action model.
Apply linear transform on the belief map.
Update the bayesian filter using a measurement.
Retrieve the number of grids on the horizontal axis.
|
http://robotics.usc.edu/~boyoon/bjlib/d1/d33/classbj_1_1BayesianMotionFilter.html
|
CC-MAIN-2018-26
|
refinedweb
| 158
| 53.27
|
How to Redirect to a New URL in Servlet
Servlet is a type of Java programming that allows you to connect to a web server. Servlet can be used to control request and responses to web hosts on your web pages. Servlet uses basic Java code and can be programmed into a web page just as you would Javascript. One of the ways you can use Servlet is to redirect your web page to a new location or automatically move your web page to a new URL.
Instructions
- 1
Open a text editor, such as Notepad or Text Edit. Select "File," then "Save" from the top menu. Save your page with a .html extension, and name it what you want your web page to be called. For instance, if you want the page to have a URL of, call your file "newpage.html."
- 2
Type <html> at the top of the page. Next, type "<script type="text/javascript">". This will indicate that you will be using Javascript.
- 3
Import Java servlet code into your page. Type in:
"import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;"
This will import the code necessary for your page to recognize your URL redirect.
- 4
Insert the redirect code. Type in:
"public class ExampleServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("");
}
}"
Replace "" to the URL you wish to redirect your page to.
- 5
Type in "</script></html>" to indicate that you are finished with your web page. Select "File," then "Save" from the top menu. Upload this page to your web server to have a functional URL redirect.
Tips & Warnings
Servlet URL redirects may not be recognized by search engines and is not recommended for proper SEO.
References
- Photo Credit Hemera Technologies/Photos.com/Getty Images
|
http://www.ehow.com/how_12023070_redirect-new-url-servlet.html
|
crawl-003
|
refinedweb
| 309
| 77.13
|
Orbit is a development framework to create real-time multi-user multi-device applications. Applications can be written with a platform-agnostic API which fits perfectly in your development environment.
Orbit is network-based, so you don’t necessarily need an internet connection, but you do need a way to reach your other devices though the IP protocol. Though it’s highly preferable that you can connect directly (like multiple computers on the same LAN), it was thought to allow complex network configurations. Each user that appears on the network is an object which emits/receives messages, following a classic Observer pattern.
Sample
package aerys.helloworld { import aerys.orbit.Node; import aerys.orbit.Session; import aerys.orbit.log.ConsoleLogger; import aerys.orbit.log.LogLevel; import aerys.orbit.log.Logger; import aerys.orbit.scheme.AttachedMessage; import flash.display.Sprite; import flash.events.Event; public class HelloFlashClient extends Sprite { // Create a node, associated with our generated scheme. private var _node : Node = new Node(new HelloScheme); public function HelloFlashClient() { addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler); } public function addedToStageHandler(event : Event) : void { // Set up the default logger to standard output. Logger.backend = new ConsoleLogger(); // Accept any log message. Verbose. Logger.level = LogLevel.ALL; // Add an endpoint. By default, a node has none. _node.addEndpoint("orbit://localhost:4242"); // Create a session, to dispatch the messages. var session : Session = _node.create(); // Add a handler to detect when the session is attached to the remote node. session.addEventListener(AttachedMessage.ATTACHED, attachedHandler); // Attach the session. Stops on the first successful endpoint. Asynchronous. session.attach(); // Mark the node as ready. _node.start(); } // Define the handler, ActionScript-style. public function attachedHandler(message : AttachedMessage) : void { // Retrieve the Session. There are three ways of doing it: // - Session.current // - (message.target as Session) // - Keep the result of _node.create() in an instance variable var session : Session = Session.current; // Dispatch a custom message to the server. session.dispatchEvent(new HelloMessage("Hey!")); } } }
@as3gamegears Do you know when Orbit is due to release? It doesn’t seem to be released yet!
Orbit
is it possible to make game like counter strike on a LAN without the use of Internet connection. I don’t want to use P2PGameEngine with makes it a must to connect to cirrus. i dont even want to use flash media server. i want a direct connection between two computer on a LAN or a shared network.
I think it is possible to create a Counter Strike like game the way you want using Orbit, but I’m not sure. I didn’t have the change to get my hands on Orbit yet
great framework !
Can you try Orbit framework ? link..
Commercial price ?
Hi manu! I never asked for an Orbit license, so I was not able to try it or check its price. I suggest you to contact Aerys, the company responsible for Orbit.
|
https://www.as3gamegears.com/multiplayer/orbit/
|
CC-MAIN-2021-17
|
refinedweb
| 470
| 53.27
|
Introduction: Scroll a Single LCD Line in From Left or Right
The Liquid Crystal Library has two useful functions scrollDisplayLeft() and scrollDisplayRight(). These functions scroll the whole display. That is, they scroll both lines on a 1602 LCD and all four lines on a 2004 LCD. What we often need is the ability to scroll a single line onto these displays rather than scroll the entire display.
This Instructable provides two additional functions, scrollInFromRight (line to display text on, string to be scrolled) and scrollInFromLeft (line to display text on, string to be scrolled). These two functions which scroll lines into the LCD screen combined with the two functions, scrollLineRight (line to display text on, string to be scrolled) and scrollLineLeft (line to display text on, string to be scrolled) from my earlier Instructable, which presented functions to scroll lines off the screen, gives us several powerful ways to control how text can be presented on, or removed from, an LCD screen.
Step 1: What's Needed
- A 1602 or 2004 LCD standalone display, or LCD shield
-- See note below regarding use of a 2004 LCD display
- An Arduino UNO R3 or clone
- A USB cable to connect the Arduino to a computer
- A half-size, 400 tie points, breadboard
- The Arduino IDE
- An experimental platform (optional, but helpful)
The items required are an LCD screen either 1602 or 2004 [if a 2004 is used, it will work without problems to scroll from the right by changing the lcd.begin() function to reflect that you are now using a 20 character x 4 line display. [To scroll in from the left using a 2004 display, a code rewrite of the function scrollInFromLeft() is necessary]. In addition to an LCD you will need an Arduino UNO or clone, the Arduino IDE, and a USB cable to connect the Arduino to a computer.
An LCD shield can be used instead of the standalone LCD shown here. If that is the case, then the pin assignments for the LCD in the sketch below will need to be changed.
- For the independent 1602 LCD display I used the following pin assignments in my sketches:
// LiquidCrystal (rs, enable, d4, d5, d6, d7)
LiquidCrystal lcd(12,11,5,4,3,2);
and included the Liquid Crystal library LiquidCrystal.h.
- For the LCD shield, I use the following pin assignments in my sketches, and also included the Liquid Crystal library LiquidCrystal.h.
// LiquidCrystal (rs, enable, d4, d5, d6, d7)
LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);
Either route will run the code here, i.e., either a LCD shield or a standalone LCD. A 1602 standalone LCD display was used in this Instructable, but as noted a 1602 shield can be used as well if the different pin assignments are taken into account.
I used an “experimental platform” to connect the Arduino UNO to a half-size, 400 tie points , breadboard. (See an earlier Instructable of mine, “Experimental Platform For the Arduino UNO R3, How To Prepare It For Use “). However, an experimental platform is not needed, although for me it makes connecting the LCD to the UNO much easier and quicker.
The assignments I used for connecting the LCD to the UNO can be seen above.
Step 2: Hookup
The LCD is plugged into a breadboard and then hookup wires are connected from the breadboard to the appropriate pins on the Arduino (see step 2 if you have any questions on the connections I used).
I preferred a standalone LCD for this project rather than a shield as it was more satisfying for me, and allowed me to easily see which pins were available. It also allows me to use a potentiometer which has a knob, rather than a shield’s potentiometer which must be adjusted with a screwdriver.
The standalone LCD requires the use of a separate 10k ohm potentiometer. As noted above, I used one with a knob which has its wiper connected to the third LCD pin (counting from the right with the LCD pins facing you). The potentiometer is used to control the LCD’s contrast. The connections are the same for the 1602 and the 2004. However, the statement lcd.begin(16, 2) needs to be changed in the sketch to lcd.begin(20, 4) to show that our LCD has changed from a 16 character by two line display to a 20 character by four line one.
A look at the photographs attached shows the hookup I used, including the experimental platform, and 10k potentiometer.
Step 3: The Sketch
Just enter the attached sketch into the Arduino IDE. Please keep in mind that the Instructable site often removes all greater than and less than signs and the text between them. Thus, be sure and include the text, #include LiquidCrystal.h and enclose the words LiquidCrystal.h inside greater than and less than symbols.
// Sketch to scroll characters onto an LCD screen
int i = 0;
int j = 0;
int k = 0;
int delayTime2 = 350; // Delay between shifts
void scrollInFromRight (int line, char str1[]) {
// Written by R. Jordan Kreindler June 2016
i = strlen(str1);
for (j = 16; j >= 0; j--) {
lcd.setCursor(0, line);
for (k = 0; k <= 15; k++) {
lcd.print(" "); // Clear line
}
lcd.setCursor(j, line);
lcd.print(str1);
delay(delayTime2);
}
}
void scrollInFromLeft (int line, char str1[]) {
// Written by R. Jordan Kreindler June 2016
i = 40 - strlen(str1);
line = line - 1;
for (j = i; j <= i + 16; j++) {
for (k = 0; k <= 15; k++) {
lcd.print(" "); // Clear line
}
lcd.setCursor(j, line);
lcd.print(str1);
delay(delayTime2);
}
}
void setup() {
Serial.begin(9600);
Serial.println("Starting test ...");
lcd.begin(16, 2);
lcd.clear();
lcd.print("Test Only");
}
void loop() {
lcd.clear();
scrollInFromRight(0, "Line1 From Right");
scrollInFromRight(1, "Line2 From Right");
lcd.clear();
scrollInFromLeft(0, "Line1 From Left.");
scrollInFromLeft(1, "Line2 From Left.");
lcd.clear();
scrollInFromRight(0, "Line1 From Right");
scrollInFromLeft(1, "Line2 From Left.");
lcd.clear();
}
The two functions: scrollInFromRight (line to display text on, string to be scrolled) and scrollInFromLeft (line to display text on, string to be scrolled) can be moved into your sketch to control the lines that get scrolled onto the LCD screen. These functions provide an elegant way to move new text to the screen.
When combined with the two functions in the sketch contained in the Instructable “Scroll a single LCD line out to left or right, How to” the four functions provide elegant ways to scroll text onto and off an LCD display. These functions allow you to scroll text one line at a time, and do not require that the whole display be scrolled as do the functions, scrollDisplayLeft() and scrollDisplayRight().
This scrolling ability allows us to present lines longer that the display is normally capable of showing. That is, for a 1602 display we are not restricted to only 16 characters per line (although only 16 will show at a time), and for a 2004 we are not restricted to 20 characters per line.
As an aside, you may want to adjust the display time between scrolls to match your needs.
Step 4: Afterwards
That's all there is to it. These functions and the two from my previous Instructable can be added to any sketch you have that uses an LCD and displays text. As noted, the ability to use longer lines is a definite benefit that is possible through the use of scrolling.
If you would like to contact me with any questions or for additional information, or to expand my knowledge in the area presented, I can be reached at transiintbox@gmail.com. (please replace the second 'i' with an 'e' to contact me.
Recommendations
We have a be nice policy.
Please be positive and constructive.
Tips
2 Questions
I believe I understand what you would like to do. I will take a look at what you sent and get back to you.
The very best
I looked at your code and it appears you do not have anything after the include statement. In my Instructable paper I noted:
Thus, if you replace the include statement you have, you should have no issue. That is, use
#include <LiquidCrystal.h>
instead of the #include you have that includes no text.
The very best, sorry if there was some confusion. However, the Instructable editor appears to remove all text between < and > signs, as well as the "greater than" and "less than" signs themselves.
Jordan
Hello, I want place my word in row 1 as scrolling text, and row 2 as fixed text, can you explain how about it?
i use this code, but i wrong.
/*
* MONSTER ARDUINO V2 : BASIC SENSOR
* Program Mengontrol Lampu Backlight LCD
*
*/
// library LCD dengan modul I2C
#include
// jumlah kolom dan baris LCD (16x2)
#define LCD_COL 16
#define LCD_ROW 2
// ===== Konfigurasi LCD ===========
// LCD1602 dengan Modul I2C
// Alamat I2C di 0x27
// lcd_Addr, EN, RW, RS, D4, D5, D6, D7, PIN_BACKLIGHT, Pol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
int i = 0;
int j = 0;
int k = 0;
int delayTime2 = 500; // Delay between shifts
void scrollInFromRight (int line, char str1[]) {
i = strlen(str1);
for (j = 40; j >= 16; j--) {
lcd.setCursor(j, line);
lcd.print(str1);; // Clear line
delay(delayTime2);
}
}
void setup() {
// Nyalakan Backlight
lcd.setBacklight(BACKLIGHT_ON);
lcd.begin(16, 2);
Serial.begin(9600);
lcd.clear();
}
void loop() {
{
scrollInFromRight(1, "DAFTAR PENGHUNI KOS KALISEGARA UNNES: ");
}
{
lcd.clear();
lcd.setCursor(0,1);
lcd.print("TONI WIDIYANTO");
delay(1000);
lcd.setCursor(0,1);
lcd.print("JUNANTO ");
delay(1000);
lcd.setCursor(0,1);
lcd.print("ARIS TRIYONO ");
delay(1000);
lcd.setCursor(0,1);
lcd.print("M. TEGUH A. ");
delay(1000);
lcd.setCursor(0,1);
lcd.print("KUSWORO ");
delay(1000);
}
}
4 Comments
And what if you have text longer than 16 symbols, that will just stop at the first position.
The 1602 display buffers text beyond the visible 16 characters displayed on the screen, although not initially presented on the display. That is, there are character positions (buffers) available past those displayed that can be written to and read from.
Nice Instructable! It will be great having the ability to move the display one line at a time.
For learning the 16 pin connector works fine but for projects we like the I2C versions and they only cost about $2 more. The I2C uses only 2 data pins and makes wiring very easy. Well worth it if putting the display in a project box.
FYI- For inserting code use the 'code' option under formatting. It is a little quirky to use but you don't lose any characters. You can see it on our Instructables.
Thank you for your kind comments.
I have not needed to include my displays in project boxes, yet, and find the ability to “plug” LCDs into a breadboard stabilizes them if the appropriate “support feet” are used. See an earlier Instructable of mine, “Stabilize and level a 1602 or 2004 breadboard-mounted LCD display, A simple way to”.
I agree with your thoughts on I2C as it does allow many more pins on an Arduino
to be used when necessary. I also appreciate your comments on posting code. Thanks.
The very best.
|
http://www.instructables.com/id/Scroll-a-Single-LCD-Line-In-How-to/
|
CC-MAIN-2018-09
|
refinedweb
| 1,861
| 70.84
|
Hi guys.
So whenever I try to make a game I run into a problem where a circular dependency occurs between the scene or level holding my game objects and the game objects that need access to the level. I am sure this can be easily solved because my architecture is structured wrong but I just can't seem to think of an efficient solution. I'll roughly show what I have (just the parts that are causing the dependency).
Scene.h
#include "ObjectList.h" class Scene : public EventListener { public: ObjectList objectList; // This holds all the entities that are currently active in a particular scene/level. };
ObjectList.h
#include "Entity" class ObjectList { private: std::vector<Entity*> objectList; };
Entity.h
#include "Scene.h" class Entity : public sf::Sprite, public EventListener { protected: Scene *gameWorld; };
|
http://www.gamedev.net/user/209638-pragmaonce/?tab=topics
|
CC-MAIN-2015-40
|
refinedweb
| 132
| 56.15
|
I have a CW11 project for a MC9S08QE processor using ProcessorExpert.
The significant components are SPI master (SM1) and a Free counter (FC1).
The projet comprises four files, main.c, main.h, events.c and events.h. The only include statements are
#include "main.h" in main.c and
#include "events.h" in events.c
When I declare a variable in one .h file and declare it as external in the other I get the error:
ERROR L1818: Symbol 24 - HexTemp duplicated in SM1_c.obj and Events_c.obj.
I get the same error message for up to 10 variables and sometimes the first reference is CPU.c.obj.
I tried re-naming the variable to no avail and I also tried deleting the offending .obj files.
I get the same problem when I cut from main .h file and paste it into events.h.
My only solution is to cut the offending variable from events.h and paste it into events.c and then I get no errors.
I re-created a new project with the same components and I got the same problem.
Hello Julian Cox,
Could you please send your project or a simple project that can reproduce the issue,
I will check it on my side.
BR
Alice
|
https://community.nxp.com/t5/CodeWarrior-for-MCU/Problem-with-include-files/m-p/1031477
|
CC-MAIN-2021-21
|
refinedweb
| 211
| 78.55
|
This article explains some of the new concepts and important features introduced in the Java API for XML Processing (JAXP) 1.3. JSR 206 was developed with performance and ease of use in mind. The new Validation Framework gives much more power to any application dealing with XML schema and improves performance significantly. XPath APIs provide access to the XPath evaluation environment. JAXP 1.3 brings richer XML Schema data type support to the Java platform by defining new data types that map to data types defined in W3C XML Schema: Datatypes specification.
Keeping pace with the evolution of XML standards, JAXP 1.3 also adds complete support for the following standards: XML 1.1, Document Object Model (DOM) L3, XInclude, and Simple API for XML (SAX) 2.0.2. All this has already gone into the Java platform in the latest release of the Java Platform, Standard Edition (J2SE) 5.0, code-named Tiger. If you are using J2SE 1.3 or 1.4, you can download a stand-alone stable implementation of JAXP 1.3 from java.net.
This article mainly concentrates on the work done as part of the JSR 206 effort and explains new Schema Validation Framework concepts, along with providing working code and diagrams. All the samples are available for download from here. The major new features introduced are the following:
Schema Validation Framework
Reusing a Parser Instance
JAXP 1.3 introduces a new schema-independent Validation Framework (called the Validation APIs). This new framework gives much more power to the application dealing with XML schema and can accomplish things that were not possible before. The new approach makes a fundamental shift in the way XML processing and validation are performed. Validation used to be considered an integral part of XML parsing, and previous versions of JAXP supported validation as a feature of an XML parser: a
SAXParser or
DocumentBuilder instance.
The new Validation APIs decouple the validation of an instance document as a process independent of parsing. This new approach has several advantages. Applications that rely heavily on XML schema can greatly improve the performance of schema validation. Perhaps more importantly, many previously unsolvable problems can now be solved in an efficient, easy, and secure way. Let's look at what you can do with the new Schema Validation Framework.
Validate XML Against Any Schema
Validate XML Using a Compiled Schema
Validate a SAXSource or DOMSource
Validate XML After Transformation
Obtain Schema Type Information
Validate XML Against Any Schema
Though JAXP 1.3 requires support only for W3C XML schema language, you can easily plug in support for other schema languages, such as RELAX NG. The Validation APIs provide a pluggability layer through which applications can provide specialized validation libraries supporting additional schema languages. This is achieved using a
SchemaFactory class that is capable of locating implementations for the schema languages at runtime. The first step is to specify the schema language to be used and obtain the concrete factory implementation:
If this function returns successfully, it means that an implementation capable of supporting specified schema language is available. Getting the
SchemaFactory implementation is the entry point to the Validation APIs. This step goes through the pluggability mechanism that has long been at the core of JAXP. You can write the code in such a way that applications can switch between W3C XML Schema and RELAX NG validation without changing a single line of code.
With the new Validation APIs, an application has the option to parse only the schema, checking schema syntax and semantics against the constraints that the particular schema language imposes. This is quite useful when you are writing a schema and want to make sure that the schema conforms to the specification. The
SchemaFactory class does this job, loading the schemas and also preparing them in a special form represented as a
javax.xml.validation.Schema object that can be used for validating instance documents against the schema. A schema may include or import other schemas. In that case, those schemas are also loaded.
When reading a schema, a
SchemaFactory may need to resolve resources and can encounter errors. As Figure 1 indicates,
LSResourceResolver and an
ErrorHandler can be registered on
SchemaFactory. The
ErrorHandler is used to report any errors encountered during schema compilation. The
LSResourceResolver is used to customize resolution of resources. This is a new interface introduced as part of DOM L3. Functionally, it is the same as SAX
EntityResolver, except that it also provides the information about the namespace of the resource being resolved -- for example, the
targetNamespace of the W3C XML schema.
Here is a code sample that shows how
SchemaFactory can be used to compile schema and get a
Schema object:
A
Schema object is an immutable memory representation of schema. A
Schema instance can be shared with many different parser instances, even if they are running in different threads. You can write applications so that the same set of schema are parsed only once and the same
Schema instance is passed to different instances of the parser.
Validate XML Using Compiled Schema
Before we look at this approach, let's look at how we have been doing schema validation using the schema properties that were defined in JAXP 1.2:
Here is an example showing how these two properties are used in JAXP 1.3:
The user sets the
schemaLanguage and/or the
schemaSource property on
SAXParser and sets the validation to
true. Generally, a business application defines a set of schemas containing the business rules against which XML documents must be validated. To accomplish this, an application sets the schema using the
schemaSource property or relies on the
xsi:
schemaLocation attribute in the instance document to specify the schema location(s).
This approach works well, but there is a tremendous performance penalty: The specified schemas are loaded again and again for every XML document that needs to be validated! However, with the new Validation APIs, an application needs to parse a set of schemas only once. See Figure 2.
After the Compile Schema step, do the following.
Just set the
Schema instance on the factory and you are done. There is no need to set the validation to
true and no need to set the
schemaLanguage or
schemaSource property. Validation of XML documents is done against the compiled schema set on the factory. You will be amazed by the performance gain using this approach. Try it yourself.
Run the sample
ComparePerformance.java, which can be downloaded from here. Performance gain largely depends on the ratio of the size of the XML schema to the size of the XML document. Larger ratios lead to a larger performance gain. Look at the Reusing a Parser Instance section to further improve the performance.
Note that it is an error to use either of the following properties:
in conjunction with a non-null
Schema object. Such configuration will cause a
SAXException when those properties are set on
SAXParser or
DocumentBuilderFactory.
Validate a SAXSource or DOMSource
As we mentioned earlier, there has been fundamental shift in XML parsing and validation. Now XML validation is considered a process independent from XML parsing. Once you have the
Schema instance loaded into memory, you can do many things. You can create a
ValidatorHandler that can validate a SAX stream or create a stand-alone
Validator (see Figure 3). A stand-alone
Validator can validate a
SAXSource, a
DOMSource, or an XML document against any schema. In fact, a
Validator can still work if the
SAX stream or
DOM object comes from a different implementation.
To receive any errors during the validation, an
ErrorHandler should be registered with the
Validator. Let's look at some working code. (Note: For clarity, only a section of code is shown here. For the complete source, look at the sample
Validate.java, which can be downloaded here.)
Validator can also be used to validate the instance document or
DOM object in memory, with the augmented result sent to
DOMResult.
The Validation APIs can validate a
SAX stream and work in conjunction with Transformation APIs to achieve pipeline processing, as we will see in the next section.
Validate XML After Transformation
Transformation APIs are used to transform one XML document into another by applying a style sheet. There are times when we need to validate the transformed XML document against a schema. Should we feed that XML document to a parser and then use the schema feature to do the schema validation? No. The new Validation APIs give you the power to validate the transformed XML document against a different schema by allowing the application to create a pipeline and pass the output of a transformer to the Validation APIs to validate against the desired schema. It doesn't matter if the output of the transformation is a
SAX stream or a
DOM in memory.
The following code snippet shows you how to use specially designed
javax.xml.validation.ValidatorHandler to validate a
SAX stream. In the downloadable source, look at the sample
ValidateSAXStream.java for more detail. Also look at the sample
TransformerValidationHandler.java, which shows how to chain the output of
Transformer to
ValidatorHandler. Here is a section of the code:
Figure 4 shows the whole flow, with an XML document and a style sheet given as input to a
Transformer and a
SAX stream as the output. We take advantage of the modular approach of doing validation independent from parsing. The
ValidatorHandler is a special handler that is capable of working directly with a
SAX stream. It validates the stream and passes it to the application.
The Transformation APIs also allow a transformed result to be obtained as a
DOM object. The
DOM object in memory can be validated against a schema. This can be done as follows:
So you see that the Validation APIs can be used with the Transformation APIs to do complex things easily. This approach also boosts performance because it avoids the step of parsing the XML again when validating a transformed XML document.
The
ValidatorHandler can be used to validate various object models such as
JDOM against the schema(s). In fact, any object model (
XOM,
DOM4J, and so on) that can be built on top of a
SAX stream or can emit
SAX events can be used with the Schema Validation Framework to validate an XML document against a schema. This is possible because
ValidationHandler can validate a
SAX stream.
Let's see how a
JDOM document can be validated against schema(s):
It is that simple.
JDOM has a way to output a
JDOM document as a stream of
SAX events.
SAXOutputter fires
SAX events that are validated by
ValidatorHandler. Any error encountered is reported through
ErrorHandler set on
ValidatorHandler.
Obtain Schema Type Information
ValidatorHandler can give access to
TypeInfoProvider, which can be queried to access the type information determined by the validator. This object is dynamic in nature and returns the type information of the current element or attribute assessed by the
ValidationHandler during validation of the XML document. This interface allows an application to know three things:
Whether the attribute is declared as an
ID type
Whether the attribute was declared in the original XML document or was added by
Validator during validation
What type information of the element or attribute as declared in the schema is associated with the document
Type information is returned as an
org.w3c.dom.TypeInfo object, which is defined as part of DOM L3. The TypeInfo object returned is immutable, and the caller can keep references to the obtained TypeInfo object longer than the callback scope. The methods of this interface may only be called by the
startElement event of the
ContentHandler that the application sets on the
ValidatorHandler. For example, look at the section of the code below. (Note: For clarity, only part of the code is shown here. For the complete source, look at the sample
SchemaTypeInformation.java, which can be downloaded from here.)
Validating an XML document against an untrusted schema could have serious consequences, as validation may modify the actual data by adding default attributes and possibly corrupting the data. Validation against an untrusted schema may also mean that an incoming instance document might not conform to your business's constraints or rules.
With the new Validation APIs, getting a
Schema instance is the first step before being able to validate an instance document, and it is the application that determines how to create the
Schema instance. Validation using the
Schema instance makes sure that an incoming instance document is not validated against any other (untrusted) schema(s) but only against the schema(s) from which the instance is created. If the instance XML document has elements or attributes that refer to schema(s) from a different
targetNamespace and are not part of
javax.xml.validation.Schema representation, an error will be thrown. This approach protects you from accidental mistakes and malicious documents.
Is it possible to use the same parser instance to parse multiple XML documents? This was not clear, and the behavior was implementation dependent. JAXP 1.3 has added the new function
reset() on
SAXParser,
DocumentBuilder, and
Transformer. This guarantees that the same instance can be reused. The
reset function improves the overall performance by saving resources, time associated with creating memory instances, and garbage collection time. Let's see how the
reset() function can be used.
The same function has also been added to newly designed
javax.xml.validation.Validator, as well as to
javax.xml.xpath.XPath. Applications are encouraged to reuse the
parser,
transformer,
validator and XPath instance by calling
reset() when processing multiple XML documents. Note that
reset() sets the instance back to factory settings.
Accessing XML is made simple using XPath: A single XPath expression can be used to replace many lines of
DOM API code. JAXP 1.3 has defined XPath APIs that conform to the XPath 1.0 specification and provide object-model-neutral APIs for the evaluation of XPath expressions and access to the evaluation environment. Though current APIs conform to XPath 1.0, the APIs have been designed with future XPath 2.0 support in mind.
To use JAXP 1.3 XPath APIs, the first step is to get the instance of
XPathFactory. Though the default model is W3C
DOM, it can be changed by specifying the object model URI:
Evaluate the XPath Expression
XpathFactory is used to create
XPath objects. The
XPath interface provides access to the XPath evaluation environment and expressions.
XPath has overloaded the
evaluate() function, which can return the result by evaluating an XPath expression based on the return type set by the application. For example, look at the following XML document:
Following is the working code to evaluate the XPath expression and print the contents of all the
Book elements in the XML document:
Evaluate With Context Specified
XPath is also capable of evaluating an expression based on the context set by the application. The following example sets the
Document node as the context for evaluation:
With a reference to a
Book element, a relative XPath expression can now be written to select the
Name element as follows:
NamespaceContext XPath Evaluation
What happens if the XML document is namespace aware? Look at the following XML document, in which the first
Book element is in the
publisher1 domain and the second in the
publisher2 domain:
In this case, the XPath expression
/Books/Book/Name/text() won't give any result because the expression is not fully qualified. You can use an expression such as
/Books/p1:Book/p1:Name with a
p1 prefix. However, you should set
NamespaceContext on the
XPath instance so that the
p1 prefix can be resolved. In the following sample, the
NamespaceContext capable of resolving
p1 is set on the
XPath instance. Note that the two
Book elements are in different namespaces, so the expression would result in only one node.
The XPath specification allows variables to be used in the XPath expressions.
XPathVariableResolver is defined to provide access to the set of user-defined XPath variables. Here is an example of an XPath expression using
Variable:
A
SimpleXPathVariableResolver can implement the
resolveVariable() function as follows. (Note: For clarity, only the relevant code is shown here.)
JAXP 1.3 has introduced new data types in the Java platform, the
javax.xml.datatypes package, that directly map to some of the XML schema data types, thus bringing XML schema data type support directly into the Java platform.
The
DatatypeFactory has functions to create different types of data types -- for example,
xs:data,
xs:dateTime,
xs:duration, and so on. The
javax.xml.datatype.XMLGregorianCalendar takes care of many W3C XML Schema 1.0 date and time data types, specifically,
dateTime,
time,
date,
gYearMonth,
gMonthDay,
gYear
gMonth, and
gDay defined in this XML namespace:
These data types are normatively defined in W3C XML Schema 1.0, Part 2, Section 3.2.7-14.
The data type
javax.xml.validation.Duration is an immutable representation of a time span as defined in the W3C XML Schema 1.0 specification. A
Duration object represents a period of Gregorian time, which consists of six fields (years, months, days, hours, minutes, and seconds) as well as a sign field (+ or -).
Table 1 shows the mapping of XML schema data types to Java platform data types. Table 2 shows the mapping of XPath data types and Java Platform data types.
These data types have a rich set of functions introduced to perform basic operations over data types, for example, addition, subtraction, and multiplication.
Also, there are ways to get the
lexicalRepresentation of a particular data type that is defined at XML Schema 1.0, Part 2, Section 3.2.[7-14].1, Lexical Representation. There is no need to understand the complexities of XML schema data types such as what types of operations are allowed on a data type, how to write a lexical representation, and so on. The
javax.xml.datatype APIs have defined a rich set of functions to make it easy for you.
JAXP 1.3 has also defined the support for XInclude.
SAXParserFactory/DocumentBuilderFactory should be configured to make it XInclude aware. Do this by setting
setXIncludeAware() to
true.
JAXP 1.3 has defined a security feature:
When set to
true, this operates the parser in secure manner and instructs the implementation to process XML securely and avoid conditions such as denial-of-service attacks. Examples include restricting the number of entities that can be expanded, the number of attributes an element can have, and the XML schema constructs that would consume large amounts of resources, such as large values for
minOccurs and
maxOccurs. If XML processing is limited for security reasons, it will be reported by a call to the registered
ErrorHandler.fatalError().
This article has introduced you to some of the new features in JAXP 1.3. You have seen the benefits of the Schema Validation Framework and seen how it can be used to improve the performance of schema validation. Developers working with applications using JAXP 1.2 schema properties to validate XML document against schemas should upgrade to JAXP 1.3 and use this framework. Remember to reuse the parser instance by calling the
reset() method to improve performance.
New object-model-neutral XPath APIs bring XPath support and can work with different object models. XML schema data type support is brought directly into the Java platform with the introduction of new data types. Security features introduced in JAXP 1.3 can help protect the application from denial-of-service attacks. Also, JAXP 1.3 provides complete support for the latest standards: XML 1.1, DOM L3, XInclude, and SAX 2.0.2. These are enough reasons to upgrade to JAXP 1.3, and the implementation is available for downloading from java.net.
W3C XML Schema: Datatypes
RELAX NG home page
XPath APIs
XML 1.1 specification
DOM L3 specification
XInclude specification
SAX 2.0.2 home page
Neeraj Bajaj is a member of the technical staff in the Web Technology and Standards group at Sun Microsystems. He has been working in the area of core XML processing-related technologies for more than four years. He is the architect of the Sun Java Streaming XML Parser and the co-specification lead of JAXP 1.4. He has contributed to the development of Apache's open-source Xerces2-J project and to the implementation of JSR 60 (JAXP 1.2), JSR 206 (JAXP 1.3), JSR 173 (StAX), and JAXP 1.4.
|
http://www.oracle.com/technetwork/articles/javase/jaxp1-3-136365.html
|
CC-MAIN-2014-52
|
refinedweb
| 3,427
| 55.03
|
GoogleScraper 0.0.2.dev1
A module to scrape and extract links, titles and descriptions from Google search results
### Table of Contents
1. [Installation](#install)
2. [About](#about)
3. [Usage with Python](#usage)
4. [Command line usage (read this!)](#cli-usage)
5. [Contact](#contact)
<a name="install" \="">
### Installation
GoogleScraper is written in Python 3. Therefore install at least python 3.3
Furthermore, you need to install the Chrome Browser, maybe even the ChromeDriver for Selenium (I didn't have to).
From now on (august 2014), you can just install with pip:
```
pip install GoogleScraper
```
#### Alternatively install from Github:
First clone and change in project tree.
Begin with installing the following third party modules:
```
lxml
selenium
bs4 [try beautifulsoup4]
cssselect
requests
```
You can do so with:
`pip3 install module1, module2, ..`
If you want to install GoogleScraper locally, do as follows (Run all commands in the GoogleScraper.py directory):
```bash
virtualenv --no-site-packages .venv
source .venv/bin/activate
pip install -r requirements.txt
# Now test it
python run.py
```
<a name="about"/>
### What does GoogleScraper.py?
GoogleScraper parses Google search engine results easily and in a performant way. It allows you to extract all found
links and their titles and descriptions programmatically which enables you to process scraped data further.
There are unlimited *usage scenarios*:
+ Quickly harvest masses of [google dorks][1].
+ Use it as a SEO tool.
+ Discover trends.
+ Compile lists of sites to feed your own database.
+ Many more use cases...
First of all you need to understand that GoogleScraper uses **two completely different scraping approaches**:
+ Scraping with low level networking libraries such as `urllib.request` or `requests` modules. This simulates the http packets sent by real browsers.
+ Scrape by controlling a real browser with Python
Whereas the first approach was implemented first, the second approach looks much more promising in comparison.
Effective: Development for the second approach started around 10.03.2014
GoogleScraper is implemented with the following techniques/software:
+ Written in Python 3.4
+ Uses multithreading/asynchroneous IO. (two possible approaches, currently only multi-threading is implemented)
+ Supports parallel google scraping with multiple IP addresses.
+ Provides proxy support using [socksipy][2] and built in browser proxies:
* Socks5
* Socks4
* HttpProxy
+ Support for additional google search features like news/image/video search.
### Google Servers to detect that a robot is using
their search engine:
+ The User-Agent is not one of a browser.
+ The search params are not identical to the ones that browser used by a human sets:
*...
### How to overcome difficulties of low level (http) scraping?
As mentioned above, there are several drawbacks when scraping with `urllib.request` or `requests` modules and doing the networking on my own:
Browsers are ENORMOUSLY complex software systems. Chrome has around 8 millions line of code and firefox even 10 LOC. Huge companies invest a lot of money to push technology forward (HTML5, CSS3, new standards) and each browser
has a unique behaviour. Therefore it's almost impossible to simulate such a browser manually with HTTP requests. This means Google has numerous ways to detect anomalies and inconsistencies in the browsing usage. Alone the
dynamic nature of Javascript makes it impossible to scrape undetected.
This cries for an alternative approach, that automates a **real** browser with Python. Best would be to control the Chrome browser since Google has the least incentives to restrict capabilities for their own native browser.
Hence I need a way to automate Chrome with Python and controlling several independent instances with different proxies set. Then the output of result grows linearly with the number of used proxies...
Some interesting technologies/software to do so:
+ [Selenium]()
+ [Mechanize]()
<a name="usage" \="">
### Example Usage
Here you can learn how to use GoogleScrape from within your own Python scripts.
Keep in mind that the bottom example source uses the not very powerful *http* scrape method. Look [here](#cli-usage) if you
need to unleash the full power of GoogleScraper.
```python
import GoogleScraper
import urllib.parse
GoogleScraper.setup_logger()
if __name__ == '__main__':
results = GoogleScraper.scrape('Best SEO tool', num_results_per_page=50, num_pages=3, offset=0, searchtype='normal')
for page in results:
for link_title, link_snippet, link_url, *rest in page['results']:
# You can access all parts of the search results like that
# link_url.scheme => URL scheme specifier (Ex: 'http')
# link_url.netloc => Network location part (Ex: '')
# link_url.path => URL scheme specifier (Ex: ''help/Python.html'')
# link_url.params => Parameters for last path element
# link_url.query => Query component
try:
print(urllib.parse.unquote(link_url.geturl())) # This reassembles the parts of the url to the whole thing
except:
pass
# How many urls did we get on all pages?
print(sum(len(page['results']) for page in results))
# How many hits has google found with our keyword (as shown on the first page)?
print(results[0]['num_results_for_kw'])
```
### Example Output
This is a example output of the above *use.py*. You can execute it by just firing `python use.py` in the project directory:
```
[nikolai@niko-arch GoogleScraper]$ python use.py
151
About 14,100,000 results
```
<a name="cli-usage" \="">
### Direct command line usage
Probably the best way to use GoogleScrape is to use it from the command line and fire a command such as
the following:
```
python GoogleScraper.py sel --keyword-file path/to/keywordfile
```
Here *sel* marks the scraping mode as 'selenium'. This means GoogleScraper.py scrapes with real browsers. This is pretty powerful, since
you can scrape long and a lot of sites (Google has a hard time blocking real browsers). The argument of the flag `--keyword-file` must be a file with keywords separated by
newlines. So: For every google query one line. Easy, isnt' it?
Example keyword-file:
```
keyword number one
how to become a good rapper
inurl:"index.php?sl=43"
filetype:.cfg
allintext:"You have a Mysql Error in your"
intitle:"admin config"
Best brothels in atlanta
```
By default, *sel* mode only requests the first 10 results for each keyword. But you can specify on how many Google result pages
you want to scrape every keyword. Just use the **-p** parameter as shown below:
```
# searches all keywords in the keywordfile on 10 result pages
python GoogleScraper.py sel --keyword-file path/to/keywordfile -p 10
```
By now, you have 10 results per page by default (google returns up to 100 results per page), but this will also be configurable in the near future. *http* mode
supports up to 100 results per page.
After the scraping you'll automatically have a new sqlite3 database in the project directory (with a date time string as file name). You can open the database with any sqlite3 command
line tool or other software.
It shouldn't be a problem to scrape **_10'000 keywords in 2 hours_**, if you are really crazy, set the maximal browsers in the config a little
bit higher (in the top of the script file).
If you want, you can specify the flag `--proxy-file`. As argument you need to pass a file with proxies in it and with the following format:
```
protocol proxyhost:proxyport username:password
(...)
```
Example:
```
socks5 127.0.0.1:1080 blabla:12345
socks4 77.66.55.44:9999 elite:js@fkVA3(Va3)
```
That's basically all for the *sel* modeHave fun.
In case you want to use GoogleScraper.py in *http* mode (which means that raw http headers are sent), use it as follows:
```
python GoogleScraper.py http -p 1 -n 25 -q "keywords separated by whitespaces"
```
<a name="contact" \="">
If you feel like contacting me, do so and send me a mail. You can find my contact information on my [blog][3].
[1]: "Google Dorks"
[2]: "Socksipy Branch"
[3]: "Contact with author"
[4]:
- Author: Nikolai Tschacher
- Package Index Owner: zardaxt
- DOAP record: GoogleScraper-0.0.2.dev1.xml
|
https://pypi.python.org/pypi/GoogleScraper/0.0.2.dev1
|
CC-MAIN-2016-44
|
refinedweb
| 1,280
| 57.67
|
Never underestimate the power of simplicity. It's hard to imagine the application of concepts like push real-time notifications, using databases, having a rich text editor with Vanilla JS. But you can do a lot with it. Here are some examples of their libraries that make Vanilla JS somewhat impeccable. I will try to embellish each library with its features and other attributes concerning its documentation.
Pushjs
I've been breaking my head all around to find the best tutorials for implementing the push notification feature. But Pushjs made my work painless. The documentation is easy and beginner-friendly.
All the effort that you need to take is to create an HTML file in a folder.
The next step is followed by the installation part. Either install it using the npm package manager or using Github download the zip file. After downloading, unzip the folder and copy-paste push.min.js and serviceWorker.min.js into your project directory.
Code for index.html
<body> <script src="push.min.js"></script> <script src="serviceWorker.min.js"></script> <script> function start() { Push.create("Hello from Unnati!", { body: "Here's your push notification demo", icon: '', timeout: 4000, onClick: function () { window.focus(); this.close(); } }); } </script> <h1>Push notification implementation</h1> <h3>Click on this button to view notification</h3> <a href="javascript:void(0)" onclick="start()">Start</a> </body>
EditorJS
Next, the amazing library on the list is Editor Js. We need text editors in our project quite often, hence EditorJs is one of the simple and captivating libraries. You can use it with Vanilla Js, ReactJs, and other frameworks. Making your text bold or italics or adding a heading, has it all. Just quickly run through the documentation and you'll get a clear gist of this library. Let's come to the coding part. Again, you can either install it using the npm package manager or use its cdn.
index.html
<body> <h1>Enter your content here</h1> <div id="editorjs"></div> <button id='button'>Save article</button> <script src=""></script> <script src="index.js"></script> </body>
index.js
try { var editor = new EditorJS({ holderId : 'editorjs', placeholder: 'Let`s write an awesome story!', autofocus: true, }); editor.isReady .then(() => { console.log("Editor.js is ready to work!"); }) .catch((reason) => { console.log(`Editor.js initialization failed because of ${reason}`); }); const btn = document.getElementById("button"); btn.addEventListener("click", function () { editor.save().then((outputData) => { console.log('Article data: ', outputData) }).catch((error) => { console.log('Saving failed: ', error) }); }); } catch (reason) { console.log(`Editor.js initialization failed because of ${reason}`); }
After installing if your try to import editorjs it will give an error, you need to make some configurations for import to work. Hence, you use the above code for reference.
It can also help you to save your write-up material.
You get a lot of options for configuring your editor like adding headers, lists, embed.
import Header from '@editorjs/header'; import List from '@editorjs/list'; import MyParagraph from 'my-paragraph.js'; const editor = new EditorJS({ tools: { header: Header, list: List, myOwnParagraph: MyParagraph }, defaultBlock: "myOwnParagraph" })
Howler.js
You must've used audio and video tags in your projects. Howlerjs, is here to enhance your experience. The documentation explains the code well. Here's the reference piece of code which gives you a basic idea of HowlerJS
<script> var sound = new Howl({ src: ['sound.webm', 'sound.mp3'] }); </script>
Reveal.js
Ever wondered one day you'll be able to create presentation slides using Javascript. Reveal.js, made it possible. This is an amazing library that I would like to add to the list. You can install it using npm package manager or navigate to Github and download zip and include the files in your project folder. Create an HTML file and fetch all the CSS and javascript files.
<link rel="stylesheet" href="dist/reset.css"> <link rel="stylesheet" href="dist/reveal.css"> <link rel="stylesheet" href="dist/theme/black.css" id="theme"> <link rel="stylesheet" href="plugin/highlight/monokai.css" id="highlight-theme">
Javascript files
<script src="dist/reveal.js"></script> <script src="plugin/notes/notes.js"></script> <script src="plugin/markdown/markdown.js"></script> <script src="plugin/highlight/highlight.js"></script> <script> Reveal.initialize({ hash: true, plugins: [ RevealMarkdown, RevealHighlight, RevealNotes ] }); </script>
For the slides part.
In index.html inside body tag create a div with id name reveal and nest another div with id name slides. Inside the nested keep adding the section div depending upon the slide requirement.
<div class="reveal"> <div class="slides"> <section> <h1>Slide 1</h1> <h3>This is an amazing library</h3> </section> <section> <h1>Slide 2</h1> <h3>You can just play around with a lot of stuff</h3> </section> <section> <h1>Slide 3</h1> <h3>That's it for the slide Show</h3> </section> </div> </div>
ChartJS
Presentations and displaying graphical charts go hand in hand. Javascript has a stunning library Chartjs where we can represent data using these charts. It includes bar graphs, pie diagrams, dot diagrams, and a lot more.
Here's the sample code for the pie chart
var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: : { beginAtZero: true } } } });
There are a lot of other popular and useful libraries which can be used with Vanilla Js. That's it for this post. If you know more stunning libraries like these please do mention them in the comment section below.
Discussion (38)
Vanilla js librairies, how does that makes sense ?
I thought vanilla was js precisely without libs
This totally makes sense to me in a matter that the "library" doesn't have any other dependencies like jQuery, React/Vue, etc. i.e. if you're familiar with JS you can just get the library and start using it without cognitive overload by finding that you also have to use that on a specific platform only, having other packages installed and be in a parallel universe.
This totally makes sense to any seasoned developer or any backend developer. But frontend developers nowadays have a mess in their heads. They believe that React is a library because they thought to believe this. Therefore they don't understand completely what a library actually is. Hence a comment: "Vanilla js librairies, how does that makes sense ?" with 17 likes. Awful.
Kindly please describe what is a library to you, their might be an interesting discussion here.
If we take the example of the editor.js "library":
The line between library and framework is a bit fuzzy, I would still consider react a framework because it is how people use it and arguably the recommanded way to use it.
My message was not about react being a lib, more than using huge library not the spirit of what I would call vanilla JS.
It is not fuzzy and it never was. It always was simple and clear. It became fuzzy when promoters of React decided to call it "library".
A library is just a set of methods/functions regardless of its size. It can be GB in size and it still will be the library. Editor.js is a perfect example of a library. Another one jQuery - 30,000 plugins and why it even matters?
Framework on another side can be several lines of code, but still, be a framework just because it requires your code to be written in a certain way. React which requires extending classes and implementing methods is a perfect example of a framework.
General principle:
Your code calls the library, but the framework calls your code.
Speaking of "Vanilla JS", "Vanilla JS" is a part of jQuery hate strategy invented by the same frauds who call React the library.
The power of a language is in its libraries and frameworks. "Vanilla JS" is nonsense, the same way as "Vanilla Java" or "Vanilla Python". We just need to call libraries - libraries and frameworks - frameworks and use them where they make sense.
Thanks bigbott, I was skimming the comments and thinking “please tell me SOMEONE knows what a library is! Big ol bundle of code!”
Maybe people don’t “need” to learn C++ but I swear a week with it and people wouldn’t be confused by stuff like the idea of a “library” that is just a big block of text.
It’s almost like how a real library is a place that holds lots of useful information data and methods to achieve things. Weird, right? 😜
My exact thought.
I get that there might be an established definition of Vanilla JS. But isn't Vanilla JS libraries just JS functions packaged together. I don't see much of a difference between keeping the JS all in one file, vs storing it in another module and importing it.
With this definition then libraries like Vue and React are "Vanilla JS" libraries.
Yeah good point. I think of React as non-vanilla because of how many layers of abstraction it has. But I guess ultimately, if there's even one layer of abstraction, like packaging a one-liner into a library, then it might as well be considered non-vanilla.
For me the difference is, directly using the browser API and writing code just for your needs and understanding the API behind the code.
In a way, react can be use as just a vanilla JS library in that case, you don't even need to write JSX and can use it for some elements only... It's probably lighter than some of the libraries listed in this article.
Because you can use them with vanilla JS, w/o dependencies nor supersets.
I guess, it means it doesn't require some framework like React, Angular, Vue, JQuery, etc.
JQuery isn't really a framework though, yet I'd still consider it non vanilla JS.
True but ... this list is f****** awesome! I'll allow it! :-D
I don't think that's necessarily the case - I always thought that it means without the prerequisite of a framework like Angular or library like React...
Vanilla JS is when you don’t abstract away to a framework like React or JQuery etc... You can still use libraries.
What about popper.js? I think it makes tool-tips easy.
Cool, thanks for your suggestion. Will definitely try it
Nice article!
Also, tippy.js for tooltips and popovers
I think having the title "Vanilla JS" is misleading here. Vanilla JS usually means using methods and features natively available in most browsers and included in the standard of ECAMScript without importing external libraries. This is a good post about libraries you recommend (and these are all great libraries) but there is not really such thing as a Vanilla JS library IMO.
French Vanilla JS then. 🙄
Yikes, these comments are a bad take. Great article!
It looks like there are a ton of developers out there who don't see the difference between libraries built (or adapted) to work with frameworks and libraries built to work in non-framework-dependent environments.
Thanks, I was looking for a push notification to add to my current side project and slides to my personal site. Btw Great work keep it up!
Thank you!
Once you include dependencies outside your own ecosystem , this can be considered as no longer being vanilla in my opinion.
There is absolutely nothing wrong with using libraries we all do in our career but in its purest form, “Vanilla” refers to creating solutions is JavaScript which has not been scaffolded by external dependencies.
Essentially all JavaScript is vanilla but once you introduce a wider dependency tree it’s no longer true vanilla. This isn’t to say that modularizing your code is pollution as it’s merely abstraction , but using another’s code is adding to the mix as so to speak.
Cool libraries. Thanks for sharing!
You're welcome!
Came for the comments and ensuing firestorm over "Vanilla JS" and "Library" in the same sentence.
Was not disappointed. 🔥 🔥 🔥
EditorJS and PushJS seem to be quite cool, never tried them
Great stuff - thanks!
Thanks for the share
You're welcome
Hey I tried some of these before
Great! If you have something in your list which is not there in this post please do share.
Thanks, this will help.
I'm glad.
I suggest adding Swiperjs, a very handy slide library :D
|
https://dev.to/commentme/some-vanilla-js-libraries-you-must-try-17a3
|
CC-MAIN-2021-21
|
refinedweb
| 2,051
| 66.94
|
Hi guys!
Great news! There's an official .Net control at work, and I'm part of it. And it is now working very well, so, download it here:.
I have spent some time now to created a server control for ASP.NET, in the same manner as the FCKeditor2 control.
I'm keeping always the last 3 versions attached to this post, as this is the maximum for the form. And no I do not have the time to keep a blog or a 'project' in 'github' or its equivalents.
Basics how to use:
- Put the FredCK.CKEditor.dll in your /Bin folder (You can find it in bin/Release in the Zip package)
- Register the control with either or even both methods:
- Globally, in web.config: <add tagPrefix="FredCK" namespace="FredCK.CKEditor" assembly="FredCK.CKEditor, Culture=neutral, PublicKeyToken=9ef91de3e191403a" />
- Per page: <%@ Register Assembly="FredCK.CKEditor" Namespace="FredCK.CKEditor" TagPrefix="FredCK" %>
Old note: Although I have implemented a fix for the HtmlEncodeOutput in some previous release (which did not modify ckeditor's sources), now a few days after - they release CKEditor 3.1, and guess what, it finally has htmlEncodeOutput...
So I commented out my code, and implemented the configuration option htmlEncodeOutput.
Attention: If you have specified the EncodeOutput property yourself, now you have to change it to HtmlEncodeOutput, since I change it to fit the new configuration name.
Some of the configurations can be set only in actual code and not inline attributes, due to them being arrays. I may find a solution, maybe implementing a converter for the inline attributes.
Some of the configurations are pure javascript because they are tooooo complex. Be careful with those.
The only thing I do not entirely understand is the toolbarLocation thing. Are there any values other than 'top' and 'bottom' and will anyone ever use them?
People have been asking about the password for the strongKey file, so here it is: ckeditor. Pretty hard to guess huh?
Note: each time before I remove the old attachments and upload the new one, as there's a limit for max 3 attachments. Thank you all for your comments! You helped make this control better!
BTW, CKEditor team: You CAN take this and make it an official download
UPDATE: A critical update. Since 3.5.1 there was a problem when destroying the CKE (e.g. page unload, submit...) - and only when NOT using MsAjax. I found out that in the beginning of this control, the 'destroy' function was private, and so I used fire('destroy') to completely destroy it. And now CKE has trouble destroying it this was, so it needed two calls... I changed it to destroy using .destroy() which the MsAjax support already used. Yes we were so concentrated on fixing bugs related to MsAjax that we forgot to test in 'normal' environments...
UPDATE: A little fix for Dialog_BackgroundCoverOpacity, when formatting the decimal point, to always use a period.
UPDATE: Fixed a bug with SharedSpacesTop, which was working improperly under a MasterPage, or any container control.
UPDATE: CKE 3.5 is out. I have added the new configurations. Tested and everything is working fine!
UPDATE: CKE 3.4.1 is out. I have added the new configuration filebrowserWindowFeatures. And a property Text which is a synonym for the Value property.
UPDATE: I have added the "CKEditor" keyword to the title of this post, so google will find it also in response to "ckeditor" search and not only "cke"
Gotta take care of those pure guys looking for "ckeditor asp.net" and finding nothing...
UPDATE: I have tested against CKE 3.4, and added the new configurations of 3.3.2 and 3.4: smiley_columns, enableTabKeyTools, autoGrow_maxHeight, autoGrow_minHeight. I have also created a convenience property/configuration for the new plugin tableresize, this property is named "RegisterPlugin_TableResize", and if set to true (even inline), it will automatically add the 'tableresize' to the array of ExtraPlugins.
UPDATE: I have tested with CKE 3.3.1 and all seems fine! There was a bug that I have fixed in this version (was present in 3.3 also), where the following configurations were not quoted in the JS, and this broke the page's code: resizeDir, contentsLangDirection, scayt_moreSuggestions, toolbarLocation. This may also explain why ToolbarLocation did not work for some people.
UPDATE: I have updated the configurations for supporting the 3.3 changes. For some reason the config documentation was very poorly updated, some stuff like scayt-spell-checker was written down as "3.0" when it was added in 3.3, so I had to hunt down all the changes.
There's also another important change: Now ContentsLangDirection is defaulted to the new (undocumented...) value 'ui', which means it will inherit from the language of the UI.
I have added all of those configurations that I hesitated to add earlier (e.g. keystrokes, find_highlight, font_style), because I know there won't be an 'easy' solution that will also fit all developers. Then I realized that those configurations are so complex, that those who use it must know what they're doing. So what I did is 'open it up' for javascript. That's it - those configuration now accept pure javascript. Those which accept String|Array, will accept pure javascript array, or a string. If its a simple string - it will be automatically escaped for javascript and encapsulated in quotes.
Toolbar configuration now accepts javascript too. You can specify just "Full" or "Basic" or other toolbar name, or you can specify "['Bold', '-', 'Italic'...]" for an javascript array.
BasePath will now default to "~/ckeditor/", so you don't need to specify that everywhere.
BTW, you can put a key-pair in your app.config, name "CKEditor:BasePath", with a value for all instances for CKE... This will save you some code.
UPDATE: I have experimented the Update Panels myself a little bit, so I can find the source of the problem. Then I implemented javascript dispose method, and everything works fine!
UPDATE: I have just updated the configurations to reflect the new 3.2 version. (Exactly one new configuration...)
UPDATE: More bug fixes with AJAX. I have just found out that destroy() is the correct method to cleanup the CKEditor. To prevent 'hiding editor' before postback I did a 'hack' to cleanup without actually remove the editor from document.
UPDATE: And another bugfix with MsAjax. This time with postbacks which don't trigger onsubmit. Actually this was quite an easy fix.
UPDATE: Fixed another problem with Microsoft Ajax. Needed cleanup of CKEditor when there's a PostBack, because it generates an error that the instance alredy exists. Note: The cleanup is still not full. Need to find a better API function to cleanup an instance.
UPDATE: Due to some people trying to put this inside UpdatePanels and that's not working, I have added support for Microsoft AJAX, which does some workarounds for such cases. The main problem is that registering scripts with Microsoft AJAX requires that the ckeditor.js will cal back the AJAX library to tell it that it is done loading. And that of course isn't gonna happen. So according to my tests my workaround works now. Try it yourself...
UPDATE: I have added the configurations for integration with File Browsers and Uploader scripts. Still not received ANY feedback from anyone.
UPDATE: I worked on most of the configurations now and added the new ones of 3.0.2 and 3.1, and finished the work on the old ones. There are only a few left now to work on. This is the last update for today...
UPDATE: So shared spaces is supported now... And you can set them through SharedSpacesTop/SharedSpacesTopClientID/SharedSpacesBottom/SharedSpacesBottomClientID. There is also a CKSharedSpace control now, which is basically a DIV web control, so you can use that for a shared space, or anything else you want. In addition now the ExtraPlugins and RemovePlugins is fully supported.
UPDATE: CKEditor 3.1 is out, with integrated natural HtmlEncodeOutput capability. Hurray!
UPDATE: I have fixed the HTML Encode thing so ASP.NET does not give a security error anymore. The ASP.NET control is usable now!
I have reversed the order of update notifications, so If you're looking for info on the last update, look on the *beginning* of the page
Re: Have made Asp.Net Server Control! (And little help needed)
StartupMode should not be an enumeration - see the API.
ToolbarName should not be an enumeration - see the API.
ToolbarLocation should not be an enumeration - see the API.
Though I can just about see there being a desire to maintain compatibility with 1.1, client state that the control relies upon should be stored in .NET ControlState, not ViewState.
It is wrong that you have marked the files as developed by yourself, as they are very clearly in part copies of the original source available from the FCK Editor site, as well as in part derivative works.
The ClientScriptManager can handle the setting of client on submit events, a reference to which can be gleaned from 'this.Page.ClientScript'. Best practice dictates you need to first ensure that the control does not partake in a partial page update contract before that however, and if it does your escape operation must use other means.
The 'ExtraPlugins' property. Not sure why you have done this but the assignment operator will append to this property if the underlying data store has already been set. This is a clear example of unexpected operation.
You can programmatically devine an enumerations' name in .NET, for example to use with your 'ShiftEnterMode' property. For instance somthing along the lines of (from memory): Enum.GetName(typeof(EnterMode), (int)value)).
Regards
Re: Have made Asp.Net Server Control! (And little help needed)
Thanks for your comments!
About ClientScriptManager - I tried to register a javascript for the OnSubmit of the form, but its no use, because it happens BEFORE the CKEditor copies the content to the textarea. To make sure it always happens we need to make it controlled by the CKEditor itself, otherwise we will have to make a 80 lines script instead of a 1 line script in order to maintain compatibility with all browsers...
The extraPlugins is working fine by my tests. It is supposed to add to the existing list or make a new one. An existing list is there when you have set the uiColor property (which registers an extraPlugin...). There's nothing unexpected there (just not documented yet by me)
I do not know why you are saying that it is not coded by myself, as 99% of this code I did write. You have any idea how much time it takes to move all configuration properties, each one with its type and description, from the documentation to the actual code? And the basic code of the control was mostly also rewritten by me, even though it might seem the same. I did try at first to make it compatible with the FCKeditor .Net control, but when I got to the configurations, I realized thats not gonna happen...
The only thing that I recall I have taken from the original code, is the file structure (without the 'F'), and the html string for the Designer.
I know that StartupMode, ToolbarName and ToolbarLocation should not be Enum, but it is convenient for the time being, when I haven't yet added support for all those array based configurations. So for now it gives the basic functionality that most people will use.
As for ViewState vs ControlState - As I understand it, the difference is that ControlState cannot be disabled by the user. But isn't ViewState the 'standard' in server controls for this purpose?
As for "Enum.GetName(typeof(EnterMode), (int)value))." - I do not need to do that actually. If I wanted to get the string name of the enum value, I could just use ToString().
But I'm originally a C++ developer, and I tend to always do "error checking", and by a C++ developer logic, you know that there can be cases where an enum will have a value which is not in the Value-Name list, so I use switch-case for that. I'm not sure how C# handles these cases, but I'm not sure either if I'll actually gain any performance from converting directly to string.
Bottom line - the first thing we have to do, is figure out the best way to encode the html before submit, after the editor has copied its content to the textarea. (Which is probably registered with the browser for the onsubmit event).
After that - we'll handle all the rest of the work to be done with the configurations.
And then - integrating the file browser/uploader.
Thanks again for commenting on this! I did expect a lot more responses on this one, but you are the only one so far...
Re: Have made Asp.Net Server Control! (And little help needed)
Re: Have made Asp.Net Server Control! (And little help needed)
Hi,
while there is no native support for the HtmlEncode like in FckEditor 2.x you could use the following technique:
Does anyone knows, if there are any plans for a native HtmlEncode-Support ?
Greetings,
Sven
Re: Have made Asp.Net Server Control! (And little help needed)
Re: Have made Asp.Net Server Control! (And little help needed)
What I need exactly for this is a way to encode the 'critical' html entities before form submission. (Which are the <>& (< > &), just 3 characters.
Because ASP.NET won't allow those characters to be posted as they are, they need to be converted to the html entities.
So we just have to run a simple replace before post.
How do I approach this?
I tried already writing a little script in OnSubmit, but it didnt work. Seems like CKEditor registers that event, and If I register it too, I cannot have guarantee for the order in which the callbacks will be called.
Re: Have made Asp.Net Server Control! (And little help needed)
This time is more clear now
and it's a different story, which could be easily achieved by this config entry: ... #.entities
Re: Have made Asp.Net Server Control! (And little help needed)
Man thats simple
Re: Have made Asp.Net Server Control! (And little help needed)
But its not working
I tried to set entities to true, and to false, both has no effect.
Tried also entities_additional as 'amp,lt,gt', and still no effect...
Re: Have made Asp.Net Server Control! (And little help needed)
me also... html encoding not working
Re: Have made Asp.Net Server Control! (And little help needed)
I have tried using the CKEditor.on(...) method to register the event on getData, but that is turned out to be terrible, because preview plugin also uses getData, and then when CKEditor first loads, it encode the HTML entities too so everything breaks....
After some trial I have found a way to change CKEditor to encode its output before submit, without breaking the CKEditor. I'm overriding its updateElement and calling the original method with a light change - when updateElement calls getData it will get an encode data.
So now everyone can use CKEditor within ASP.NET in the same manner they used FCKEditor!
I'm attaching my code and compile DLL (within Release folder).
Attachment is at the first post.
Re: Have made Asp.Net Server Control!
My latest comments are in the original post.
Re: Have made Asp.Net Server Control!
Thank you for all work you have done. I have some question:
1. Will this server control be the "official" server control for ckeditor?
2. I have some problem with updatepanels, when using updatepanels the toolbar disappear, if you remove the updatepanel it will work as it should. I send you an example where I have your control inside an update panel.
3. For what/How do you use the control CKSharedSpace?
Attachments:
Re: Have made Asp.Net Server Control!
Everything seems to work relative to adding taxt and saving ot to a database.
I am unable to see any toolbars. Any ideas?
Here is the control I have on my page:
<cc1:CKEditor
</cc1:CKEditor>
Thanks!
Re: Have made Asp.Net Server Control!
same here, i can't seem to see the toolbar... anyone solved this?
edited:
never mind, figured it was BasePath="~/ckeditor/", you need to have this in the control
Re: Have made Asp.Net Server Control!
hey danielgindi
thank you sooo much with this control, i'm able to port my entire FCKEditor app over to CKEditor now...
for those who are interested of storing uploaded images/files/flash to a database, i have written an app that does this (using the connector by danielgindi)
or if you are still using FCKEditor...
Re: Have made Asp.Net Server Control!
I apologize for the delay in my response, it is just that I forgot to check the "Notify me when a reply is posted", and I did not get any emails...
I think you may have missed the BasePath property. You have to tell it where is the actual CKEditor folder... usually it is at ~/ckeditor/.
<FredCK:CKEditor
There may be a bug when the basePath is not / terminated, I'll check that out.
Anyway, regarding the shared space control, it is basically a DIV container. What you do is put that control where you want the toolbar or the status bar. Then in the ckeditor you specify the control id of the shared space in the SharedSpacesTop/SharedSpacesBottom, or if you have a div which is not a server control, you can put its id in SharedSpacesTopClientID if SharedSpacesBottomClientID.
ckeditor takes care of the rest.
The shared space is any space that you wish to put your toolbar there (or that bottom status bar). I wrote the extra control just for anyone who wants to distinguish between other divs and controls to the place where they put the toolbar...
Regarding the question if this is gonna be the official control - I have no idea. I was not contacted by anyone of the CKEditor team until now. As I stated before I have no problem with my control being the official one and being updated regularly by the actual ckeditor team.
Re: Have made Asp.Net Server Control!
Hello there,
First of all thanks for this great control to .net
I though think I found a bug:
When the CKEditor is inside an update panel and you trigger the update panel, the editor change to a regular textbox.. All the buttons and the WYSIWYG function is gone..
Any idea?
Regards,
Jeppe
Re: Have made Asp.Net Server Control!
Truth is I never used Update Panels so I do not know yet how they work and where the problem could be.
I'll check it out.
Can you send me a 'working' example?
Re: Have made Asp.Net Server Control!
Well just create a standard website and put this in the form
<asp:ScriptManager
<asp:UpdatePanel
<ContentTemplate>
Editor here + a button to postback or something
</ContentTemplate>
</asp:UpdatePanel>
When it loads first time with the rest of the page there isn't any problems, but when make postback..
Well if you never used it before: ... rview.aspx
Re: Have made Asp.Net Server Control!
I know the principles how it should work, what I mean to say is I do not know its exact underlying mechanism.
Anyway I'm checking this out now
Re: Have made Asp.Net Server Control!
I tried registering the scripts with the ScriptManager when MS AJAX is available, but what happens is that MS AJAX is waiting for a callback from the ckeditor.js...
I have made added a workaround which will register the ckeditor.js on the OnInit event when there's MS AJAX, because we want to load it the 'simple' way. And it will register it only in the PreRender event when there's no MS AJAX.
In addition the CKEDITOR.replace will be called using the RegisterStartupScript of the ScriptManager when there's MS AJAX.
Try it now and tell me how it works for you!
Re: Have made Asp.Net Server Control!
Hi there Daniel,
Really great that you work this fast
I have tried with the new version of the control, and I'm sorry to inform that it doesn't work..
Instead of showing an empty textbox(as before), it completely disappear when you do a postback in the update panel.
Does that make any sense?
Re: Have made Asp.Net Server Control!
So if the script is not executed - there should be a textbox as before. If it does - there should be a CKEditor...
If you have google chrome installed, its a good tool to debug and see what happened.
I've tested my code with the example that is posted here a fews replies back, and it actually works!
One thing I can tell you that you should verify is that you have a ScriptManager on your page..
Re: Have made Asp.Net Server Control!
hi danielgindi
i confirm with marci,
control released on 2010-01-17 - textbox appears after postback
control released on 2010-01-21 - the editor disappears
<body>
<form id="form1" runat="server">
<asp:ScriptManager
<div>
<asp:UpdatePanel
<ContentTemplate>
<cc1:CKEditor
<asp:Button
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
Re: Have made Asp.Net Server Control!
Which browser do you use?
Can you upload here a package of an example 'website' in which it doesnt work?
Re: Have made Asp.Net Server Control!
here is the page..
Default.zip
AjaxControlToolkit.dll 3.0.30512.0
FredCK.CKEditor.dll 3.1.0.35312
Attachments:
Re: Have made Asp.Net Server Control!
hi danielgindi
i got 2 question regarding ckeditor for .net
1.
how do i create custom toolbars and link them to the editor
i know that CKEditor1.Toolbar = "Full" or "Basic" works, but where can i manually create my toolbar
i've tried putting it in the ckeditor.js file
i.toolbar = 'CustomToolbar';
i.toolbar_CustomToolbar =
[
['FitWindow', 'ShowBlocks', '-', 'Preview', '-', 'Templates', 'Print', 'SpellCheck'],
['Bold', 'Italic', 'Underline', 'StrikeThrough', '-', 'Subscript', 'Superscript'],
['OrderedList', 'UnorderedList', '-', 'Outdent', 'Indent'],
['Undo', 'Redo', '-', 'Find', 'Replace'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyFull'],
['Link', 'Unlink'],
['Image', 'Flash', 'Table', 'Rule', 'SpecialChar'],
'/',
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteWord'], ['Style', 'FontFormat', 'FontName', 'FontSize'],
['TextColor', 'BGColor']
];
and tried to CKEditor1.Toolbar = "CustomToolbar"
but that doesn't seem to work
EDITED:
i've putted in the config.js file
and it works
2.
create custom styles and link them to the editor...
the default style file is located in...
ckeditor/plugins/stylescombo/styles/default.js
CKEDITOR.addStylesSet('default',........
i've tried adding another line to the file so it now looks like
CKEDITOR.addStylesSet('custom_style', .......
in the code behind, i've tried
CKEditor1.StylesCombo_StylesSet = "default" ----> this works
CKEditor1.StylesCombo_StylesSet = "custom_style" ------> this doesn't work
EDITED:
i've putted in the config.js file
and it works
Re: Have made Asp.Net Server Control!
If you want to learn about all of the configurations of the cke, you can go to the docs. (Or look at the 'summary' of the configurations' set/get in my code)
Re: Have made Asp.Net Server Control!
thanks for that, will do
|
https://ckeditor.com/old/forums/CKEditor-3.x/CKEditor-Asp.Net-Server-Control-CKE-3.5-update
|
CC-MAIN-2019-35
|
refinedweb
| 3,877
| 67.86
|
RE: Sites and Services
- From: "MT" <MT@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 1 Jul 2005 11:24:01 -0700
"sambrake" wrote:
>
>
> "MT" wrote:
>
> > We just recently upgraded our NT domain to 2K3 AD. We have one corp site with
> > around 40 branches. The in place upgrade went great, however when deploying
> > DC's to other sites I am having an issue with Headquarters clients
> > authentication to a Branch.
> > We are using a mixed Bind windows DNS environment where our AD name is the
> > same as our existing Bind DNS name. The appropriate zones are handed off to
> > our windows DNS server. Our Windows DNS servers then transfer the zones to
> > the BIND dns servers. All clients/server use our BIND servers located at
> > headquartes for DNS.
> >
> > Each DC is a GC and I have configured sites and services with the
> > appropriate server for each subnet.
> > Example Branch subnet 135.74.65.0/24 assigned to Branch site Houston which
> > includes the Houston DC.
> > Branch subnet 135.74.41.0/24 assigned to Branch site Tulsa which includes
> > Tulsa DC.
> > I have not defined any subnets for the Headquarters yet. (135.74.48.0 - 55.0)
> >
> > I would like to keep Headquarters pc's from authenticating at branches...and
> > vice versa. That is the whole reason to have GC's at each site.
> >
> > My thoughts are...It might have something to do with DNS. Setup each DC at
> > each branch as a DNS server and point all client at each branch to them for
> > resolution. Setup forwaders to the BIND servers.
> >
> > Any thoughts?
> >
> >
>
> The first thing I would do is make sure that your DNS zone for your Active
> Directory namespace (i.e. contoso.com) is Active Directory integrated and has
> all of the appropriate srv records for your domain controllers and GCs. Then
> setup all of your branch DCs as DNS servers and Replicate the zone to all DNS
> servers in your domain or forest. I would get the records from your bind
> servers put into the Active Directory zone using dnscmd and then setup your
> BIND servers with secondary zones unless you want to run split-brain with
> your BIND and Windows DNS zones.
>
> For your sites you have the right idea. Put a domain controller with DNS in
> each site and setup Site links so the clients will prefer their local domain
> contoller for authentication.
All of the AD zones _msdcs _tcp etc. are all AD integrated. Our Windows DNS
servers are the authorative for those zones on the BIND side, with the BIND
servers as secondaries.
With my sites and services setup...If I configure my headquarters site with
135.74.48.0 will that affect branch offices that have no DC?
.
- Follow-Ups:
- RE: Sites and Services
- From: sambrake
- References:
- Sites and Services
- From: MT
- RE: Sites and Services
- From: sambrake
- Prev by Date: Active Desktop offline setting
- Next by Date: RE: Sites and Services
- Previous by thread: RE: Sites and Services
- Next by thread: RE: Sites and Services
- Index(es):
|
http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.server.active_directory/2005-07/msg00074.html
|
crawl-002
|
refinedweb
| 503
| 73.88
|
Transfer focus to SwipeView inner element
- egor.utsov
Hi all. What i am trying to achieve: I have custom QML component
CustomElemwith SwipeView inside. SwipeView by itself can contain different components inside and i want to transfer focus to one of them when
CustomElemcomponent take focus.
For example:
main.qmlloaded --> user push button and one of
CustomElemin
main.qmlbecomes focused (
elem.focus = true) --> focus is transferred through object hierarchy inside
CustomElem, through SwipeView down to element inside the SwipeView, that have property
focus: true.
In my example i want that inner
Rectangle
activeFocusproperty becomes
true.
I have QML component
CustomElem.qmlwith following code:
import QtQuick 2.0 import QtQuick.Controls 2.2 Item { id: rootItem objectName: "rootItem" width: parent.width height: parent.height SwipeView { anchors.fill: parent objectName: "swipeView" Rectangle { id: innerRect objectName: "rectInRect" focus: true color: activeFocus ? "orange" : "black" } } }
This component used in
main.qmlas followed:
import QtQuick 2.9 import QtQuick.Window 2.2 Window { objectName: "window" visible: true width: 640 height: 480 title: qsTr("Hello World") Item { id: keyHandler objectName: "keyHandler" } CustomElem { width: 200 height: 200 focus: true } CustomElem { width: 200 height: 200 y: 200 } }
- poor_robert
Hello,
I have very similar problem. Did you find any solution?
poor_robert
- Diracsbracket
@egor.utsov
Maybe this post would help?
- egor.utsov
@poor_robert Hi! I used
KeyNavigation.down: swipe.currentItemin the element root
Item. But i think it is the same as
forceActiveFocus.
|
https://forum.qt.io/topic/92110/transfer-focus-to-swipeview-inner-element
|
CC-MAIN-2018-43
|
refinedweb
| 232
| 55
|
. On the Xamarin alpha channel, create a binding project.
2. In my case the name of the project was xf.Beacons.
3. Import the native library and populate the ApiDefinitions.cs file till all APIs are bounded.
4. Build Debug or Build Release. Same error.
Got this error:
namespace MonoTouch {
[CompilerGenerated]
static class Libraries {
static public class xf.Beacons {
static public readonly IntPtr Handle = Dlfcn.dlopen (Constants.xf.BeaconsLibrary, 0);
}
}
}
Debug/ios/ObjCRuntime/Libraries.g.cs(25,25): Error CS1519: Unexpected symbol `.' in class, struct, or interface member declaration (CS1519) (xf.Beacons)
Any ideas?
Ok I think this needs to be escalated. May be I'm doing something wrong or the library that was supplied has issue or it is an issue with Xamarnin.
I'm attaching the project.
I'm having the exact same problem while binding an Objective-C library. Did you ever figure out a solution?
Have not seen this for a long time.
Created attachment 7024 [details]
Test project showing the bug
The problem is caused when binding a static library and not using "_Internal" as the "libraryName" when flagging a property with the Field attribute.
In my case I had something like this:
ObjC:
@implementation TestLibrary
NSString * const TheString = @"A String";
@end
C#:
namespace InvalidClassTest.Foo.Bar
{
[BaseType (typeof(NSObject))]
public partial interface TestLibrary {
[Field ("TheString")]
NSString TherStringTest { get; }
}
}
Adding "__Internal" to the Field attribute as mentioned on the FieldAttribute section[1] of the bindings reference guide fixed the problem.
...
[Field ("TheString", "__Internal")]
...
Another side effect of not setting libraryName to "__Internal" is mentioned on this SO[2] thread.
Steps to reproduce:
1. Unzip the attachment and go into its directory via terminal
2. make
Result:
Build fails with the following error:
...
lipo -create -output libTestLibrary.a libTestLibrary-i386.a libTestLibrary-armv7.a
/Developer/MonoTouch/usr/bin/btouch ApiDefinition.cs StructsAndEnums.cs libTestLibrary.linkwith.cs --out=TestLibrary.dll --link-with=libTestLibrary.a,libTestLibrary.a
ObjCRuntime/Libraries.g.cs(35,39): error CS1519: Unexpected symbol `.' in class, struct, or interface member declaration
ObjCRuntime/Libraries.g.cs(35,48): error CS1519: Unexpected symbol `{' in class, struct, or interface member declaration
ObjCRuntime/Libraries.g.cs(39,0): error CS1525: Unexpected symbol `}'
Compilation failed: 3 error(s), 0 warnings
btouch: API binding contains errors.
make: *** [TestLibrary.dll] Error 1
Expected Result:
Build should fail with a more descriptive error about the actual problem, instead of complaining about unrelated symbols.
This is what I had installed on my machine at the time I reproduced the bug:
Xamarin Studio 4.2.3
Runtime:
Mono 3.2.6 ((no/9b58377)
GTK+ 2.24.23 theme: Raleigh
GTK# (2.12.0.0)
Package version: 302060000
Xamarin iOS 7.2.1.42 (Business Edition)
Mac OS X 10.9.3
Xcode 5.1.1 (5085)
[1]
[2]
The original description and comment #5 sounds like different issues. @Alex can you check both case and see if the issue still exists in master ? thanks!
Fixed in
|
https://bugzilla.xamarin.com/17/17232/bug.html
|
CC-MAIN-2021-25
|
refinedweb
| 491
| 52.76
|
The ObjDict class has many uses including: as a tool for processing and generating json information, for ad-hoc classes and mutable named tuples, or just as dictionaries that allow dot notation access.
pip install objdict==0.4.4
Why an 'ObjDict'? The reasons include:
- The ad-hoc structure/object 'swiss army knife' class.
- Support for JSON message encoding and decoding.
- ObjDict in place of dictionaries as convenient ad-hoc data structures.
- Mutable equivalent to nametuple (or namedlist).
- Adding JSON serialization to classes.
- OrderedDict alternative.
- History and acknowledgements.
- JsonWeb alternative to ObjDict JSON processing.
- Multiple uses of dictionaries.
- Introducing the ObjDict.
- Multiple modes of dictionary use and JSON.
- ObjDict JSON general.
- ObjDict JSON load tools.
- ObjDict JSON dump tools.
- General notes and restrictions.
- Initialisation and JSON load.
- 'str' and JSON dumps.
- Custom classes and JSON.
- Maintaining order with custom classes and defaults.
As described in this 'uses' 'ObjDict' can be a replacement for several other classes, plus provide best tools for working with JSON data..
See the text below on 'multiple uses of dictionaries' for background. There is a significant amount of code where dictionaries have been used for ad-hoc structures. The use case often arises where it can become useful if these data structure can have elements accessed in the simpler are many.
There are occasions where a 'named 'object state' information.
OrderedDicts do everything dictionaries can, and in some applications it can be useful to simply move to OrderedDict classes for all dictionaries. 'ObjDict' is another alternative, with a shorter name, even more flexibility and power, and a much more readable 'str' representation that can also be used for clearer initialisation. See instructions for details on 'str' and initialisation flexibility.
- History and acknowledgements.
- JsonWeb alternative to ObjDict JSON processing.
- Multiple uses of dictionaries.
- Introducing the ObjDict.
- Multiple modes of dictionary use and JSON.
- ObjDict JSON general.
- ObjDict JSON load tools.
- ObjDict JSON dump tools.
The project emerged from a need for code to generate and decode JSON messages. Originally the package JsonWeb was selected for the task, but it became clear the use case differed. 'Json class.
The project 'JsonWeb' overlaps is use cases with this project. The focus of 'JsonWeb' is to provide for serializing python object structures and instancing python objects from the serialized form. ObjDict can be used for this role also, but currently lacks the validation logic used by 'Json.
In python, dictionaries are designed as 'collections' 'bob' or 'jane'. The data associated with 'bob' or 'jane' is of the same type and is interpreted the same way. For an 'ad.
An ObjDict is a subclass of dictionary designed to support this second 'ad.
The standard JSON dump and load map JSON 'objects' to python dictionaries. JSON objects even look like python dictionaries (using {} braces and a ':'). 'name' is really an object but 'color 'name' is not ideal as the 'keys' rather than being entries in a collections each have specific meaning. Keys should not really have meaning, and these keys are really 'attributes' 'objects' to a new python ObjDict (Object Dictionaries). These act like OrderedDictionaries, but can also be treated as python objects.
So 'dump' or '__JSON__()' or 'str()' / '__str__()' of the 'names' and 'colour_codes' example above produces an outer ObjDict containing two inner 'ObjDict's, 'name' and 'colour_codes'. Assume the outer ObjDict is assigned to a variable called 'data'. 'str' or 'dump' back to the original JSON as above. However if the original string was changed to:
{ "name": {"first": "fred", "last": "blogs", "__type__": "Name" } "colour_codes":{"red": 100, "green": 010, "yellow": 110, "white": 111 } }
The JSON 'load' used to load or initialise ObjDict uses an 'object_pairs_hook' that checks a table of registered class names and corresponding classes.
If there is an entry in the table, then that class will be used for embedded objects. Entries with no '__type__' result in ObjDict objects, and if the 'DefaultType` is set then a class derived from the default type, with the name from the value of '__type__' will be returned. If 'DefaultType' is None, then an exception will be generated.
See the instructions section for further information. 'top-level' object, there may be many embedded objects and identifying and processing these embedded objects is the actual challenge.
In general, handling embedded objects is achieved through the '__from_JSON__' class method within each class for the 'JSON.load', or the '__JSON__' method within each object for the 'JSON.dump'.
Standard routines to perform these methods are available, together with the tools to easily decorate classes and other utilities.
The three main tools for loading JSON objects are an 'object_pairs_hook' method to be passed to the standard 'JSON.load' function, the '__from_JSON__' class method that can be added to any class to control instancing the class from JSON and the 'from_JSON' decorator.
The philosophy is the use of simple, flexible building blocks.
object_pairs_hook
A class within the objdict module, 'ObjPairHook', is a wrapper tool to provide a function for the standard library JSON.load() function. Simply instance an ObjPairHook and pass the 'from_JSON' method to JSON_load(). eg:
hook=ObjPairHook().from_JSON JSON.load(object_pairs_hook=hook) class ObjPairsHook() def __init__(classes_list=[],BaseHook=None,BaseType=None):
The 'from_JSON' method will check all JSON objects for a '__type__' entry, or use 'default' processing. For objects with a '__type__', both the entries in the 'classes_list' parameter and the default_classes_list maintained within the objdict module and added to through the 'from_JSON' decorator, can be instanced if there is a name match.
For objects with '__type__' entries but no name match with either source of classes then the a dynamic class based on 'BaseClass' is generated and selected as the 'class'.
For objects with no '__type__' entry, then the 'BaseHook' is selected as the 'class' (although in practice is it also possible to use a method rather than a class).
Once a class is selected, then if this class has a '__from_JSON__' attribute, then this class method is called to instance an object, otherwise the normal init method for the class is called.
__from_JSON__class method
Providing a '__from_JSON__' class method is called to instance an the object by the 'object_pairs_hook' if an attribute of this name is present.
from_JSONdecorator
The from_JSON decorator, when used to decorate a class, adds the class to default_class list used by the object_pairs_hook.
The '_ '__JSON__'
method within each object, or from a table of class/converter pairs.
The JSON_encoder class does the actual encoding, and for each object it first checks for a '__JSON__' method and class that method if present. For objects defined outside of scope e.g. Decimal(), the encoder checks the encoder_table for a matching entry and if present calls that encoder.
to_JSONdecorator
This decorator checks if the class has a '__JSON__' method, and if not, decorates the class with a default '__JSON__' method. The '_.
This is an object which can be imported from the objdict module to access the
'add_to' method (
JSON_registry.add_to(<class>,<method/function>). By default, the
table contains entries for Decimal, datetime.datetime and datetime.time.
Any entry can be overwritten by simply adding new values for the same class.
- General notes and restrictions.
- Initialisation and JSON load.
- 'str' and JSON dumps.
- Custom classes and JSON.
- Maintaining order with custom classes and defaults. 'scaffolding' added as extensions to the ObjDict class or to derived classes, where this scaffolding is not to be included as also dictionary data.
ObjDict can be initialised from lists, from JSON strings, from dictionaries, from parameter lists or from keyword parameter lists.
Examples:
a = ObjDict('{"a": 1, "b": 2}') class XYZ(ObjDict): __keys__ = 'x y z' xyz = XYZ(10,20,30) xyz.y == 20
Initialisation from a list of key value pairs, as with OrderedDict class is supported. Beyond key value pairs, there is also support for direct initialisation from lists. The '_keys' parameter must be included for initialisation from lists. Also, Classes derived from ObjDict can have '_keys' as a class attribute, providing a similar use pattern to the 'namedtuple'. '_keys' can be either a list of strings, or a string with space or comma separated values. When initialising from a list or parameter list, the list size must match the number of keys created through '_keys', however other items can be added after initialisation.
So this code produces True:
class XY(ObjDict): __keys__ = 'x y' sample = XY(1, 3) sample.x, sample.y == 1, 3
Alternatively the form to produce a similar result but with the SubClass would be:
sample = ObjDict(1, 3, __keys__ = 'x y') sample = ObjDict([1, 3] ,__keys__ = 'x y')
For more complex initialisation, JSON strings can provide an ideal solution. This allows for complex structures with nested/embedded 'Obj.
As discussed already, initialisation from dict or key word arguments will not maintain order of keys, but if order is not important, such as when the data has already been inserted into a dictionary.
A limitation with OrderDict objects is that 'str' representation can be clumsy when the structure is nested.
The '__str__' method of ObjDict class calls the '__JSON__' method. '__str__' can be overridden without disturbing the '__JSON__' method. To convert an ObjDict to JSON, simply call either of these methods.
For working with ObjDict objects or other objects using 'json.dumps' the objdict module provides a 'JsonEncoder' object to use as a parameter to 'json.dumps', and an alternative 'dumps' with the encoder as a default parameter:
import json from objdict import JsonEncoder json.dumps(<object>, cls=JsonEncoder) or import objDict objdict.dumps(<object>)
Simple decorate other classes with the 'to_json' decorator and these will also then encode using their __json__ method.
Also other classes, including classes already defined without a __json__ method can register together with an appropriate method of function to produce json from those objects.
Custom classes allow for JSON data to result in instantiating objects other
than ObjDict from JSON data. These custom classes can be sub-classed from ObjDict
or built simply using the
@to_JSON() and/or
@from_JSON() decorators.
If sub-classing from ObjDict, then your class should not need to be decorated with either of the from/to decorators. Such class will make use of code in the standard __init__ method of ObjDict and standard ObjDict json encoding/decoding method.'))
The alternative to subclassing ObjDict avoids inheriting other properties of
ObjDict which may not be relevant to the application. The
@to_JSON decorator
decorates a class with a '_ '__JSON__' method, in addition to any classes in the JSON_registry.
The JSONEncoder encodes all classes added to the JSON_registry, as well as any class with a '__JSON__' method. Classes such as datetime.date or decimal.Decimal are standard library classes and it may not be convenient to sub-class these to have a '__JSON__' method. For these cases, calling the add_to method of the JSON_registry allows adding these objects to be encoded.
For example:
from objdict import JSON_registry JSON_registry.add_to(datetime.date, str)
This will ensure JSONEncoder will use the 'str' function to encode dates.
The
@from_json() decorator adds the class to the class register internal to the
objdict module, to then be used by the 'object>)
The from_json(type_name=None,use=None) can be supplied with a alternate name if desired to overide the class name for __type__ entries in the json text, plus a 'use ' setting which applies for cases where no '__from_json__ class method is present. The 'use' setting can specify a fuction to instantiate objects. The method must take two parameters, a class, and an orderdictionary of values.
Alternately, 'use' as None, will simply instantiate a class from the __init__ method and supply all values from the json text as keyword arguments.
Setting 'use'
To call json.loads, instance an ObjPairHook object and then pass the decode method of that object to json.loads.
The decode method will, for all classes in the load_class_register, check if the class has a '__from_JSON__' class method, and if present, call the '_ 'unParsed'
{ "name":{ __type__: "Name" "first": "joe", "last": "foo" } }
Decoding automatically to objects can then be added at a later time. '__init__' method. Note, the order attributes are set will be their order in a message. Classes sub-classed from ObjDict will have '_ 'ObjDict' and custom classes. In JSON representation a '_ 'ObjDict' objects.
|
https://libraries.io/pypi/objdict
|
CC-MAIN-2020-40
|
refinedweb
| 2,031
| 56.76
|
In my day job at Blend, I write a lot of TypeScript1. One great feature of TypeScript is the ability to specify an enum with a finite set of values as a union type:
type Coordinate = 'x' | 'y'
which then gives compile time checking for values of this type
const coordinate: Coordinate = 'x' // This will not compile: const coordinate: Coordinate = 'donut'
Contents
What's Missing
Unfortunately, there is no utility built into the language that will provide
an array of the values in the union type. I.e. for our
Coordinate type, we
often want:
const COORDINATES: Coordinate[] = ['x', 'y'] // Or even better, make it immutable: Object.freeze(['x', 'y'])
Such a
COORDINATES array has many uses. It's common to use such an array
to write a type guard
function isCoordinate(value: string): value is Coordinate { return COORDINATES.includes(value) }
or to specify a
Joi schema for an external facing API:
import * as Joi from '@hapi/joi' const REPLACE_VALUE: Joi.ObjectSchema = Joi.object({ id: Joi.string().guid().required(), coordinate: Joi.string().valid(COORDINATES).required(), value: Joi.number().required(), })
What Can Go Wrong
It's easy enough to just hardcode
COORDINATES to exactly agree with your
Coordinate union type and feel happy that it's a comprehensive coverage of
the values. Even better, since
COORDINATES has the type
Coordinate[], you
have a guarantee2 from the
tsc
compiler that you won't have any invalid values.
However, let's say one day your codebase decides to expand from 2D into 3D:
type Coordinate = 'x' | 'y' | 'z'
None of the rest of your code will break, but it should have! Your
COORDINATES covering set is no longer a covering set, but both
x and
y
are valid. Calling
isCoordinate('z') will return
false (which is a lie)
and your
REPLACE_VALUE schema will reject calls to your API that want to
replace the
z value.
How Can We Fix It
By hardcoding
COORDINATES we've accidentally made our codebase brittle. The
['x', 'y'] literal encodes an assumption about our code that is not
checked anywhere at all. Also, the
tsc compiler has no hope in helping us
because
COORDINATES is a value, not a type, so
tsc isn't able to
make any extra assertions to act as a guard rail.
Unit tests to the rescue! We can write a single unit test (with
ava)
that is guaranteed to fail if either the
Coordinate union type or the
COORDINATES value is changed:
import test from 'ava' test('COORDINATES covers the Coordinate union type', t => { const asKeys: Record<Coordinate, number> = { x: 0, y: 0 } const expectedKeys = Object.keys(asKeys).sort() // NOTE: Sort `COORDINATES` without mutating it. const actualKeys = COORDINATES.concat().sort() t.deepEqual(expectedKeys, actualKeys) })
Using the
Record<> type allows the compiler to tell us if any
members of the
Coordinate are absent keys in
asKeys. Then at runtime
we use
Object.keys() to convert those (already compiler checked) keys into
a value
expectedKeys. Then we can ensure that
expectedKeys is verified
against
COORDINATES.
But What About ...
The snippet in the unit test absolutely provides a template for doing this inline (i.e. without the support of a unit test):
type Coordinate = 'x' | 'y' const asKeys: Record<Coordinate, number> = { x: 0, y: 0 } const COORDINATES: Coordinate[] = Object.keys(asKeys)
however, this snippet of code will fail due to the return type of
Object.keys():
$ tsc snippet.ts snippet.ts:6:7 - error TS2322: Type 'string[]' is not assignable to type 'Coordinate[]'. Type 'string' is not assignable to type 'Coordinate'. 6 const COORDINATES: Coordinate[] = Object.keys(asKeys) ~~~~~~~~~~~ Found 1 error.
So in order to use it, you'd need to resort back to a type assertion (and IMO type assertions should be avoided at all costs).
Additionally, though declaring
asKeys only takes up one line, it's a bit
of an eyesore in source code (vs. test code). As the number of allowed
values in a given union type goes up, declaring
asKeys inline will look even
worse.
Related Approaches
I've also had cases where I had a use in my code for a mapping identical to what
was provided by
Record<>. It's equally fine to define that mapping
directly and derive the
Coordinate union type from it via the
keyof keyword
interface Point { x: number y: number } type Coordinate = keyof Point
Then the unit test will change ever so slightly3
const asKeys: Point = { x: 0, y: 0 }
In codebases where "no magic constants" is a rule4, a convenience
enum can
be provided to give named variables for each value in the
Coordinate type:
enum CoordinateNames { x = 'x', y = 'y', } type Coordinate = keyof typeof CoordinateNames
Since a TypeScript
enum is really just an
object, we can use it
directly in our unit test without having to form the stand-in
asKeys value
const expectedKeys = Object.keys(CoordinateNames).sort()
- This may surprise many of my colleagues from the Python world ↩
- Provided you don't use any
as Coordinate[]type assertion funny business ↩
- In cases where some of the keys are optional, a
Required<Point>must be used for the type of
asKeys. The
Required<>type was added in TypeScript 2.8.) ↩
- I.e. typing
'x'or
'y'would not be allowed ↩
|
https://blog.bossylobster.com/2019/06/type-guards-for-union-types.html
|
CC-MAIN-2021-21
|
refinedweb
| 867
| 52.09
|
i am sending my attachment of the java file.
i have tried to put image with 3 buttons and 1 label.n in label image should be display. n when i click on button it changes the different images.but i didnt get success. even i dont get image in the frame. please tell me where i am wrong in the code n give me directions what should i do.
change images on button clickPage 1 of 1
1 Replies - 9568 Views - Last Post: 19 October 2010 - 10:46 AM
#1
change images on button click
Posted 19 October 2010 - 09:36 AM
Replies To: change images on button click
#2
Re: change images on button click
Posted 19 October 2010 - 10:46 AM
You need something like the following:
public class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent ae) { if (ae.getSource() == up) { k %= mypictures.length; ImageIcon icon1 = new ImageIcon(mypictures[k]); display.setIcon(icon1); k++; //repaint(); } } }
Page 1 of 1
|
http://www.dreamincode.net/forums/topic/195740-change-images-on-button-click/
|
CC-MAIN-2016-44
|
refinedweb
| 162
| 66.13
|
Cycle through Objects return only Nulls with polys
On 11/02/2014 at 01:45, xxxxxxxx wrote:
Hello everyone,
I need to cycle through a Object tree which consists of Null-Objects and Poly-Objects, nested.
Afterwards the selected "Null" will be merged to one Poly-Object.
But I need only the "deepest" Null Object and want to leave the Nulls in Nulls untouched.
Null-1
-Null-2
--Null-3 <- this should be returned
---Poly
---Poly
---Poly
--Null-4 <- this should be returned
---Poly
---Poly
---Poly
-Null-5
--Null-6 <- this should be returned
---Poly
---Poly
---Poly
Standard Python cycle - how to modify?
def GetNextObject(op) : if not op: return if op.GetDown() : return op.GetDown() while op.GetUp() and not op.GetNext() : op = op.GetUp() return op.GetNext()
thanks in advance for any help.
mogh
On 11/02/2014 at 07:17, xxxxxxxx wrote:
Use recursion. You can make the function return True if a Null Object was found in the hierarchy
and False if not. If you get False from a recursive call and are currently at a Null Object, you've found
the Null-Object at the lowest level.
function find_lowest_nullobjects(current, result_list) returns bool has_nullobject = false for each child in current has_nullobject = find_lowest_nullobjects(child, result_list) if has_nullobject is true break loop endif endfor if current is "Null Object" and has_nullobject is false add current to result_list endif return current is "Null Object" endfunction
-Niklas
Edit: Fixed return value of function in pseudo-code
On 12/02/2014 at 00:27, xxxxxxxx wrote:
Thanks Niklas,
I have trouble reading your code, and it hast lists which I still have trouble implementing into my scripts, guess i need a few weeks to understand what you gave me here.
thanks for your time.
this is the code i want to update to goo deep instead of only ging flat:
Edit_ removed code hence it doesn't contribute to the discussion.
kind regards mogh
On 17/02/2014 at 06:35, xxxxxxxx wrote:
This is my coding so far ...
def GetNextObject(op) : if not op: return if op.GetDown() : return op.GetDown() while op.GetUp() and not op.GetNext() : op = op.GetUp() return op.GetNext() def find_lowest_nullobjects(op, nullobj_list) : has_nullobject = False all_list = list() opchildren = op.GetChildren() for child in opchildren: has_nullobject = find_lowest_nullobjects(child, nullobj_list) if has_nullobject is True: break if op.GetType() == 5140 and has_nullobject == False: nullobj_list.append(op) while op: all_list.append(op) op = GetNextObject(op) return {'all_objects_list' : all_list, 'null_obj_list' : nullobj_list }
On 17/02/2014 at 08:02, xxxxxxxx wrote:
Give this code a shot.
All of the logic occurs in one single method rather than using several methods.
*Make sure you test it thoroughly though. Because I just whipped it up in 5 minutes. And I haven't fully tested it in battle.
#This code searches for the last Null object in each tree branch(But not single Null objects) #Then stores them in a list array import c4d nulls = [] def SearchOM(op) : while(op) : if op.GetType()==c4d.Onull and not op.GetDown() and op.GetUp() : nulls.append(op) break SearchOM(op.GetDown()) op = op.GetNext() def main() : SearchOM(doc.GetFirstObject()) print nulls if __name__=='__main__': main()
-ScottA
On 18/02/2014 at 01:26, xxxxxxxx wrote:
Thanks ScottA:
I did remove the "NOT" in your if and i get some Nulls in my list but it discards nulls in the same level.
-Null
--null-a
--null-b
-Null
--null-d
--null-e
In this case it returns (a, d)
any ideas?
kind regards
On 18/02/2014 at 14:12, xxxxxxxx wrote:
This turned out to be lot harder than I thought it would be.
Targeting the first Null child object of each tree branch is fairly simple.
But the hard part is trying to target the first null object inside of any inner tree branches.
Using break the way I did prevented me from checking those sub branches.
After a lot of trial and error. I came up with this.
It should target the first Null object (even the sub branches of main branches) and put them into a list:
import c4d nulls = [] def SearchOM(op) : while(op) : if op.GetUp() : parent = op.GetUp() firstChild = parent.GetDown() #print firstChild.GetName() if firstChild.GetType()==c4d.Onull: #print firstChild.GetName() if not firstChild in nulls: nulls.append(firstChild) if firstChild.GetDown() : break SearchOM(op.GetDown()) op = op.GetNext() def main() : firstObj = doc.GetFirstObject() SearchOM(firstObj) print nulls c4d.EventAdd() if __name__=='__main__': main()
I'm not sure if I got it all correct.
Dealing with those sub branches is pretty tricky stuff.
-ScottA
|
https://plugincafe.maxon.net/topic/7697/9722_cycle-through-objects-return-only-nulls-with-polys
|
CC-MAIN-2020-10
|
refinedweb
| 766
| 68.87
|
hypothesis (1) - Linux Man Pages
hypothesis: Hypothesis Documentation
NAMEhypothesis - Hypothesis Documentation
Hypothesis is a Python library for creating unit tests which are simpler to write and more powerful when run, finding edge cases in your code you wouldn't have thought to look for. It is stable, powerful and easy to add to any existing test suite.
It works by letting you write tests that assert that something should be true for every case, not just the ones you happen to think of.
Think of a normal unit test as being something like the following:
- 1.
- Set up some data.
- 2.
- Perform some operations on the data.
- 3.
- Assert something about the result.
Hypothesis lets you write tests which instead look like this:
- 1.
- For all data matching some specification.
- 2.
- Perform some operations on the data.
- 3.
- Assert something about the result.
This is often called property based testing, and was popularised by the Haskell library Quickcheck..:
- •
- Your code shouldn't throw an exception, or should only throw a particular type of exception (this works particularly well if you have a lot of internal assertions).
- •
- If you delete an object, it is no longer visible.
- •
-.
QUICK START GUIDE
This document should talk you through everything you need to get started with Hypothesis.
An example else: else:
Hypothesis is available on pypi as "hypothesis". You can install it with:
pip install hypothesis
If you want to install directly from the source code (e.g. because you want to make changes and install the changed version) you can do this with:
pip install -e .:
- 1.
-.
- 2.
- Look for duplication in your tests. Are there any cases where you're testing the same thing with multiple different examples? Can you generalise that to a single test using Hypothesis?
- 3.
- This piece is designed for an F# implementation, but is still very good advice which you may find helps give you good ideas for using Hypothesis.
If you have any trouble getting started, don't feel shy about asking for help.
DETAILS AND ADVANCED FEATURES
This is an account of slightly less common Hypothesis features that you don't need to get started but will nevertheless make your life easier.
Additional test output, 0, 1], r=RandomWithSeed(0)) Shuffle: [0, 1, 0] ls != ls2
The note is printed in the final run of the test in order to include any additional information you might need in your test.
Test Statistics
If you are using py.test: - 200 passing examples, 0 failing examples, 0 invalid examples - Typical runtimes: < 1ms - Stopped because settings.max_examples=200: - 200 passing examples, 0 failing examples, 16 invalid examples - Typical runtimes: < 1ms - Stopped because settings.max_examples=200 - Events: * 30.56%, Retried draw from integers().filter(lambda x: x % 2 == 0) to satisfy filter * 7.41%, Aborted test because unable to satisfy integers().filter(lambda x: x % 2 == 0)
- hypothesis.event(value)
- Record an event that occurred this test. Statistics on number of test runs with each event will be reported at the end if you run Hypothesis in statistics reporting mode.
Events should be strings or convertable to them.
You can also mark custom events in a test using the 'event' function:
from hypothesis import given, event, strategies as st @given(st.integers().filter(lambda x: x % 2 == 0)) def test_even_integers(i): event("i mod 3 = %d" % (i % 3,))
You will then see output like:
test_even_integers: - 200 passing examples, 0 failing examples, 28 invalid examples - Typical runtimes: < 1ms - Stopped because settings.max_examples=200 - Events: * 47.81%, Retried draw from integers().filter(lambda x: x % 2 == 0) to satisfy filter * 31.14%, i mod 3 = 2 * 28.95%, i mod 3 = 1 * 27.63%, i mod 3 = 0 * 12.28%, Aborted test because unable to satisfy integers().filter(lambda x: x % 2 == 0)
Arguments to event() can be any hashable type, but two events will be considered the same if they are the same when converted to a string with str().
Making assumptions
Sometimes Hypothesis doesn't give you exactly the right sort of data you want - it's mostly of the right shape, but some examples won't work and you don't want to care about them. You can just ignore these by aborting the test early, but this runs the risk of accidentally testing a lot less than you think you are. Also it would be nice to spend less time on bad examples - if you're running 200 examples per test (the default) and it turns out 150 of those examples don't match your needs, that's a lot of wasted time.
- hypothesis.assume(condition)
- assume() is like an assert that marks the example as bad, rather than failing the test.
This allows you to specify properties that you assume will be true, and let Hypothesis try to avoid similar examples in future.
For example suppose had the following test:
@given(floats()) def test_negation_is_self_inverse(x): assert x == -(-x)
Running this gives us:
Falsifying example: test_negation_is_self_inverse(x=float('nan')) AssertionError
This is annoying. We know about NaN and don't really care about it, but as soon as Hypothesis finds a NaN example it will get distracted by that and tell us about it. Also the test will fail and we want it to pass.
So lets block off this particular example:
from
How good is assume?
Hypothesis has an adaptive exploration strategy to try to avoid things which falsify assumptions, which should generally result in it still being able to find examples in hard to find situations.
Suppose we had the following:
@given(lists(integers())) def test_sum_is_positive(xs): assert sum(xs) > 0
Unsurprisingly this fails and gives the falsifying example [].
Adding assume(xs) to this removes the trivial empty example and gives us [0].
Adding assume(all(x > 0 for x in xs)) and it passes: A sum of a list of positive integers is positive.
The reason that this should be surprising is not that it doesn't find a counter-example, but that it finds enough examples at all.
In order to make sure something interesting is happening, suppose we wanted to try this for long lists. e.g. suppose we added an assume(len(xs) > 10) to it. This should basically never find an example: A naive strategy would find fewer than one in a thousand examples, because if each element of the list is negative with probability half, you'd have to have ten of these go the right way by chance. In the default configuration Hypothesis gives up long before it's tried 1000 examples (by default it tries 200).
Here's what happens if we try to run this:
@given(lists(integers())) def test_sum_is_positive(xs): assume(len(xs) > 10) assume(all(x > 0 for x in xs)) print(xs) assert sum(xs) > 0 In: test_sum_is_positive() [17, 12, 7, 13, 11, 3, 6, 9, 8, 11, 47, 27, 1, 31, 1] [6, 2, 29, 30, 25, 34, 19, 15, 50, 16, 10, 3, 16] [25, 17, 9, 19, 15, 2, 2, 4, 22, 10, 10, 27, 3, 1, 14, 17, 13, 8, 16, 9, 2... [17, 65, 78, 1, 8, 29, 2, 79, 28, 18, 39] [13, 26, 8, 3, 4, 76, 6, 14, 20, 27, 21, 32, 14, 42, 9, 24, 33, 9, 5, 15, ... [2, 1, 2, 2, 3, 10, 12, 11, 21, 11, 1, 16]
As you can see, Hypothesis doesn't find many examples here, but it finds some - enough to keep it happy.
In general if you can shape your strategies better to your tests you should - for example integers(1, 1000) is a lot better than assume(1 <= x <= 1000), but assume will take you a long way if you can't.
Defining strategies
The type of object that is used to explore the examples given to your test function is called a SearchStrategy. These are created using the functions exposed in the hypothesis.strategies module.
Many of these strategies expose a variety of arguments you can use to customize generation. For example for integers you can specify min and max values of integers you want. If you want to see exactly what a strategy produces you can ask for an example:
>>> integers(min_value=0, max_value=10).example() 5
Many strategies are build out of other strategies. For example, if you want to define a tuple you need to say what goes in each element:
>>> from hypothesis.strategies import tuples >>> tuples(integers(), integers()).example() (50, 15)
Further details are available in a separate document.
The gory details of given parameters
- hypothesis.given(*given_arguments, **given_kwargs)
- A decorator for turning a test function that accepts arguments into a randomized test.
This is the main entry point to Hypothesis.
The @given decorator may be used to specify what arguments of a function should be parametrized over. You can use either positional or keyword arguments or a mixture of the two.
For example all of the following are valid uses:
@given(integers(), integers()) def a(x, y): pass @given(integers()) def b(x, y): pass @given(y=integers()) def c(x, y): pass @given(x=integers()):
- 1.
- You may pass any keyword argument to given.
- 2.
- Positional arguments to given are equivalent to the rightmost named arguments for the test function.
- 3.
- positional arguments may not be used if the underlying test function has varargs or arbitrary keywords.
- 4.
- Functions tested with given may not have any defaults.
The reason for the "rightmost named arguments" behaviour is so that using @given with instance methods works: self will be passed to the function as normal and not be parametrized over.
The function returned by given has all the arguments that the original test did , minus the ones that are being filled in by given.
Custom function execution
Hypothesis provides you with a hook that lets you control how it runs examples.
This lets you do things like set up and tear down around each example, run examples in a subprocess, transform coroutine tests into normal tests, etc.
The way this works is by introducing the concept of an executor. An executor is essentially a function that takes a block of code and run it. The default executor is:
def default_executor(function): return function()
You define executors by defining a method execute_example on a class. Any test methods on that class with @given used on them will use self.execute_example as an executor with which to run tests. For example, the following executor runs all its code twice:
from unittest import TestCase class TestTryReallyHard(TestCase): @given(integers()) def test_something(self, i): perform_some_unreliable_operation(i) def execute_example(self, f): f() return f()
Note: The functions you use in map, etc. will run inside the executor. i.e. they will not be called until you invoke the function passed to setup import inspect class TestRunTwice(TestCase): def execute_example(self, f): result = f() if inspect.isfunction(result): result = result() return result
Using Hypothesis to find values
You can use Hypothesis's data exploration features to find values satisfying some predicate. This is generally useful for exploring custom strategies defined with @composite, or experimenting with conditions for filtering data.
- hypothesis.find(specifier, condition, settings=None, random=None, database_key=None)
- Returns the minimal example from the given strategy specifier that matches the predicate function condition.
>>> from hypothesis import find >>> from hypothesis.strategies import sets, lists, integers >>> find(lists(integers()), lambda x: sum(x) >= 10) [10] >>> find(lists(integers()), lambda x: sum(x) >= 10 and len(x) >= 3) [0, 0, 10] >>> find(sets(integers()), lambda x: sum(x) >= 10 and len(x) >= 3) {0, 1, 9}
The first argument to find() describes data in the usual way for an argument to given, and supports all the same data types. The second is a predicate it must satisfy.
Of course not all conditions are satisfiable. If you ask Hypothesis for an example to a condition that is always false it will raise an error:
>>> find(integers(), lambda x: False) Traceback (most recent call last): ... hypothesis.errors.NoSuchExample: No examples of condition lambda x: <unknown>
(The lambda x: unknown is because Hypothesis can't retrieve the source code of lambdas from the interactive python console. It gives a better error message most of the time which contains the actual condition)
Providing explicit examples
You can explicitly ask Hypothesis to try a particular example, using
- hypothesis.example(*args, **kwargs)
- A decorator to that ensures a specific example is always tested.
Hypothesis will run all examples you've asked for first. If any of them fail it will not go on to look for more examples.
It doesn't matter whether you put the example decorator before or after given. Any permutation of the decorators in the above will do the same thing.
Note that examples can be positional or keyword based. If they're positional then they will be filled in from the right when calling, so.
SETTINGS
Hypothesis tries to have good defaults for its behaviour, but sometimes that's not enough and you need to tweak it.
The mechanism for doing this is the settings object. You can set up a @given based test to use this using a settings decorator:
@given invocation as follows:
from hypothesis import given, settings @given(integers()) @settings(max_examples=500) def test_this_thoroughly(x): pass
This uses a settings object which causes the test to receive a much larger set of examples than normal.
This may be applied either before or after the given and the results are the same. The following is exactly equivalent:
from hypothesis import given, settings @settings(max_examples=500) @given(integers()) def test_this_thoroughly(x): pass
Available settings
- class hypothesis.settings(parent=None, **kwargs)
- A settings object controls a variety of parameters that are used in falsification. These may control both the falsification strategy and the details of the data that is generated.
Default values are picked up from the settings.default object and changes made there will be picked up in newly created settings.
- database_file
- database: An instance of hypothesis.database.ExampleDatabase that will be used to save examples to and load previous examples from. May be None in which case no storage will be used. default value: (dynamically calculated)
- database
- An ExampleDatabase instance to use for storage of examples. May be None.
If this was explicitly set at settings instantiation then that value will be used (even if it was None). If not and the database_file setting is not None this will be lazily loaded as an ExampleDatabase using that file the first time this property is accessed on a particular thread.
- max_examples
- Once this many satisfying examples have been considered without finding any counter-example, falsification will terminate. default value: 200
- max_iterations
- Once this many iterations of the example loop have run, including ones which failed to satisfy assumptions and ones which produced duplicates, falsification will terminate. default value: 1000
- min_satisfying_examples
- Raise Unsatisfiable for any tests which do not produce at least this many values that pass all assume() calls and which have not exhaustively covered the search space. default value: 5
- max_shrinks
- Once this many successful shrinks have been performed, Hypothesis will assume something has gone a bit wrong and give up rather than continuing to try to shrink the example. default value: 500
- timeout
- Once this many seconds have passed, falsify will terminate even if it has not found many examples. This is a soft rather than a hard limit - Hypothesis won't e.g. interrupt execution of the called function to stop it. If this value is <= 0 then no timeout will be applied. default value: 60
- strict
- If set to True, anything that would cause Hypothesis to issue a warning will instead raise an error. Note that new warnings may be added at any time, so running with strict set to True means that new Hypothesis releases may validly break your code.
You can enable this setting temporarily by setting the HYPOTHESIS_STRICT_MODE environment variable to the string 'true'. default value: False
- stateful_step_count
- Number of steps to run a stateful program for before giving up on it breaking. default value: 50
- perform_health_check
- If set to True, Hypothesis will run a preliminary health check before attempting to actually execute your test. default value: True
- suppress_health_check
- A list of health checks to disable default value: []
- buffer_size
- The size of the underlying data used to generate examples. If you need to generate really large examples you may want to increase this, but it will make your tests slower. default value: 8192
Seeing intermediate result
To see what's going on while Hypothesis runs your tests, you can turn up the verbosity setting. This works with both find() and @given.
>>> from hypothesis import find, settings, Verbosity >>> from hypothesis.strategies import lists, booleans >>> find(lists(integers()), any, settings=settings(verbosity=Verbosity.verbose)) Found satisfying example [-208] Shrunk example to [-208] Shrunk example to [208] Shrunk example to [1] [1].
Building settings objects
settings can be created by calling settings with any of the available settings values. Any absent ones will be set to defaults:
>>> from hypothesis import settings >>> settings() settings(buffer_size=8192, database_file='...', derandomize=False, max_examples=200, max_iterations=1000, max_mutations=10, max_shrinks=500, min_satisfying_examples=5, perform_health_check=True, phases=..., report_statistics=..., stateful_step_count=50, strict=..., suppress_health_check=[], timeout=60, verbosity=Verbosity.normal) >>> settings().max_examples 200 >>> settings(max_examples=10).max_examples 10
You can also copy settings off other settings:
>>> s = settings(max_examples=10) >>> t = settings(s, max_iterations=20) >>> s.max_examples 10 >>> t.max_iterations 20 >>> s.max_iterations 1000 >>> s.max_shrinks 500 >>> t.max_shrinks 500
Default settings
At any given point in your program there is a current default settings, available as settings.default. As well as being a settings object in its own right, all newly created settings objects which are not explicitly based off another settings are based off the default, so will inherit any values that are not explicitly set from it.
You can change the defaults by using profiles (see next section), but you can also override them locally by using a settings object as a context manager
>>> with settings(max_examples=150): ... print(settings.default.max_examples) ... print(settings().max_examples) 150.
Warning: If you use define test functions which don't use @given inside a context block, these will not use the enclosing settings. This is because the context manager only affects the definition, not the execution of the function.
settings Profiles
Depending on your environment you may want different default settings. For example: during development you may want to lower the number of examples to speed up the tests. However, in a CI environment you may want more examples so you are more likely to find bugs.
Hypothesis allows you to define different settings profiles. These profiles can be loaded at any time.
Loading a profile changes the default settings but will not change the behavior of tests that explicitly change the settings.
>>> from hypothesis import settings >>> settings.register_profile("ci", settings(max_examples=1000)) >>> settings().max_examples 200 >>> settings.load_profile("ci") >>> settings().max_examples 1000
Instead of loading the profile and overriding the defaults you can retrieve profiles for specific tests.
>>> with settings.get_profile("ci"): ... print(settings().max_examples) ... 1000
Optionally, you may define the environment variable to load a profile for you. This is the suggested pattern for running your tests on CI. The code below should run in a conftest.py or any setup/initialization section of your test suite. If this variable is not defined the Hypothesis defined defaults will be loaded.
>>> import os >>> from hypothesis import settings >>> settings.register_profile("ci", settings(max_examples=1000)) >>> settings.register_profile("dev", settings(max_examples=10)) >>> settings.register_profile("debug", settings(max_examples=10, verbosity=Verbosity.verbose)) >>> settings.load_profile(os.getenv(u'HYPOTHESIS_PROFILE', 'default'))
If you are using the hypothesis pytest plugin and your profiles are registered by your conftest you can load one with the command line option --hypothesis-profile.
$ py.test tests --hypothesis-profile <profile-name>
WHAT YOU CAN GENERATE AND HOW
The general philosophy of Hypothesis data generation is that everything should be possible to generate and most things should be easy. Most things in the standard library is more aspirational than achieved, the state of the art is already pretty good.
This document is a guide to what strategies are available for generating data and how to build them. Strategies have a variety of other important internal features, such as how they simplify, but the data they can generate is the only public part of their API.
Functions for building strategies are all available in the hypothesis.strategies module. The salient functions from it are as follows:
- hypothesis.strategies.nothing()
- This strategy never successfully draws a value and will always reject on an attempt to draw.
- hypothesis.strategies.just(value)
- Return a strategy which only generates value.
Note: value is not copied. Be wary of using mutable values.
- hypothesis.strategies.none()
- Return a strategy which only generates None.
- hypothesis.strategies.one_of(*args)
- Return a strategy which generates values from any of the argument strategies.
This may be called with one iterable argument instead of multiple strategy arguments. In which case one_of(x) and one_of(*x) are equivalent.
- hypothesis.strategies.integers(min_value=None, max_value=None)
- Returns a strategy which generates integers (in Python 2 these may be ints or longs).
If min_value is not None then all values will be >= min_value. If max_value is not None then all values will be <= max_value
- hypothesis.strategies.booleans()
- Returns a strategy which generates instances of bool.
- hypothesis.strategies.floats(min_value=None, max_value=None, allow_nan=None, allow_infinity=None)
- Returns a strategy which generates floats.
- •
- If min_value is not None, all values will be >= min_value.
- •
- If max_value is not None, all values will be <= max_value.
- •
- If min_value or max_value is not None, it is an error to enable allow_nan.
- •
- If both min_value and max_value are not None, it is an error to enable allow_infinity.
Where not explicitly ruled out by the bounds, all of infinity, -infinity and NaN are possible values generated by this strategy.
- hypothesis.strategies.complex_numbers()
- Returns a strategy that generates complex numbers.
- hypothesis.strategies.tuples(*args)
- Return a strategy which generates a tuple of the same length as args by generating the value at index i from args[i].
e.g. tuples(integers(), integers()) would generate a tuple of length two with both values an integer.
- hypothesis.strategies.sampled_from(elements)
- Returns a strategy which generates any value present in the iterable elements.
Note that as with just, values will not be copied and thus you should be careful of using mutable data.
- hypothesis.strategies.lists(elements=None, min_size=None, average_size=None, max_size=None, unique_by=None, unique=False)
- Returns a list containing values drawn from elements length in the interval [min_size, max_size] (no bounds in that direction if these are None). If max_size is 0 then elements may be None and only the empty list will be drawn.
average_size may be used as a size hint to roughly control the size of list but it may not be the actual average of sizes you get, due to a variety of factors.
If unique is True (or something that evaluates to True), we compare direct object equality, as if unique_by was lambda x: x. This comparison only works for hashable types.
if unique_by is not None it must be a function returning a hashable type when given a value drawn from elements. The resulting list will satisfy the condition that for i != j, unique_by(result[i]) != unique_by(result[j]).
- hypothesis.strategies.sets(elements=None, min_size=None, average_size=None, max_size=None)
-.
- hypothesis.strategies.frozensets(elements=None, min_size=None, average_size=None, max_size=None)
- This is identical to the sets function but instead returns frozensets.
- hypothesis.strategies.iterables(elements=None, min_size=None, average_size=None, max_size=None, unique_by=None, unique=False)
-.fixed_dictionaries(mapping)
- Generate.
- hypothesis.strategies.dictionaries(keys, values, dict_class=<type 'dict'>, min_size=None, average_size=None, max_size=None)
- Generates dictionaries of type dict_class with keys drawn from the keys argument and values drawn from the values argument.
The size parameters have the same interpretation as for lists.
- hypothesis.strategies.streaming(elements)
- Generates an infinite stream of values where each value is drawn from elements.
The result is iterable (the iterator will never terminate) and indexable.
- hypothesis.strategies.characters(whitelist_categories=None, blacklist_categories=None, blacklist_characters=None, min_codepoint=None, max_codepoint=None)
- Generates unicode text type (unicode on python 2, str on python 3) characters following specified filtering rules.
This strategy accepts lists of Unicode categories, characters of which should (whitelist_categories) or should not (blacklist_categories) be produced.
Also there could be applied limitation by minimal and maximal produced code point of the characters.
If you know what exactly characters you don't want to be produced, pass them with blacklist_characters argument.
- hypothesis.strategies.text(alphabet=None, min_size=None, average_size=None, max_size=None)
-. If it is an empty collection this will only generate empty strings.
min_size, max_size and average_size have the usual interpretations.
- hypothesis.strategies.binary(min_size=None, average_size=None, max_size=None)
- Generates the appropriate binary type (str in python 2, bytes in python 3).
min_size, average_size and max_size have the usual interpretations.
- hypothesis.strategies.randoms()
- Generates instances of Random (actually a Hypothesis specific RandomWithSeed class which displays what it was initially seeded with)
- hypothesis.strategies.random_module()
-.
- hypothesis.strategies.builds(target, *args, **kwargs)
- Generates values by drawing from args and kwargs and passing them to target in the appropriate argument position.
e.g. builds(target, integers(), flag=booleans()) would draw an integer i and a boolean b and call target(i, flag=b).
- hypothesis.strategies.fractions(min_value=None, max_value=None, max_denominator=None)
- Returns a strategy which generates Fractions.
If min_value is not None then all generated values are no less than min_value.
If max_value is not None then all generated values are no greater than max_value.
If max_denominator is not None then the absolute value of the denominator of any generated values is no greater than max_denominator. Note that max_denominator must be at least 1.
- hypothesis.strategies.decimals(min_value=None, max_value=None, allow_nan=None, allow_infinity=None, places=None)
- Generates instances of decimals.Decimal, which may be:
- •
- A finite rational number, between min_value and max_value.
- •
- Not a Number, if allow_nan is True. None means "allow NaN, unless min__value and max_value are not None".
- •
- Positive or negative infinity, if max_value and min_value respectively are None, and allow_infinity is not False. None means "allow infinity, unless excluded by the min and max values".
Note that where floats have one NaN value, Decimals have four: signed, and either quiet or signalling. See the decimal module docs for more information on special values.
If places is not None, all finite values drawn from the strategy will have that number of digits after the decimal place.
- hypothesis.strategies.recursive(base, extend, max_leaves=100)
- base: A strategy to start from.
extend: A function which takes a strategy and returns a new strategy.
max_leaves: The maximum number of elements to be drawn from base on a given run.
This returns a strategy S such that S = extend(base | S). That is, values maybe drawn from base, or from any strategy reachable by mixing applications of | and extend.
An example may clarify: recursive(booleans(), lists) would return a strategy that may return arbitrarily nested and mixed lists of booleans. So e.g. False, [True], [False, []], [[[[True]]]], are all valid values to be drawn from that strategy.
- hypothesis.strategies.permutations(values)
- Return a strategy which returns permutations of the collection "values".
- hypothesis.strategies.datetimes(min_datetime=datetime.datetime(1, 1, 1, 0, 0), max_datetime=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), timezones=none())
- A strategy for generating datetimes, which may be timezone-aware.
This strategy works by drawing a naive datetime between min_datetime and max_datetime, which must both be naive (have no timezone).
timezones must be a strategy that generates tzinfo objects .timezones() requires the pytz package, but provides all timezones in the Olsen database. If you also want to allow naive datetimes, combine strategies like none() | timezones()..
- hypothesis.strategies.dates(min_date=datetime.date(1, 1, 1), max_date=datetime.date(9999, 12, 31))
- A strategy for dates between min_date and max_date.
- hypothesis.strategies.times(min_time=datetime.time(0, 0), max_time=datetime.time(23, 59, 59, 999999), timezones=none())
- A strategy for times between min_time and max_time.
The timezones argument is handled as for datetimes().
- hypothesis.strategies.timedeltas(min_delta=datetime.timedelta(-999999999), max_delta=datetime.timedelta(999999999, 86399, 999999))
- A strategy for timedeltas between min_delta and max_delta.
- hypothesis.strategies.composite(f)
- Defines a strategy that is built out of potentially arbitrarily many other strategies.
This is intended to be used as a decorator. See the full documentation for more details about how to use this function.
- hypothesis.strategies.shared(base, key=None)
-")
- hypothesis.strategies.choices()
- Strategy that generates a function that behaves like random.choice.
Will note choices made for reproducibility.
- hypothesis.strategies.uuids()
- Returns a strategy that generates UUIDs.
All returned values from this will be unique, so e.g. if you do lists(uuids()) the resulting list will never contain duplicates.
- hypothesis.strategies.runner(default=not_set)
- A strategy for getting "the current test runner", whatever that may be. The exact meaning depends on the entry point, but it will usually be the associated 'self' value for it.
If there is no current test runner and a default is provided, return that default. If no default is provided, raises InvalidArgument.
- hypothesis.strategies.data()
- This isn't really a normal strategy, but instead gives you an object which can be used to draw data interactively from other strategies.
It can only be used within @given, not find(). This is because the lifetime of the object cannot outlast the test body.
See the rest of the documentation for more complete information.
Choices
Sometimes you need an input to be from a known set of items. Hypothesis gives you two ways to do this. First up, choice():
from hypothesis import given, strategies as st @given(user=st.text(min_size=1), service=st.text(min_size=1), choice=st.choices()) def test_tickets(user, service, choice): t=choice(('ST', 'LT', 'TG', 'CT')) # asserts go here.
This means t will randomly be one of the items in the list ('ST', 'LT', 'TG', 'CT'), as if you were calling python:random.choice() on the list.
A different, and probably better way to do this, is to use sampled_from():
from hypothesis import given, strategies as st @given( user=st.text(min_size=1), service=st.text(min_size=1), t=st.sampled_from(('ST', 'LT', 'TG', 'CT'))) def test_tickets(user, service, t): # asserts and test code go here.
Values from sampled_from() will not be copied and thus you should be careful of using mutable data. This is great for the above use case, but may not always work out.
Infinite streams
Sometimes you need examples of a particular type to keep your test going but you're not sure how many you'll need in advance. For this, we have streaming types.
>>> from hypothesis.types import Stream >>> x = Stream(iter(integers().example, None)) >>> # Equivalent to `streaming(integers()).example()`, which is not supported >>> x Stream(...) >>> x[2] 131 >>> x Stream(-225, 50, 131, ...) >>> x[10] 127 >>> x Stream(-225, 50, 131, 30781241791694610923869406150329382725, 89, 62248, 107, 35771, -113, 79, 127, ...)
Think of a Stream as an infinite list where we've only evaluated as much as we need to. As per above, you can index into it and the stream will be evaluated up to that index and no further.
You can iterate over it too (warning: iter on a stream given to you by Hypothesis in this way will never terminate):
>>> it = iter(x) >>> next(it) -225 >>> next(it) 50 >>> next(it) 131
Slicing will also work, and will give you back Streams. If you set an upper bound then iter on those streams will terminate:
>>> list(x[:5]) [-225, 50, 131, 30781241791694610923869406150329382725, 89] >>> y = x[1::2] >>> y Stream(...) >>> y[0] 50 >>> y[1] 30781241791694610923869406150329382725 >>> y Stream(50, 30781241791694610923869406150329382725, ...)
You can also apply a function to transform a stream:
>>> t = x[20:] >>> tm = t.map(lambda n: n * 2) >>> tm[0] -344 >>> t[0] -172 >>> tm Stream(-344, ...) >>> t Stream(-172, ...)
map creates a new stream where each element of the stream is the function applied to the corresponding element of the original stream. Evaluating the new stream will force evaluating the original stream up to that index.
(Warning: This isn't the map builtin. In Python 3 the builtin map should do more or less the right thing, but in Python 2 it will never terminate and will just eat up all your memory as it tries to build an infinitely long list)
These are the only operations a Stream supports. There are a few more internal ones, but you shouldn't rely on them.
Adapting strategies() [-224, -222, 16, 159, 120699286316048]
Note that many things that you might use mapping for can also be done with hypothesis.strategies.builds().
Filtering
filter lets you reject some examples. s.filter(f).example() is some example of s such that f(example) is truthy.
>>> integers().filter(lambda x: x > 11).example() 1609027033942695427531 >>> integers().filter(lambda x: x > 11).example() 251
It's important to note that filter isn't magic and if your condition is too hard to satisfy then this can fail:
>>> integers().filter(lambda x: False).example() Traceback (most recent call last): ... hypothesis.errors.NoExamples:( ... lambda x: tuple(sorted(x))).filter(lambda x: x[0] != x[1]).example() (180, 241)
Chaining strategies togetherother.
For example suppose we wanted to generate a list of lists of the same length:
>>> rectangle_lists = integers(min_value=0, max_value=10).flatmap( ... lambda n: lists(lists(integers(), min_size=n, max_size=n))) >>> find(rectangle_lists, lambda x: True) [] >>> find(rectangle_lists, lambda x: len(x) >= 10) [[], [], [], [], [], [], [], [], [], []] >>> find(rectangle_lists, lambda t: len(t) >= 3 and len(t[0]) >= 3) [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> find(rectangle_lists, lambda t: sum(len(s) for s in t) >= 10) [
Sometimes the data you want to generate has a recursive definition. e.g. if you wanted to generate JSON data, valid JSON is:
- 1.
- Any float, any boolean, any unicode string.
- 2.
- Any list of valid JSON data
- 3.
-() function) | dictionaries(text(printable), children)) >>> pprint(json.example()) {'': 'Me$', "\r5qPZ%etF:vL'9gC": False, '$KsT(( J/(wQ': [], '0)G&31': False, '7': [], 'C.i]A-I': {':?Xh>[;': None, 'YHT\r!\x0b': -6.801160220000663e+18, ... >>> pprint(json.example()) [{"7_8'qyb": None, ':': -0.3641507440748771, 'TI_^\n>L{T\x0c': -0.0, 'ZiOqQ\t': 'RKT*a]IjI/Zx2HB4ODiSUN)LsZ', 'n;E^^6|9=@g@@BmAi': '7j5\\'}, True] >>> pprint(json() [True, False] >>> small_lists.example() True
Composite strategies
The @composite decorator lets you combine other strategies in more or less arbitrary ways. It's probably the main thing you'll want to use for complicated custom strategies.
The composite decorator works by giving you a function as the first argument that you can use to draw examples from other strategies.() ([215, 112], 0) >>> list_and_index(booleans()) list_and_index(elements=booleans()) >>> list_and_index(booleans()).example() ([False, False], 1)
There is also the data() strategy, which gives you a means of using strategies interactively. Rather than having to specify everything up front in @given you can draw from strategies in the body of your test:
.
Test functions using the data() strategy do not support explicit @example(...)s. In this case, the best option is usually to construct your data with @composite or the explicit example, and unpack this within the body of the test.
ADDITIONAL PACKAGES.
hypothesis[pytz]
hypothesis[datetime]
hypothesis[fakefactory]
Fake-factory is another Python library for data generation. hypothesis.extra.fakefactory is a package which lets you use fake-factory generators to parametrize tests.
The fake-factory API is extremely unstable, even between patch releases, and Hypothesis's support for it is unlikely to work with anything except the exact version it has been tested against.
hypothesis.extra.fakefactory defines a function fake_factory which returns a strategy for producing text data from any FakeFactory provider.
So for example the following will parametrize a test by an email address:
>>> fake_factory('email').example() 'tnader [at] prosacco.info' >>> fake_factory('name').example() 'Zbyněk Černý CSc.'
You can explicitly specify the locale (otherwise it uses any of the available locales), either as a single locale or as several:
>>> fake_factory('name',>> fake_factory('name', locales=['en_GB', 'cs_CZ']).example() 'Miloš Šťastný' >>> fake_factory('name', locales=['en_GB', 'cs_CZ']).example() 'Harm Sanford'. This is only here to provide easy reuse of things you already have.
hypothesis[django]
hypothesis.extra.django adds support for testing your Django models with Hypothesis.
It is tested extensively against all versions of Django in mainstream or extended support, including LTS releases. It may be compatible with earlier versions too, but there's no support from us either and you really should update to get security patches.
It's large enough that it is documented elsewhere.
hypothesis[numpy]
hypothesis.extra.numpy adds support for testing your Numpy code with Hypothesis.
This includes generating arrays, array shapes, and both scalar or compound dtypes.
Like the Django extra, Numpy has it's own page.
HYPOTHESIS FOR DJANGO USERS
Hypothesis offers a number of features specific for Django testing, available in the hypothesis[django] extra. This is tested against each supported series with mainstream or extended support - if you're still getting security patches, you can test with Hypothesis.
Using it is quite straightforward: All you need to do is subclass hypothesis.extra.django.TestCase or hypothesis.extra.django.TransactionTestCase and you can use @given as normal, and the transactions will be per example rather than per test function as they would be if you used @given with a normal django test suite (this is important because your test function will be called multiple times and you don't want them to interfere with each other). have for testing:
>>> from hypothesis.extra.django.models import models >>> from toystore.models import Customer >>> c = models(Customer).example() >>> c <Customer: Customer object> >>> c.email 'jaime.urbina [at] gmail.com' >>> c.name '\U00109d3d\U000e07be\U000165f8\U0003fabf\U000c12cd\U000f1910\U00059f12\U000519b0\U0003fabf\U000f1910\U000423fb\U000423fb\U00059f12\U000e07be\U000c12cd\U000e07be\U000519b0\U000165f8\U0003fabf\U0007bc31' >>> c.age -873375803
Hypothesis has just created this with whatever the relevant type of data is.
Obviously the customer's age is implausible,.
Foreign keys are not automatically derived. If they're nullable they will default to always being null, otherwise you always have to specify them. e.g. suppose we had a Shop type with a foreign key to company, we would define a strategy for it as:
shop_strategy = models(Shop, company=models(Company))
Tips and tricks
Custom field types
If you have a custom Django field type you can register it with Hypothesis's model deriving functionality by registering a default strategy for it:
>>> from toystore.models import CustomishField, Customish >>> models(Customish).example() hypothesis.errors.InvalidArgument: Missing arguments for mandatory field customish for model Customish >>> from hypothesis.extra.django.models import add_default_field_mapping >>> from hypothesis.strategies import just >>> add_default_field_mapping(CustomishField, just("hi")) >>> x = models(Customish).example() >>> x.customish 'hi'
Note that this mapping is on exact type. Subtypes will not inherit it.
Generating child models'
SCIENTIFIC HYPOTHESIS (FOR NUMPY).
HEALTH CHECKS
Hypothesis tries to detect common mistakes and things that will cause difficulty at run time in the form of a number of 'health checks'.
These include detecting and warning about:
- •
- Strategies with very slow data generation
- •
- Strategies which filter out too much
- •
- Recursive strategies which branch too much
- •
- Use of the global random module settings. The argument for this parameter is a list with elements drawn from any of the class-level attributes of the HealthCheck class.
To disable all health checks, set the perform_health_check settings parameter to False.
THE HYPOTHESIS EXAMPLE DATABASE
When Hypothesis finds a bug it stores enough information in its database to reproduce it. This enables you to have a classic testing workflow of find a bug, fix a bug, and be confident that this is actually doing the right thing because Hypothesis will start by retrying the examples that broke things last time.
Limitations
The database is best thought of as a cache that you never need to invalidate: Information may be lost when you upgrade a Hypothesis version or change your test, so you shouldn't rely on it for correctness - if there's an example you want to ensure occurs each time then there's a feature for including them in your source code - but it helps the development workflow considerably by making sure that the examples you've just found are reproduced.
File locations
The default storage format is as a fairly opaque directory structure. Each test corresponds to a directory, and each example to a file within that directory. The standard location for it is .hypothesis/examples in your current working directory. You can override this, either by setting either the database_file property on a settings object (you probably want to specify it on settings.default) or by setting the HYPOTHESIS_DATABASE_FILE environment variable..
Upgrading Hypothesis and changing your tests
The design of the Hypothesis database is such that you can put arbitrary data in the database and not get wrong behaviour. When you upgrade Hypothesis, old data might be invalidated, but this should happen transparently. It should never be the case that e.g. changing the strategy that generates an argument sometimes gives you data from the old strategy.
Sharing your example database
NOTE: If specific examples are important for correctness you should use the @example decorator, as the example database may discard entries due to changes in your code or dependencies. For most users, we therefore recommend using the example database locally and possibly persisting it between CI builds, but not tracking it under version control.
The examples database can be shared simply by checking the directory into version control, for example with the following .gitignore:
# Ignore files cached by Hypothesis... .hypothesis/ # except for the examples directory !.hypothesis/examples/
Like everything under .hypothesis/, the examples directory will be transparently created on demand. Unlike the other subdirectories, examples/ is designed to handle merges, deletes, etc if you just add the directory into git, mercurial, or any similar version control system.
STATEFUL TESTING') @rule(target=trees, x=st.integers()).') balanced_trees = Bundle('balanced BinaryTree') @rule(target=trees, x=st.integers()) there = settings(max_examples=100, stateful_step_count=100)
Which doubles the number of steps each program runs and halves the number of runs relative to the example. settings.timeout will also be respected as usual.
Preconditionsant: machine.check_invariants() for _ in range(n_steps): step = machine.steps().example() machine.execute_step(step) machine.check_invariants() finally: machine.teardown()
Where steps and execute_step are methods you must implement, and teardown and check_invarants are methods you can implement if required. steps returns a strategy, which is allowed to depend arbitrarily on the current state of the test execution. Ideally a good steps implementation should be robust against minor changes in the state. Steps that change a lot between slightly different executions will tend to produce worse quality examples because they're hard to simplify.
The steps method may depend on external state, but it's not advisable and may produce flaky tests.
If any of execute_step, check_invariants or teardown produces an exception, Hypothesis will try to find a minimal sequence of values steps such that the following throws an exception:
machine = MyStateMachine() try: machine.check_invariants() for step in steps: machine.execute_step(step) machine.check_invariants().strategies import tuples, sampled_from, just, integers class BrokenSet(GenericStateMachine): def __init__(self): self.data = [] def steps(self): add_strategy = tuples(just("add"), integers()) if not self.data: return add_strategy else: return ( add_strategy | tuples.
More fine grained control
If you want to bypass the TestCase infrastructure you can invoke these manually. The stateful module exposes the function run_state_machine_as_test, which takes an arbitrary function returning a GenericStateMachine and an optional settings parameter and does the same as the class based runTest provided.
In particular this may be useful if you wish to pass parameters to a custom __init__ in your subclass.
COMPATIBILITY
Hypothesis does its level best to be compatible with everything you could possibly need it to be compatible with. Generally you should just try it and expect it to work. If it doesn't, you can be surprised and check this document for the details.
Python versions
Hypothesis is supported and tested on CPython 2.7 and CPython 3.4+.
Hypothesis also supports PyPy2, and will support PyPy3 when there is a stable release supporting Python 3.4+. Hypothesis does not currently work on Jython, though could feasibly be made to do so..
In terms of what's actually known to work:
- •
- Hypothesis integrates as smoothly with py.test and unittest as I can make it, and this is verified as part of the CI.
- •
- py.test fixtures work correctly with Hypothesis based functions, but note that function based fixtures will only run once for the whole function, not once per example.
- •
- Nose works fine with hypothesis, and this is tested as part of the CI. yield based tests simply won't work.
- •
- Integration with Django's testing requires use of the hypothesis-django package. The issue is that in Django's tests' normal mode of execution it will reset the database one per test rather than once per example, which is not what you want.
Coverage works out of the box with Hypothesis (and Hypothesis has 100% branch coverage in its own tests). However you should probably not use Coverage, Hypothesis and PyPy together. Because Hypothesis does quite a lot of CPU heavy work compared to normal tests, it really exacerbates the performance problems the two normally have working together.
Optional Packages
The supported versions of optional packages, for strategies in hypothesis.extra, are listed in the documentation for that extra. Our general goal is to support all versions that are supported upstream.
Regularly verifying this
Everything mentioned above as explicitly supported is checked on every commit with Travis and Appveyor and goes green before a release happens, so when I say they're supported I really mean it.
Hypothesis versions
Backwards compatibility is better than backporting fixes, so we use semantic versioning and only support the most recent version of Hypothesis. See support for more information.
SOME MORE EXAMPLES
This is a collection of examples of how to use Hypothesis in interesting ways. It's small for now but will grow over time.
All of these examples are designed to be run under py.test (nose should probably work too).
How not to sort by a partial order, strategy = {} for node in nodes: table[node.label] = node return list(table.values()) NodeSet = s.lists(Node).map(deduplicate_nodes_by_label)
We define a function to deduplicate nodes by labels, and then map that over a strategy for lists of nodes to give us a strategy for lists of nodes with unique labels. We can now rewrite the test to use that:
@given(NodeSet)
This is an example of some tests for pytz which check that various timezone conversions behave as you would expect them to. These tests should all pass, and are mostly a demonstration of some useful sorts of thing to test with Hypothesis, and how the hypothesis-datetime extra package works.
>>> from datetime import timedelta >>> from hypothesis.extra.pytz import timezones >>> #:
- 1.
- We can generate a type that is much larger than an election, extract an election out of that, and rely on minimization to throw away all the extraneous detail.
- 2.
-other.()
COMMUNITY
The Hypothesis community is small for the moment but is full of excellent people who can answer your questions and help you out. Please do join us.
The two major places for community discussion are:
- •
- The mailing list.
- •
- An IRC channel, #hypothesis on freenode, which is more active than the mailing list.
Feel free to use these to ask for help, provide feedback, or discuss anything remotely Hypothesis related at all.
Code of conduct
Hypothesis's community is an inclusive space, and everyone in it is expected to abide by a code of conduct.
At the high level the code of conduct goes like this:
- 1.
- Be kind
- 2.
- Be respectful
- 3.
- Be helpful
While it is impossible to enumerate everything that is unkind, disrespectful or unhelpful, here are some specific things that are definitely against the code of conduct:
- 1.
- -isms and -phobias (e.g. racism, sexism, transphobia and homophobia) are unkind, disrespectful and unhelpful. Just don't.
- 2.
- All software is broken. This is not a moral failing on the part of the authors. Don't give people a hard time for bad code.
- 3.
- It's OK not to know things. Everybody was a beginner once, nobody should be made to feel bad for it.
- 4.
- It's OK not to want to know something. If you think someone's question is fundamentally flawed, you should still ask permission before explaining what they should actually be asking.
- 5.
- Note that "I was just joking" is not a valid defence.
What happens when this goes wrong?
For minor infractions, I'll just call people on it and ask them to apologise and not do it again. You should feel free to do this too if you're comfortable doing so.
Major infractions and repeat offenders will be banned from the community.
Also, people who have a track record of bad behaviour outside of the Hypothesis community may be banned even if they obey all these rules if their presence is making people uncomfortable.
At the current volume level it's not hard for me to pay attention to the whole community, but if you think I've missed something please feel free to alert me. You can either message me as DRMacIver on freenode or send a me an email at david [at] drmaciver.com.
THE PURPOSE OF HYPOTHESIS.
TESTIMONIALS
Hypothesis has been brilliant for expanding the coverage of our test cases, and also for making them much easier to read and understand, so we're sure we're testing the things we want in the way we want.
Seth Morton
When I first heard about Hypothesis, I knew I had to include it in my two open-source Python libraries, natsort and fastnumbers . Quite frankly, I was a little appalled at the number of bugs and "holes" I found in the code. I can now say with confidence that my libraries are more robust to "the wild." In addition, Hypothesis gave me the confidence to expand these libraries to fully support Unicode input, which I never would have had the stomach for without such thorough testing capabilities. Thanks!
Sixty North
At Sixty North we use Hypothesis for testing Segpy an open source Python library for shifting data between Python data structures and SEG Y files which contain geophysical data from the seismic reflection surveys used in oil and gas exploration.
This is our first experience of property-based testing – as opposed to example-based testing. Not only are our tests more powerful, they are also much better explanations of what we expect of the production code. In fact, the tests are much closer to being specifications. Hypothesis has located real defects in our code which went undetected by traditional test cases, simply because Hypothesis is more relentlessly devious about test case generation than us mere humans! We found Hypothesis particularly beneficial for Segpy because SEG Y is an antiquated format that uses legacy text encodings (EBCDIC) and even a legacy floating point format we implemented from scratch in Python.
Hypothesis is sure to find a place in most of our future Python codebases and many existing ones too.
mulkieran
Just found out about this excellent QuickCheck for Python implementation and ran up a few tests for my bytesize package last night. Refuted a few hypotheses in the process.
Looking forward to using it with a bunch of other projects as well.
Adam Johnson
I have written a small library to serialize dicts to MariaDB's dynamic columns binary format, mariadb-dyncol. When I first developed it, I thought I had tested it really well - there were hundreds of test cases, some of them even taken from MariaDB's test suite itself. I was ready to release.
Lucky for me, I tried Hypothesis with David at the PyCon UK sprints. Wow! It found bug after bug after bug. Even after a first release, I thought of a way to make the tests do more validation, which revealed a further round of bugs! Most impressively, Hypothesis found a complicated off-by-one error in a condition with 4095 versus 4096 bytes of data - something that I would never have found.
Long live Hypothesis! (Or at least, property-based testing).
Josh Bronson
Adopting Hypothesis improved bidict's test coverage and significantly increased our ability to make changes to the code with confidence that correct behavior would be preserved. Thank you, David, for the great testing tool.
Cory Benfield
Hypothesis is the single most powerful tool in my toolbox for working with algorithmic code, or any software that produces predictable output from a wide range of sources. When using it with Priority, Hypothesis consistently found errors in my assumptions and extremely subtle bugs that would have taken months of real-world use to locate. In some cases, Hypothesis found subtle deviations from the correct output of the algorithm that may never have been noticed at all.
When it comes to validating the correctness of your tools, nothing comes close to the thoroughness and power of Hypothesis.
Jon Moore
One extremely satisfied user here. Hypothesis is a really solid implementation of property-based testing, adapted well to Python, and with good features such as failure-case shrinkers. I first used it on a project where we needed to verify that a vendor's Python and non-Python implementations of an algorithm matched, and it found about a dozen cases that previous example-based testing and code inspections had not. Since then I've been evangelizing for it at our firm.
Russel Winder.
Your name goes here.
OPEN SOURCE PROJECTS USING HYPOTHESIS
The following is a non-exhaustive list of open source projects I know are using Hypothesis. If you're aware of any others please add them to the list! The only inclusion criterion right now is that if it's a Python library then it should be available on pypi.
- •
- aur
- •
- axelrod
- •
- bidict
- •
- binaryornot
- •
- brotlipy
- •
- chardet
- •
- cmph-cffi
- •
- cryptography
- •
- dbus-signature-pyparsing
- •
- fastnumbers
- •
- flocker
- •
- flownetpy
- •
- funsize
- •
- fusion-index
- •
- hyper-h2
- •
- into-dbus-python
- •
- justbases
- •
- justbytes
- •
- mariadb-dyncol
- •
- mercurial
- •
- natsort
- •
- pretext
- •
- priority
- •
- PyCEbox
- •
- PyPy
- •
- pyrsistent
- •
- pyudev
- •
- qutebrowser
- •
- RubyMarshal
- •
- Segpy
- •
- simoa
- •
- srt
- •
- tchannel
- •
- vdirsyncer
- •
- wcag-contrast-ratio
- •
- yacluster
- •
- yturl
PROJECTS EXTENDING HYPOTHESIS
The following is a non-exhaustive list of open source projects that make Hypothesis strategies available. If you're aware of any others please add them the list! The only inclusion criterion right now is that if it's a Python library then it should be available on pypi.
- •
- hs-dbus-signature - strategy to generate arbitrary D-Bus signatures
- •
- hypothesis-regex - strategy to generate strings that match given regular expression.
- •
- lollipop-hypothesis - strategy to generate data based on Lollipop schema definitions.
If you're thinking about writing an extension, consider naming it hypothesis-{something} - a standard prefix makes the community more visible and searching for extensions easier.
CHANGELOG
This is a record of all past Hypothesis releases and what went into them, in reverse chronological order. All previous releases should still be available on pip.
Hypothesis APIs come in three flavours:
- •
- Public: Hypothesis releases since 1.0 are semantically versioned with respect to these parts of the API. These will not break except between major version bumps. All APIs mentioned in this documentation are public unless explicitly noted otherwise.
- •
- Semi-public: These are APIs that are considered ready to use but are not wholly nailed down yet. They will not break in patch releases and will usually not break in minor releases, but when necessary minor releases may break semi-public APIs.
- •
- Internal: These may break at any time and you really should not use them at all.
You should generally assume that an API is internal unless you have specific information to the contrary.
3.12.0 - 2017-07-07:
- •
- All existing examples in the database will probably be invalidated. Hypothesis handles this automatically, so you don't need to do anything, but if you see all your examples disappear that's why.
- •
- Almost all data distributions have changed significantly. Possibly for the better, possibly for the worse. This may result in new bugs being found, but it may also result in Hypothesis being unable to find bugs it previously did.
- •
- Data generation may be somewhat faster if your existing bottleneck was in draw_bytes (which is often the case for large examples).
- •
- Shrinking will probably be slower, possibly significantly.
If you notice any effects you consider to be a significant regression, please open an issue about them.
3.11.6 - 2017-06-19
This release involves no functionality changes, but is the first to ship wheels as well as an sdist.
3.11.5 - 2017-06-18
This is a bugfix release: Hypothesis now prints explicit examples when running in verbose mode. (issue #313)
3.11.3 - 2017-06-11
This is a bugfix release: Hypothesis no longer emits a warning if you try to use sampled_from() with python:collections.OrderedDict. (issue #688)
3.11.2 - 2017-06-10
This is a documentation release. Several outdated snippets have been updated or removed, and many cross-references are now hyperlinks.
3.11.1 - 2017-05-28
This is a minor ergonomics release. Tracebacks shown by pytest no longer include Hypothesis internals for test functions decorated with @given.
3.11.0 - 2017-05-23
Hypothesis now uses python
This is a bugfix release: the default field mapping for a DateTimeField in the Django extra now respects the USE_TZ setting when choosing a strategy.
3.9.0 - 2017-05-19
This is feature release, expanding the capabilities of the decimals() strategy.
- •
- The new (optional) places argument allows you to generate decimals with a certain number of places (e.g. cents, thousandths, satoshis).
- •
- If allow_infinity is None, setting min_bound no longer excludes positive infinity and setting max_value no longer excludes negative infinity.
- •
- All of NaN, -Nan, sNaN, and -sNaN may now be drawn if allow_nan is True, or if allow_nan is None and min_value or max_value is None.
- •
- min_value and max_value may be given as decimal strings, e.g. "1.234".
3.8.5 - 2017-05-16
Hypothesis now imports python:sqlite3 when a SQLite database is used, rather than at module load, improving compatibility with Python implementations compiled without SQLite support (such as BSD or Jython).
3.8.4 - 2017-05-16
This is a compatibility bugfix release. sampled_from no longer raises a deprecation warning when sampling from an Enum, as all enums have a reliable iteration order.
3.8.3 - 2017-05-09
This is a code reorganisation release that moves some internal test helpers out of the main source tree so as to not have changes to them trigger releases in future.
3.8.1 - 2017-04-26
This is a documentation release. Almost all code examples are now doctests checked in CI, eliminating stale examples.
3.8.0 - 2017-04-23
This is a bug fix release for a single bug:
- •
- In 3.7.3, using @example and a pytest fixture in the same test could cause the test to fail to fill the arguments, and throw a TypeError.
3.7.3 - 2017-04-21
This release should include no user visible changes and is purely a refactoring release. This modularises the behaviour of the core given() function, breaking it up into smaller and more accessible parts, but its actual behaviour should remain unchanged.
3.7.2 - 2017-04-21
This reverts an undocumented change in 3.7.1 which broke installation on debian stable: The specifier for the hypothesis[django] extra_requires had introduced a wild card, which was not supported on the default version of pip.
3.7.1 - 2017-04-21
This is a bug fix and internal improvements release.
- •
- In particular Hypothesis now tracks a tree of where it has already explored. This allows it to avoid some classes of duplicate examples, and significantly improves the performance of shrinking failing examples by allowing it to skip some shrinks that it can determine can't possibly work.
- •
- Hypothesis will no longer seed the global random arbitrarily unless you have asked it to using random_module()
- •
- Shrinking would previously have not worked correctly in some special cases on Python 2, and would have resulted in suboptimal examples.
3.7.0 - 2017-03-20
This is a feature release.
New features:
- •
- Rule based stateful testing now has an @invariant decorator that specifies methods that are run after init and after every step, allowing you to encode properties that should be true at all times. Thanks to Tom Prince for this feature.
- •
- The decimals() strategy now supports allow_nan and allow_infinity flags.
- •
- There are significantly more strategies available for numpy, including for generating arbitrary data types. Thanks to Zac Hatfield Dodds for this feature.
- •
- When using the data() strategy you can now add a label as an argument to draw(), which will be printed along with the value when an example fails. Thanks to Peter Inglesby for this feature.
Bug fixes:
- •
- Bug fix: composite() now preserves functions' docstrings.
- •
- The build is now reproducible and doesn't depend on the path you build it from. Thanks to Chris Lamb for this feature.
- •
- numpy strategies for the void data type did not work correctly. Thanks to Zac Hatfield Dodds for this fix.
There have also been a number of performance optimizations:
- •
- The permutations() strategy is now significantly faster to use for large lists (the underlying algorithm has gone from O(n^2) to O(n)).
- •
- Shrinking of failing test cases should have got significantly faster in some circumstances where it was previously struggling for a long time.
- •
- Example generation now involves less indirection, which results in a small speedup in some cases (small enough that you won't really notice it except in pathological cases).
3.6.1 - 2016-12-20
This release fixes a dependency problem and makes some small behind the scenes improvements.
- •
-.
- •
-.
- •
- The distribution of code using nested calls to one_of() or the | operator for combining strategies has been improved, as branches are now flattened to give a more uniform distribution.
- •
- Examples using composite() or .flatmap should now shrink better. In particular this will affect things which work by first generating a length and then generating that many items, which have historically not shrunk very well.
3.6.0 - 2016-10-31
This release reverts Hypothesis to its old pretty printing of lambda functions based on attempting to extract the source code rather than decompile the bytecode. This is unfortunately slightly inferior in some cases and may result in you occasionally seeing things like lambda x: <unknown> in statistics reports and strategy reprs.
This removes the dependencies on uncompyle6, xdis and spark-parser.
The reason for this is that the new functionality was based on uncompyle6, which turns out to introduce a hidden GPLed dependency - it in turn depended on xdis, and although the library was licensed under the MIT license, it contained some GPL licensed source code and thus should have been released under the GPL.
My interpretation is that Hypothesis itself was never in violation of the GPL (because the license it is under, the Mozilla Public License v2, is fully compatible with being included in a GPL licensed work), but I have not consulted a lawyer on the subject. Regardless of the answer to this question, adding a GPLed dependency will likely cause a lot of users of Hypothesis to inadvertently be in violation of the GPL.
As a result, if you are running Hypothesis 3.5.x you really should upgrade to this release immediately.
3.5.3 - 2016-10-05
This is a bug fix release.
Bugs fixed:
- •
-).
- •
- Drawing from an integers() strategy with both a min_value and a max_value would reject too many examples needlessly. Now it repeatedly redraws until satisfied. (pull request #366. Thanks to Calen Pennington for the contribution).
3.5.2 - 2016-09-24
This is a bug fix release.
- •
- The Hypothesis pytest plugin broke pytest support for doctests. Now it doesn't.
3.5.1 - 2016-09-23
This is a bug fix release.
- •
- Hypothesis now runs cleanly in -B and -BB modes, avoiding mixing bytes and unicode.
- •
- python:unittest.TestCase tests would not have shown up in the new statistics mode. Now they do.
- •
- Similarly, stateful tests would not have shown up in statistics and now they do.
- •
- Statistics now print with pytest node IDs (the names you'd get in pytest verbose mode).
3.5.0 - 2016-09-22
This is a feature release.
- •
- fractions() and decimals() strategies now support min_value and max_value parameters. Thanks go to Anne Mulhern for the development of this feature.
- •
- The Hypothesis pytest plugin now supports a --hypothesis-show-statistics parameter that gives detailed statistics about the tests that were run. Huge thanks to Jean-Louis Fuchs and Adfinis-SyGroup for funding the development of this feature.
- •
- There is a new event() function that can be used to add custom statistics.
Additionally there have been some minor bug fixes:
- •
- In some cases Hypothesis should produce fewer duplicate examples (this will mostly only affect cases with a single parameter).
- •
- py.test command line parameters are now under an option group for Hypothesis (thanks to David Keijser for fixing this)
- •
- Hypothesis would previously error if you used PEP 3107 function annotations on your tests under Python 3.4.
- •
- The repr of many strategies using lambdas has been improved to include the lambda body (this was previously supported in many but not all cases).
3.4.2 - 2016-07-13
This is a bug fix release, fixing a number of problems with the settings system:
- •
- Test functions defined using @given can now be called from other threads (issue #337)
- •
- Attempting to delete a settings property would previously have silently done the wrong thing. Now it raises an AttributeError.
- •
- Creating a settings object with a custom database_file parameter was silently getting ignored and the default was being used instead. Now it's not.
3.4.1 - 2016-07-07
This is a bug fix release for a single bug:
- •
- On Windows when running two Hypothesis processes in parallel (e.g. using pytest-xdist) they could race with each other and one would raise an exception due to the non-atomic nature of file renaming on Windows and the fact that you can't rename over an existing file. This is now fixed.
3.4.0 - 2016-05-27
This release is entirely provided by Lucas Wiman:
Strategies constructed by models() will now respect much more of Django's validations out of the box. Wherever possible full_clean() should succeed.
In particular:
- •
- The max_length, blank and choices kwargs are now respected.
- •
- Add support for DecimalField.
- •
- If a field includes validators, the list of validators are used to filter the field strategy.
3.3.0 - 2016-05-27
This release went wrong and is functionally equivalent to 3.2.0. Ignore it.
3.2.0 - 2016-05-19
This is a small single-feature release:
- •
- All tests using @given now
Single bug fix release
- •
- Another charmap problem. In 3.1.2 text() and characters() would break on systems which had /tmp mounted on a different partition than the Hypothesis storage directory (usually in home). This fixes that.
3.1.2 - 2016-04-30
Single bug fix release:
- •
- Anything which used a text() or characters() strategy was broken on Windows and I hadn't updated appveyor to use the new repository location so I didn't notice. This is now fixed and windows support should work correctly.
3.1.1 - 2016-04-29
Minor bug fix release.
- •
- Fix concurrency issue when running tests that use text() from multiple processes at once (issue #302, thanks to Alex Chan).
- •
- Improve performance of code using lists() with max_size (thanks to Cristi Cobzarenco).
- •
- Fix install on Python 2 with ancient versions of pip so that it installs the enum34 backport (thanks to Donald Stufft for telling me how to do this).
- •
- Remove duplicated __all__ exports from hypothesis.strategies (thanks to Piët Delport).
- •
- Update headers to point to new repository location.
- •
- Allow use of strategies that can't be used in find() (e.g. choices()) in stateful testing.
3.1.0 - 2016-03-06
- •
- Add a nothing() strategy that never successfully generates values.
- •
- sampled_from() and one_of() can both now be called with an empty argument list, in which case they also never generate any values.
- •
- one_of() may now be called with a single argument that is a collection of strategies as well as as varargs.
- •
- Add a runner() strategy which returns the instance of the current test object if there is one.
- •
- 'Bundle' for RuleBasedStateMachine is now a normal(ish) strategy and can be used as such.
- •
- Tests using RuleBasedStateMachine should now shrink significantly better.
- •
- Hypothesis now uses a pretty-printing library internally, compatible with IPython's pretty printing protocol (actually using the same code). This may improve the quality of output in some cases.
- •
- As a 'phases' setting that allows more fine grained control over which parts of the process Hypothesis runs
- •
- Add a suppress_health_check setting which allows you to turn off specific health checks in a fine grained manner.
- •
- Fix a bug where lists of non fixed size would always draw one more element than they included. This mostly didn't matter, but if would cause problems with empty strategies or ones with side effects.
- •
- Add a mechanism to the Django model generator to allow you to explicitly request the default value (thanks to Jeremy Thurgood for this one).
3.0.5 - 2016-02-25
- •
- Fix a bug where Hypothesis would now error on py.test development versions.
3.0.4 - 2016-02-24
- •
- Fix a bug where Hypothesis would error when running on Python 2.7.3 or earlier because it was trying to pass a python:bytearray object to python:struct.unpack() (which is only supported since 2.7.4).
3.0.3 - 2016-02-23
- •
- Fix version parsing of py.test to work with py.test release candidates
- •
- More general handling of the health check problem where things could fail because of a cache miss - now one "free" example is generated before the start of the health check run.
3.0.2 - 2016-02-18
- •
- directory was recreated this would have caused the tests to fail their health check on every run. This is now fixed for all the known cases, although there could be others lurking.
3.0.1 - 2016-02-18
- •
- Fix a case where it was possible to trigger an "Unreachable" assertion when running certain flaky stateful tests.
- •
- Improve shrinking of large stateful tests by eliminating a case where it was hard to delete early steps.
- •
- Improve efficiency of drawing binary(min_size=n, max_size=n) significantly by provide a custom implementation for fixed size blocks that can bypass a lot of machinery.
- •
- Set default home directory based on the current working directory at the point Hypothesis is imported, not whenever the function first happens to be called.
3.0.0 - 2016-02-17:
- •
- Addition of data() strategy which allows you to draw arbitrary data interactively within the test.
- •
- New "exploded" database format which allows you to more easily check the example database into a source repository while supporting merging.
- •
- Better management of how examples are saved in the database.
- •
- Health checks will now raise as errors when they fail. It was too easy to have the warnings be swallowed entirely.
New limitations:
- •
- choices() and streaming() strategies may no longer be used with find(). Neither may data() (this is the change that necessitated a major version bump).
Feature removal:
- •
- The ForkingTestCase executor has gone away. It may return in some more working form at a later date.
Performance improvements:
- •
- A new model which allows flatmap, composite strategies and stateful testing to perform much better. They should also be more reliable.
- •
- Filtering may in some circumstances have improved significantly. This will help especially in cases where you have lots of values with individual filters on them, such as lists(x.filter(...)).
- •
-
Codename: A new beginning
This release cleans up all of the legacy that accrued in the course of Hypothesis 1.0. These are mostly things that were emitting deprecation warnings in 1.19.0, but there were a few additional changes.
In particular:
- •
- non-strategy values will no longer be converted to strategies when used in given or find.
- •
- FailedHealthCheck is now an error and not a warning.
- •
- Handling of non-ascii reprs in user types have been simplified by using raw strings in more places in Python 2.
- •
- given no longer allows mixing positional and keyword arguments.
- •
- given no longer works with functions with defaults.
- •
- given no longer turns provided arguments into defaults - they will not appear in the argspec at all.
- •
- the basic() strategy no longer exists.
- •
- the n_ary_tree strategy no longer exists.
- •
- the average_list_length setting no longer exists. Note: If you're using using recursive() this will cause you a significant slow down. You should pass explicit average_size parameters to collections in recursive calls.
- •
- @rule can no longer be applied to the same method twice.
- •
- Python 2.6 and 3.3 are no longer officially supported, although in practice they still work fine.
This also includes two non-deprecation changes:
- •
- given's keyword arguments no longer have to be the rightmost arguments and can appear anywhere in the method signature.
- •
- The max_shrinks setting would sometimes not have been respected.
1.19.0 - 2016-01-09:
- •
- New @seed() decorator which allows you to manually seed a test. This may be harmlessly combined with and overrides the derandomize setting.
- •
- settings objects may now be used as a decorator to fix those settings to a particular @given test.
API changes (old usage still works but is deprecated):
- •
- Settings has been renamed to settings (lower casing) in order to make the decorator usage more natural.
- •
- Functions for the storage directory that were in hypothesis.settings are now in a new hypothesis.configuration module.
Additional deprecations:
- •
- the average_list_length setting has been deprecated in favour of being explicit.
- •
- the basic() strategy has been deprecated as it is impossible to support it under a Conjecture based model, which will hopefully be implemented at some point in the 2.x series.
- •
- the n_ary_tree strategy (which was never actually part of the public API) has been deprecated.
- •
- Passing settings or random as keyword arguments to given is deprecated (use the new functionality instead)
Bug fixes:
- •
- No longer emit PendingDeprecationWarning for __iter__ and StopIteration in streaming() values.
- •
- When running in health check mode with non strict, don't print quite so many errors for an exception in reify.
- •
- When an assumption made in a test or a filter is flaky, tests will now raise Flaky instead of UnsatisfiedAssumption.
1.18.1 - 2015-12-22
Two behind the scenes changes:
- •
- Hypothesis will no longer write generated code to the file system. This will improve performance on some systems (e.g. if you're using PythonAnywhere which is running your code from NFS) and prevent some annoying interactions with auto-restarting systems.
- •
- Hypothesis will cache the creation of some strategies. This can significantly improve performance for code that uses flatmap or composite and thus has to instantiate strategies a lot.
1.18.0 - 2015-12-21
Features:
- •
- Tests and find are now explicitly seeded off the global random module. This means that if you nest one inside the other you will now get a health check error. It also means that you can control global randomization by seeding random.
- •
- There is a new random_module() strategy which seeds the global random module for you and handles things so that you don't get a health check warning if you use it inside your tests.
- •
- floats() now accepts two new arguments: allow_nan and allow_infinity. These default to the old behaviour, but when set to False will do what the names suggest.
Bug fixes:
- •
- Fix a bug where tests that used text() on Python 3.4+ would not actually be deterministic even when explicitly seeded or using the derandomize mode, because generation depended on dictionary iteration order which was affected by hash randomization.
- •
- Fix a bug where with complicated strategies the timing of the initial health check could affect the seeding of the subsequent test, which would also render supposedly deterministic tests non-deterministic in some scenarios.
- •
-().
- •
-
A small bug fix release, which fixes the fact that the 'note' function could not be used on tests which used the @example decorator to provide explicit examples.
1.17.0 - 2015-12-15):
- •
-
There are no public API changes in this release but it includes a behaviour change that I wasn't comfortable putting in a patch release.
- •
-.
- •
- Errors caused by accidentally invoking the legacy API are now much less confusing, although still throw NotImplementedError.
- •
- hypothesis.extra.django is 1.9 compatible.
- •
- When tests are run with max_shrinks=0 this will now still rerun the test on failure and will no longer print "Trying example:" before each run. Additionally note() will now work correctly when used with max_shrinks=0.
1.15.0 - 2015-11-24
A release with two new features.
- •
- A 'characters' strategy for more flexible generation of text with particular character ranges and types, kindly contributed by Alexander Shorin.
- •
- Add support for preconditions to the rule based stateful testing. Kindly contributed by Christopher Armstrong
1.14.0 - 2015-11-01
New features:
- •
- Add 'note' function which lets you include additional information in the final test run's output.
- •
- Add 'choices' strategy which gives you a choice function that emulates random.choice.
- •
- Add 'uuid' strategy that generates UUIDs'
- •
- Add 'shared' strategy that lets you create a strategy that just generates a single shared value for each test run
Bugs:
- •
-
This is quite a small release, but deprecates some public API functions and removes some internal API functionality so gets a minor version bump.
- •
- All calls to the 'strategy' function are now deprecated, even ones which pass just a SearchStrategy instance (which is still a no-op).
- •
- Never documented hypothesis.extra entry_points mechanism has now been removed ( it was previously how hypothesis.extra packages were loaded and has been deprecated and unused for some time)
- •
- Some corner cases that could previously have produced an OverflowError when simplifying failing cases using hypothesis.extra.datetimes (or dates or times) have now been fixed.
- •
- Hypothesis load time for first import has been significantly reduced - it used to be around 250ms (on my SSD laptop) and now is around 100-150ms. This almost never matters but was slightly annoying when using it in the console.
- •
- hypothesis.strategies.randoms was previously missing from __all__.
1.12.0 - 2015-10-18
- •
-.
- •
- A number of cases where the repr of strategies build from lambdas is improved
- •
- Add dates() and times() strategies to hypothesis.extra.datetimes
- •
- Add new 'profiles' mechanism to the settings system
- •
- Deprecates mutability of Settings, both the Settings.default top level property and individual settings.
- •
- A Settings object may now be directly initialized from a parent Settings.
- •
- @given should now give a better error message if you attempt to use it with a function that uses destructuring arguments (it still won't work, but it will error more clearly),
- •
- A number of spelling corrections in error messages
- •
- py.test should no longer display the intermediate modules Hypothesis generates when running in verbose mode
- •
- Hypothesis should now correctly handle printing objects with non-ascii reprs on python 3 when running in a locale that cannot handle ascii printing to stdout.
- •
- Add a unique=True argument to lists(). This is equivalent to unique_by=lambda x: x, but offers a more convenient syntax.
1.11.4 - 2015-09-27
- •
- Hide modifications Hypothesis needs to make to sys.path by undoing them after we've imported the relevant modules. This is a workaround for issues cryptography experienced on windows.
- •
- Slightly improved performance of drawing from sampled_from on large lists of alternatives.
- •
-
- •
- Better argument validation for datetimes() strategy - previously setting max_year < datetime.MIN_YEAR or min_year > datetime.MAX_YEAR would not have raised an InvalidArgument error and instead would have behaved confusingly.
- •
- Compatibility with being run on pytest < 2.7 (achieved by disabling the plugin).
1.11.2 - 2015-09-23
Bug fixes:
- •
- Settings(database=my_db) would not be correctly inherited when used as a default setting, so that newly created settings would use the database_file setting and create an SQLite example database.
- •
- Settings.default.database = my_db would previously have raised an error and now works.
- •
- Timeout could sometimes be significantly exceeded if during simplification there were a lot of examples tried that didn't trigger the bug.
- •
- When loading a heavily simplified example using a basic() strategy from the database this could cause Python to trigger a recursion error.
- •
- Remove use of deprecated API in pytest plugin so as to not emit warning
Misc:
- •
- hypothesis-pytest is now part of hypothesis core. This should have no externally visible consequences, but you should update your dependencies to remove hypothesis-pytest and depend on only Hypothesis.
- •
- Better repr for hypothesis.extra.datetimes() strategies.
- •
- Add .close() method to abstract base class for Backend (it was already present in the main implementation).
1.11.1 - 2015-09-16
Bug fixes:
- •
- When running Hypothesis tests in parallel (e.g. using pytest-xdist) there was a race condition caused by code generation.
- •
- Example databases are now cached per thread so as to not use sqlite connections from multiple threads. This should make Hypothesis now entirely thread safe.
- •
- floats() with only min_value or max_value set would have had a very bad distribution.
- •
- Running on 3.5, Hypothesis would have emitted deprecation warnings because of use of inspect.getargspec
1.11.0 - 2015-08-31
- •
- text() with a non-string alphabet would have used the repr() of the the alphabet instead of its contexts. This is obviously silly. It now works with any sequence of things convertible to unicode strings.
- •
- @given will now work on methods whose definitions contains no explicit positional arguments, only varargs (bug #118). This may have some knock on effects because it means that @given no longer changes the argspec of functions other than by adding defaults.
- •
- Introduction of new @composite feature for more natural definition of strategies you'd previously have used flatmap for.
1.10.6 - 2015-08-26
Fix support for fixtures on Django 1.7.
1.10.4 - 2015-08-21
Tiny bug fix release:
- •
- If the database_file setting is set to None, this would have resulted in an error when running tests. Now it does the same as setting database to None.
1.10.3 - 2015-08-19
Another small bug fix release.
- •
- lists(elements, unique_by=some_function, min_size=n) would have raised a ValidationError if n > Settings.default.average_list_length because it would have wanted to use an average list length shorter than the minimum size of the list, which is impossible. Now it instead defaults to twice the minimum size in these circumstances.
- •
- basic() strategy would have only ever produced at most ten distinct values per run of the test (which is bad if you e.g. have it inside a list). This was obviously silly. It will now produce a much better distribution of data, both duplicated and non duplicated.
1.10.2 - 2015-08-19
This is a small bug fix release:
- •
- star imports from hypothesis should now work correctly.
- •
- example quality for examples using flatmap will be better, as the way it had previously been implemented was causing problems where Hypothesis was erroneously labelling some examples as being duplicates.
1.10.0 - 2015-08-04
This is just a bugfix and performance release, but it changes some semi-public APIs, hence the minor version bump.
- •
- Significant performance improvements for strategies which are one_of() many branches. In particular this included recursive() strategies. This should take the case where you use one recursive() strategy as the base strategy of another from unusably slow (tens of seconds per generated example) to reasonably fast.
- •
- Better handling of just() and sampled_from() for values which have an incorrect __repr__ implementation that returns non-ASCII unicode on Python 2.
- •
- Better performance for flatmap from changing the internal morpher API to be significantly less general purpose.
- •
- Introduce a new semi-public BuildContext/cleanup API. This allows strategies to register cleanup activities that should run once the example is complete. Note that this will interact somewhat weirdly with find.
- •
- Better simplification behaviour for streaming strategies.
- •
- Don't error on lambdas which use destructuring arguments in Python 2.
- •
- Add some better reprs for a few strategies that were missing good ones.
- •
- The Random instances provided by randoms() are now copyable.
- •
- Slightly more debugging information about simplify when using a debug verbosity level.
- •
- Support using given for functions with varargs, but not passing arguments to it as positional.
1.9.0 - 2015-07-27
This contains no functionality changes but fixes a mistake made with building the previous package that would have broken installation on Windows.
1.8.4 - 2015-07-20
Bugs fixed:
- •
- When a call to floats() had endpoints which were not floats but merely convertible to one (e.g. integers), these would be included in the generated data which would cause it to generate non-floats.
- •
- Splitting lambdas used in the definition of flatmap, map or filter over multiple lines would break the repr, which would in turn break their usage.
1.8.3 - 2015-07-20
"Falsifying example" would not have been printed when the failure came from an explicit example.
1.8.2 - 2015-07-18
Another small bugfix release:
- •
- When using ForkingTestCase you would usually not get the falsifying example printed if the process exited abnormally (e.g. due to os._exit).
- •
- Improvements to the distribution of characters when using text() with a default alphabet. In particular produces a better distribution of ascii and whitespace in the alphabet.
1.8.1 - 2015-07-17
New features:
- •
- Much more sensible reprs for strategies, especially ones that come from hypothesis.strategies. These should now have as reprs python code that would produce the same strategy.
- •
- lists() accepts a unique_by argument which forces the generated lists to be only contain elements unique according to some function key (which must return a hashable value).
- •
- Better error messages from flaky tests to help you debug things.
Mostly invisible implementation details that may result in finding new bugs in your code:
- •
- Sets and dictionary generation should now produce a better range of results.
- •
- floats with bounds now focus more on 'critical values', trying to produce values at edge cases.
- •
- flatmap should now have better simplification for complicated cases, as well as generally being (I hope) more reliable.
Bug fixes:
- •
- You could not previously use assume() if you were using the forking executor.
1.7.2 - 2015-07-10
This is purely a bug fix release:
- •
- When using floats() with stale data in the database you could sometimes get values in your tests that did not respect min_value or max_value.
- •
- When getting a Flaky error from an unreliable test it would have incorrectly displayed the example that caused it.
- •
-.
- •
-
- •
- strategies now has a permutations() function which returns a strategy yielding permutations of values from a given collection.
- •
- if you have a flaky test it will print the exception that it last saw before failing with Flaky, even if you do not have verbose reporting on.
- •
- Slightly experimental git merge script available as "python -m hypothesis.tools.mergedbs". Instructions on how to use it in the docstring of that file.
Bug fixes:
- •
- Better performance from use of filter. In particular tests which involve large numbers of heavily filtered strategies should perform a lot better.
- •
- floats() with a negative min_value would not have worked correctly (worryingly, it would have just silently failed to run any examples). This is now fixed.
- •
- tests using sampled_from would error if the number of sampled elements was smaller than min_satisfying_examples.
1.6.2 - 2015-06-08
This is just a few small bug fixes:
- •
- Size bounds were not validated for values for a binary() strategy when reading examples from the database.
- •
- sampled_from is now in __all__ in hypothesis.strategies
- •
- floats no longer consider negative integers to be simpler than positive non-integers
- •
- Small floating point intervals now correctly count members, so if you have a floating point interval so narrow there are only a handful of values in it, this will no longer cause an error when Hypothesis runs out of values.
1.6.1 - 2015-05-21
This is a small patch release that fixes a bug where 1.6.0 broke the use of flatmap with the deprecated API and assumed the passed in function returned a SearchStrategy instance rather than converting it to a strategy.
1.6.0 - 2015-05-21
This is a smallish release designed to fix a number of bugs and smooth out some weird behaviours.
- •
-.
- •
- flatmap simplification performance should now be better in some cases where it previously had to redo work.
- •
- Fix for a bug where invalid unicode data with surrogates could be generated during simplification (it was already filtered out during actual generation).
- •
- The Hypothesis database is now keyed off the name of the test instead of the type of data. This makes much more sense now with the new strategies API and is generally more robust. This means you will lose old examples on upgrade.
- •
- The database will now not delete values which fail to deserialize correctly, just skip them. This is to handle cases where multiple incompatible strategies share the same key.
- •
- find now also saves and loads values from the database, keyed off a hash of the function you're finding from.
- •
- Stateful tests now serialize and load values from the database. They should have before, really. This was a bug.
- •
- Passing a different verbosity level into a test would not have worked entirely correctly, leaving off some messages. This is now fixed.
- •
- Fix a bug where derandomized tests with unicode characters in the function body would error on Python 2.7.
1.5.0 - 2015-05-14:
- •
- Mixing keyword and positional arguments in a call to @given is deprecated as well.
- •
- There is a new setting called 'strict'..
- •
- max_examples in settings is now interpreted as meaning the maximum number of unique (ish) examples satisfying assumptions. A new setting max_iterations which defaults to a larger value has the old interpretation.
- •
- Example generation should be significantly faster due to a new faster parameter selection algorithm. This will mostly show up for simple data types - for complex ones the parameter selection is almost certainly dominated.
- •
- Simplification has some new heuristics that will tend to cut down on cases where it could previously take a very long time.
- •
- timeout would previously not have been respected in cases where there were a lot of duplicate examples. You probably wouldn't have previously noticed this because max_examples counted duplicates, so this was very hard to hit in a way that mattered.
- •
- A number of internal simplifications to the SearchStrategy API.
- •
- You can now access the current Hypothesis version as hypothesis.__version__.
- •
- A top level function is provided for running the stateful tests without the TestCase infrastructure.
1.4.0 - 2015-05-04
Codename: What a state.
The big feature of this release is the new and slightly experimental stateful testing API. You can read more about that in the appropriate section.
Two minor features the were driven out in the course of developing this:
- •
-.
- •
- There is a new debug level of verbosity which is even more verbose than verbose. You probably don't want this.
Breakage of semi-public SearchStrategy API:
- •
-.
- •
-:
- •
-.
- •
- If you reduced max_examples below the number of examples already saved in the database, you would have got a ValueError. Additionally, if you had more than max_examples in the database all of them would have been considered.
- •
- @given will no longer count duplicate examples (which it never called your function with) towards max_examples. This may result in your tests running slower, but that's probably just because they're trying more examples.
- •
-!
- •
-.
- •
-.
- •
- In Python 2.7, integers_from strategies would have failed during simplification with an OverflowError if their starting point was at or near to the maximum size of a 64-bit integer.
- •
- flatmap and map would have failed if called with a function without a __name__ attribute.
- •
- If max_examples was less than min_satisfying_examples this would always error. Now min_satisfying_examples is capped to max_examples. Note that if you have assumptions to satisfy here this will still cause an error.
Some minor quality improvements:
- •
- Lists of streams, flatmapped strategies and basic strategies should now now have slightly better simplification.
1.3.0 - 2015-05-22
New features:
- •
- New verbosity level API for printing intermediate results and exceptions.
- •
- New specifier for strings generated from a specified alphabet.
- •
- Better error messages for tests that are failing because of a lack of enough examples.
Bug fixes:
- •
- Fix error where use of ForkingTestCase would sometimes result in too many open files.
- •
- Fix error where saving a failing example that used flatmap could error.
- •
- Implement simplification for sampled_from, which apparently never supported it previously. Oops.
General improvements:
- •
- Better range of examples when using one_of or sampled_from.
- •
- Fix some pathological performance issues when simplifying lists of complex values.
- •
- Fix some pathological performance issues when simplifying examples that require unicode strings with high codepoints.
- •
- Random will now simplify to more readable examples.
1.2.1 - 2015-04-16
A small patch release for a bug in the new executors feature. Tests which require doing something to their result in order to fail would have instead reported as flaky.
1.2.0 - 2015-04-15
Codename: Finders keepers.
A bunch of new features and improvements.
- •
- Provide a mechanism for customizing how your tests are executed.
- •
- Provide a test runner that forks before running each example. This allows better support for testing native code which might trigger a segfault or a C level assertion failure.
- •
- Support for using Hypothesis to find examples directly rather than as just as a test runner.
- •
- New streaming type which lets you generate infinite lazily loaded streams of data - perfect for if you need a number of examples but don't know how many.
- •
- Better support for large integer ranges. You can now use integers_in_range with ranges of basically any size. Previously large ranges would have eaten up all your memory and taken forever.
- •
- Integers produce a wider range of data than before - previously they would only rarely produce integers which didn't fit into a machine word. Now it's much more common. This percolates to other numeric types which build on integers.
- •
- Better validation of arguments to @given. Some situations that would previously have caused silently wrong behaviour will now raise an error.
- •
- Include +/- sys.float_info.max in the set of floating point edge cases that Hypothesis specifically tries.
- •
-.
- •
- Fix some internal bugs with object lifecycle management that were impossible to hit with the previously released versions but broke hypothesis-django.
- •
- Bias floating point numbers somewhat less aggressively towards very small numbers
1.1.0 - 2015-04-06
Codename: No-one mention the M word.
- •
- Unicode strings are more strongly biased towards ascii characters. Previously they would generate all over the space. This is mostly so that people who try to shape their unicode strings with assume() have less of a bad time.
- •
-.
- •
- Out of the box support for Decimal and Fraction.
- •
- new dictionary specifier for dictionaries with variable keys.
- •
- Significantly faster and higher quality simplification, especially for collections of data.
- •
- New filter() and flatmap() methods on Strategy for better ways of building strategies out of other strategies.
- •
- New BasicStrategy class which allows you to define your own strategies from scratch without needing an existing matching strategy or being exposed to the full horror or non-public nature of the SearchStrategy interface.
1.0.0 - 2015-03-27
Codename: Blast-off!
There are no code changes in this release. This is precisely the 0.9.2 release with some updated documentation.
0.9.2 - 2015-03-26
Codename: T-1 days.
- •
- floats_in_range would not actually have produced floats_in_range unless that range happened to be (0, 1). Fix this.
0.9.1 - 2015-03-25
Codename: T-2 days.
- •
- Fix a bug where if you defined a strategy using map on a lambda then the results would not be saved in the database.
- •
- Significant performance improvements when simplifying examples using lists, strings or bounded integer ranges.
0.9.0 - 2015-03-23:
- •
-
Codename: Hygienic macros or bust
- •
- You can now name an argument to @given 'f' and it won't break (issue #38)
- •
- strategy_test_suite is now named strategy_test_suite as the documentation claims and not in fact strategy_test_suitee
- •
- Settings objects can now be used as a context manager to temporarily override the default values inside their context.
0.7.1 - 2015-03-21
Codename: Point releases go faster
- •
- Better string generation by parametrizing by a limited alphabet
- •
-).
- •
- Faster list simplification by first trying a binary chop down the middle
- •
- Simultaneous simplification of identical elements in a list. So if a bug only triggers when you have duplicates but you drew e.g. [-17, -17], this will now simplify to [0, 0].
0.7.0, - 2015-03-20
Codename: Starting to look suspiciously real
This is probably the last minor release prior to 1.0. It consists of stability improvements, a few usability things designed to make Hypothesis easier to try out, and filing off some final rough edges from the API.
- •
- Significant speed and memory usage improvements
- •
- Add an example() method to strategy objects to give an example of the sort of data that the strategy generates.
- •
- Remove .descriptor attribute of strategies
- •
- Rename descriptor_test_suite to strategy_test_suite
- •
- Rename the few remaining uses of descriptor to specifier (descriptor already has a defined meaning in Python)
0.6.0 - 2015-03-13
Codename: I'm sorry, were you using that API?
This is primarily a "simplify all the weird bits of the API" release. As a result there are a lot of breaking changes. If you just use @given with core types then you're probably fine.
In particular:
- •
- Stateful testing has been removed from the API
- •
- The way the database is used has been rendered less useful (sorry). The feature for reassembling values saved from other tests doesn't currently work. This will probably be brought back in post 1.0.
- •
- SpecificationMapper is no longer a thing. Instead there is an ExtMethod called strategy which you extend to specify how to convert other types to strategies.
- •
- Settings are now extensible so you can add your own for configuring a strategy
- •
- MappedSearchStrategy no longer needs an unpack method
- •
- Basically all the SearchStrategy internals have changed massively. If you implemented SearchStrategy directly rather than using MappedSearchStrategy talk to me about fixing it.
- •
- Change to the way extra packages work. You now specify the package. This must have a load() method. Additionally any modules in the package will be loaded in under hypothesis.extra
Bug fixes:
- •
- Fix for a bug where calling falsify on a lambda with a non-ascii character in its body would error.
Hypothesis Extra:
- hypothesis-fakefactory: An extension for using faker data in hypothesis. Depends
- on fake-factory.
0.5.0 - 2015-02-10
Codename: Read all about it.
Core hypothesis:
- •
- Add support back in for pypy and python 3.2
- •
- @given functions can now be invoked with some arguments explicitly provided. If all arguments that hypothesis would have provided are passed in then no falsification is run.
- •
- Related to the above, this means that you can now use pytest fixtures and mark.parametrize with Hypothesis without either interfering with the other.
- •
- Breaking change: @given no longer works for functions with varargs (varkwargs are fine). This might be added back in at a later date.
- •
- Windows is now fully supported. A limited version (just the tests with none of the extras) of the test suite is run on windows with each commit so it is now a first class citizen of the Hypothesis world.
- •
- Fix a bug for fuzzy equality of equal complex numbers with different reprs (this can happen when one coordinate is zero). This shouldn't affect users - that feature isn't used anywhere public facing.
- •
- Fix generation of floats on windows and 32-bit builds of python. I was using some struct.pack logic that only worked on certain word sizes.
- •
- When a test times out and hasn't produced enough examples this now raises a Timeout subclass of Unfalsifiable.
- •
- Small search spaces are better supported. Previously something like a @given(bool, bool) would have failed because it couldn't find enough examples. Hypothesis is now aware of the fact that these are small search spaces and will not error in this case.
- •
- Improvements to parameter search in the case of hard to satisfy assume. Hypothesis will now spend less time exploring parameters that are unlikely to provide anything useful.
- •
- Increase chance of generating "nasty" floats
- •
- Fix a bug that would have caused unicode warnings if you had a sampled_from that was mixing unicode and byte strings.
- •
-
Codename: TIL narrow Python builds are a thing
This just fixes the one bug.
-
Codename: O(dear)
This is purely a bugfix release:
- •
-.
- •
- Fix a bug in formatting of complex numbers where the string could get incorrectly truncated.
0.4.1 - 2015-02-03
Codename: Cruel and unusual edge cases
This release is mostly about better test case generation.
Enhancements:
- •
- Has a cool release name
- •
- text_type (str in python 3, unicode in python 2) example generation now actually produces interesting unicode instead of boring ascii strings.
- •
- floating point numbers are generated over a much wider range, with particular attention paid to generating nasty numbers - nan, infinity, large and small values, etc.
- •
- examples can be generated using pieces of examples previously saved in the database. This allows interesting behaviour that has previously been discovered to be propagated to other examples.
- •
- improved parameter exploration algorithm which should allow it to more reliably hit interesting edge cases.
- •
- Timeout can now be disabled entirely by setting it to any value <= 0.
Bug fixes:
- •
-
- •
- If you had strategies that could produce NaN (which float previously couldn't but e.g. a Just(float('nan')) could) then this would have sent hypothesis into an infinite loop that would have only been terminated when it hit the timeout.
- •
- Given elements that can take a long time to minimize, minimization of floats or tuples could be quadratic or worse in the that value. You should now see much better performance for simplification, albeit at some cost in quality.
Other:
- •
-:
- •
- Printing of failing examples. I was finding that the pytest runner was not doing a good job of displaying these, and that Hypothesis itself could do much better.
- •
- Drop dependency on six for cross-version compatibility. It was easy enough to write the shim for the small set of features that we care about and this lets us avoid a moderately complex dependency.
- •
- Some improvements to statistical distribution of selecting from small (<= 3 elements)
- •
- Improvements to parameter selection for finding examples.
Bugs fixed:
- •
-.
- •
- sampled_from would not work correctly on a single element list.
- •
-
- •
- Fix a bug where if you specified floats_in_range with integer arguments Hypothesis would error in example simplification.
- •
-.
- •
- Improved repr() for strategies and RandomWithSeed instances.
- •
-.
- •
- Provide a "derandomized" mode. This allows you to run hypothesis with zero real randomization, making your build nice and deterministic. The tests run with a seed calculated from the function they're testing so you should still get a good distribution of test cases.
- •
- Add a mechanism for more conveniently defining tests which just sample from some collection.
- •
-
- •
- Support for generation of frozenset and Random values
- •
-.
- •
- Fix for a bug where some strategies did not correctly implement could_have_produced. It is very unlikely that any of these would have been seen in the wild, and the consequences if they had been would have been minor.
- •
- Re-export the @given decorator from the main hypothesis namespace. It's still available at the old location too.
- •
- Minor performance optimisation for simplifying long lists.
0.3.0 - 2015-01-12
- •
- Complete redesign of the data generation system. Extreme breaking change for anyone who was previously writing their own SearchStrategy implementations. These will not work any more and you'll need to modify them.
- •
- New settings system allowing more global and modular control of Verifier behaviour.
- •
- Decouple SearchStrategy from the StrategyTable. This leads to much more composable code which is a lot easier to understand.
- •
- A significant amount of internal API renaming and moving. This may also break your code.
- •
- Expanded available descriptors, allowing for generating integers or floats in a specific range.
- •
- Significantly more robust. A very large number of small bug fixes, none of which anyone is likely to have ever noticed.
- •
-
- •
- Fix an embarrassing complete failure of the installer caused by my being bad at version control
0.2.1 - 2015-01-07
- •
- Fix a bug in the new stateful testing feature where you could make __init__ a @requires method. Simplification would not always work if the prune method was able to successfully shrink the test.
0.2.0 - 2015-01-07
- •
- It's aliiive.
- •
- Improve python 3 support using six.
- •
- Distinguish between byte and unicode types.
- •
- Fix issues where FloatStrategy could raise.
- •
- Allow stateful testing to request constructor args.
- •
- Fix for issue where test annotations would timeout based on when the module was loaded instead of when the test started
0.1.4 - 2013-12-14
- •
- Make verification runs time bounded with a configurable timeout
0.1.3 - 2013-05-03
- •
- Bugfix: Stateful testing behaved incorrectly with subclassing.
- •
- Complex number support
- •
- support for recursive strategies
- •
- different error for hypotheses with unsatisfiable assumptions
0.1.2 - 2013-03-24
- •
- Bugfix: Stateful testing was not minimizing correctly and could throw exceptions.
- •
- Better support for recursive strategies.
- •
- Support for named tuples.
- •
- Much faster integer generation.
0.1.1 - 2013-03-24
- •
- Python 3.x support via 2to3.
- •
- Use new style classes (oops).
0.1.0 - 2013-03-23
- •
- Introduce stateful testing.
- •
- Massive rewrite of internals to add flags and strategies.
0.0.5 - 2013-03-13
- •
- No changes except trying to fix packaging
0.0.4 - 2013-03-13
- •
- No changes except that I checked in a failing test case for 0.0.3 so had to replace the release. Doh
0.0.3 - 2013-03-13
- •
- Improved a few internals.
- •
- Opened up creating generators from instances as a general API.
- •
- Test integration.
0.0.2 - 2013-03-12
- •
- Starting to tighten up on the internals.
- •
- Change API to allow more flexibility in configuration.
- •
- More testing.
0.0.1 - 2013-03-10
- •
- Initial release.
- •
- Basic working prototype. Demonstrates idea, probably shouldn't be used.
ONGOING HYPOTHESIS DEVELOPMENT
Hypothesis development is managed by me, David R. MacIver. I am the primary author of Hypothesis.
However, I no longer do unpaid feature development on Hypothesis. My roles as leader of the project are:
- 1.
- Helping other people do feature development on Hypothesis
- 2.
- Fixing bugs and other code health issues
- 3.
- Improving documentation
- 4.
- General release management work
- 5.
- Planning the general roadmap of the project
- 6.
-
Hypothesis releases follow semantic versioning.
We maintain backwards-compatibility wherever possible, and use deprecation warnings to mark features that have been superseded by a newer alternative. If you want to detect this, the strict setting upgrades all Hypothesis warnings to errors.
Hypothesis does not have a long-term release plan. However some visibility into our plans for future compatibility may be useful:
- •
- We value compatibility, and maintain it as far as practical. This generally excludes things which are end-of-life upstream, or have an unstable API.
- •
- We would like to drop Python 2 support when it it reaches end of life in 2020. Ongoing support is likely to depend on commercial funding.
- •
- We intend to support PyPy3 as soon as it supports a recent enough version of Python 3. See issue #602.
HELP AND SUPPORT
For questions you are happy to ask in public, the Hypothesis community is a friendly place where I or others will be more than happy to help you out. You're also welcome to ask questions on Stack Overflow. If you do, please tag them with 'python supported.
If you need to ask questions privately or want more of a guarantee of bugs being fixed promptly, please contact me on hypothesis-support [at] drmaciver.com to talk about availability of support contracts.
PACKAGING GUIDELINES
Downstream packagers often want to package Hypothesis. Here are some guidelines.
The primary guideline is this: If you are not prepared to keep up with the Hypothesis release schedule, don't. You will annoy me and are doing your users a disservice.
Hypothesis has quite a frequent release schedule. It's very rare that it goes a month without a release, and there are often multiple releases in a given month.
Many people not only fail to follow the release schedule but also seem included to package versions which are months out of date even at the point of packaging. This will cause me to be very annoyed with you and you will consequently get very little co-operation from me.
If you are prepared to keep up with the Hypothesis release schedule, the rest of this document outlines some information you might find useful.
Release tarballs
Python versions
Hypothesis is designed to work with a range of Python versions. Currently supported are:
- •
- pypy-2.6.1 (earlier versions of pypy may work)
- •
- CPython 2.7.x
- •
- CPython 3.4.x
- •
- CPython 3.5.x
- •
- CPython 3.6.x
If you feel the need to have separate Python 3 and Python 2 packages you can, but Hypothesis works unmodified on either.
Other Python libraries
Hypothesis has optional dependencies on the following libraries:
- •
- pytz (almost any version should work)
- •
- faker, version 0.7
- •
- Django, all supported versions
- •
- numpy, 1.10 or later (earlier versions will probably work fine)
- •
- py.test (2.7.0 or greater). This is a mandatory dependency for testing Hypothesis itself but optional for users.
The way this works when installing Hypothesis normally is that these features become available if the relevant library is installed.
Testing Hypothesis.7.0 is strongly encouraged, but it may work with earlier versions (however py.test specific logic is disabled before 2.7.0).
Tests are organised into a number of top level subdirectories of the tests/ directory.
- •
- cover: This is a small, reasonably fast, collection of tests designed to give 100% coverage of all but a select subset of the files when run under Python 3.
- •
- nocover: This is a much slower collection of tests that should not be run under coverage for performance reasons.
- •
- py2: Tests that can only be run under Python 2
- •
- py3: Tests that can only be run under Python 3
- •
- datetime: This tests the subset of Hypothesis that depends on pytz
- •
- fakefactory: This tests the subset of Hypothesis that depends on fakefactory.
- •
- django: This tests the subset of Hypothesis that depends on django (this also depends on fakefactory).
An example invocation for running the coverage subset of these tests:
pip install -e . pip install pytest # you will probably want to use your own packaging here python -m pytest tests/cover
Examples
- •
- arch linux
- •
- fedora
- •
- gentoo (slightly behind at the time of this writing)
AUTHORDavid R. MacIver
|
https://www.systutorials.com/docs/linux/man/1-hypothesis/
|
CC-MAIN-2020-40
|
refinedweb
| 18,535
| 56.35
|
I can debug Python code using
ddd -pydb prog.py
prog.py
boost-python
break my_python.py:123
break my_cpp.cpp:456
cont
DDD
DDD
gdb
I found out how to debug the C++ part while running python. (while reading Python book..).
First you run the python program which includes C++ programs. At the start of the python program, use raw_input() to make the program wait for you input. But just before that do
print os.getpid() (of course you should have imported os package). When you run the python program, it will have printed the pid of the python program you are running and will be waiting for your keyboard input.
python stop code :
import os def w1(str): print (str) wait = raw_input() return print os.getpid() w1('starting main..press a key')
result :
27352 starting main..press a key
Or, you can use import pdb, pdb.set_trace() as comment below.(thanks @AndyG)
Now, suppose the C++ shared library is _caffe.so (which is my case. This _caffe.so library has all the C++ codes and boost python wrapper functions). 27352 is the pid. Then in another shell start gdb like
gdb caffe-fast-rcnn/python/caffe/_caffe.so 27352
or if you want to use graphical debugging using like DDD, do
ddd caffe-fast-rcnn/python/caffe/_caffe.so 27352
Then you'll see gdb starts and wait with prompt. The python program is interrupted by gdb and waits in stopped mode (it was waiting for your key input but now it's really in stopeed mode, and it needs gdb continue command from the second debugger to proceed with the key waiting).
Now you can give break point command in gdb like
br solver.cpp:225
and you can see message like
Breakpoint 1 at 0x7f2cccf70397: file src/caffe/solver.cpp, line 226. (2 locations)
When you give
continue command in the second gdb window(that was holding the program), the python code runs again. Of course you should give a key input in the first gdb window to make it proceed.
Now at least you can debug the C++ code while running python program(that's what I wanted to do)!
I later checked if I can do python and C++ debugging at the same time and it works. You start the debugger(DDD) like
ddd -pydb prog1.py options.. and attach another DDD using method explained above. Now you can set breakpoints for python and C++ and using other debug functions in each window(I wish I had known this a couple of months earlier.. I should have helped tons.).
EDIT : to get the pid, you can do
ps -aux | grep python instead. This pid is the next of ddd's pid.
|
https://codedump.io/share/4aaY5EaPV5V4/1/debugging-python-and-c-exposed-by-boost-together
|
CC-MAIN-2018-17
|
refinedweb
| 457
| 76.72
|
fcntl - file control
#include <sys/types.h> #include <unistd.h> #include <fcntl.h> int fcntl(int fildes, int cmd, ...);
The fcntl() function provides for control over open files. The fildes argument is a file descriptor.
The available values for cmd are defined in the header <fcntl.h>, which include:
- F_DUPFD
- Return a new file descriptor which is the lowest numbered available (that is, not already open) file descriptor greater than or equal to the third argument, arg, taken as an integer of type int. The new file descriptor refers to the same open file description as the original file descriptor, and shares any locks. The FD_CLOEXEC flag associated with the new file descriptor will remain open across the exec functions; otherwise the file will oflag values that are set in arg are ignored. If any bits in arg other than those mentioned here are changed by the application, the result is unspecified.
The following values for cmd_SETLK
- Set or clear a file segment lock according to the lock description pointed to by the third argument, arg, taken as a pointer to type struct flock, defined in <fcntl.h>. F_SETLK is used() will return immediately with a return value of -1.
- F_SETLKW
- This command is the same as F_SETLK except that if a shared or exclusive lock is blocked by other locks, the thread will wait until the request can be satisfied. If a signal that is to be caught is received while fcntl() is waiting for a region, fcntl() will be interrupted. Upon return from the signal handler, fcntl() will return -1 with errno set to [EINTR], and the lock operation will not be done.
Additional implementation-dependent values for cmd may be defined in <fcntl.h>. Their names will start with F_., that is, one in which a lock was found, the value of l_whence will be.
There will or an F_SETLKW.
If _XOPEN_REALTIME is defined and has a value other than -1:
-
- When the file descriptor fildes refers to a shared memory object, the behaviour of fcntl() is the same as for a regular file except the effect of the following values for the argument cmd are unspecified: F_SETFL, F_GETLK, F_SETLK, and F_SETLKW., will be treated as a request to unlock from the start of the requested segment with an l_len equal to 0. Otherwise an unlock (F_UNLCK) request will attempt to unlock only the requested segment.
Upon successful completion, the value returned depends on cmd as follows:
- F_DUPFD
- A new file descriptor.
- F_GETFD
- Value of flags defined in <fcntl.h>. The return value will not be negative.
- F_SETFD
- Value other than -1.
- F_GETFL
- Value of file status flags and access modes. The return value will not be negative.
- F_SETFL
- Value other than -1.
- F_GETLK
- Value other than -1.
- F_SETLK
- Value other than -1.
- F_SETLKW
- Value other than -1.
Otherwise, -1 is returned and errno is set to indicate the error.
The fcntl() function will some lock from another process and putting the calling process to sleep, waiting for that lock to become free would cause a deadlock.
None.
None.
None.
close(), exec, open(), sigaction(), <fcntl.h>, <signal.h>, <sys/types.h>, <unistd.h>.
Derived from Issue 1 of the SVID.
|
http://pubs.opengroup.org/onlinepubs/7990989775/xsh/fcntl.html
|
CC-MAIN-2014-52
|
refinedweb
| 533
| 65.73
|
PART 4
Specific Equipment
Order of Presentation
SG Radar
SC, SK Radars
Mark 3, Mark 4 Radars
SA Radar
SL Radar
SO Radar
SF Radar
SJ Radar
SD Radar
SU Radar
ST Radar
SR Radar
SP Radar
VD Remote Indicator
VF Remote Indicator
VG Remote Indicator
OBU Echo Box
Part 4
SG Radar
4-SG-1
SG RADAR
CONTROLS.
The switch marked A is the remote control for the main-power switch at the transmitter-receiver unit.
Meter B is identical to one located on the transmitter-receiver unit, and indicates line voltage. This meter should read between 110 and 120 volts AC. If it does not, call the maintenance
Figure 4 SG-1. Range and train indicator unit.
4-SG-2
unit. When switch K is an the RECEIVER TUNE position, it should read from 30 to 40 depending upon how well the receiver is tuned. The receiver should be tuned for maximum meter deflection. The meter reading in the MONITOR position will vary from time to time according to the way it is adjusted by the maintenance man. The operator should check the value at the start of his watch, and periodically thereafter, in order to determine whether any changes occur. The maintenance man should be notified immediately of any change.
The radiation switch D controls intermittent and continuous operation of the transmitter. For intermittent operation, switch D must be held in KEY position, as there is a spring action that automatically returns the switch to OFF position. LOCK position is for continuous operation.
Variac (E) controls the power supplied to the transmitter..
When the radar is operating, switch K is in the NORMAL position. The other positions, RECEIVER TUNE and MONITOR, are for purposes stated in 3 above.
Receiver sensitivity is controlled remotely by the operator through receiver gain control (L).
Receiver's tuning is controlled remotely by the operator with receiver tune control (M) This is set for maximum return signals.
The range crank (N) is geared to the range counters and also moves the step in the time base on the range scope. Thus, lining up the step with the blip on the range scope, the range of the target can be read directly from the range counters.
There are two range scales. 15,000 yards and 75,000 yards. Switch P permits the operator to select either of the two ranges..
As a safety precaution against overloading the transmitter, there is a relay which trips during any overload condition. This relay can be reset by the operator by pushing reset button (V).
Switch W will determine the positions OFF, INTERMITTENT, and CONTINUOUS operation for IFF equipment when it is installed,
Switch X adjusts the IFF gain.
Range focus (1), permits the operator to adjust the sweep on the range scope, permitting a sharp, even trace for the entire width of the scope. This setting is made on installing a new tube.
15,000-yard zero set (2) adjusts the calibration for the lower end of this range scale.
4-SG-3
15,000-yard limit set (3) adjusts the calibration for the upper end of this range scale.
75,000-yard zero set (4) adjusts the calibration for the lower end of this range scale.
75,000-yard limit set (5) adjusts the calibration for the upper end of this range scale..
PPI focus (7) permits the operator to adjust the sweep on the PPI for a sharp, even trace.
Dial lights switch (8) controls the intensity of lights on the PPI, bearing dial, and counters. Pilot lights switch (9) controls light intensity for the red and amber lights opposite the stand-by and radiation switches (this control has been omitted on later models).
There are five screwdriver adjustments with which the operator should not tamper once the set is operating normally.
H center adjustment (12) centers the time base on the range scope from right to left. that he can make any adjustment automatically, even in complete darkness.
TURNING ON AND OFF
Turning on.
Let us assume that the transmitter and receiver unit are ready for operation. When starting the gear for the first time, check to see that the controls are set as follows:
Turn the main-line power at the remote control switch (A) to STANDBY.
Set the radiation switch (D) in the OFF position.
Turn the variac (E) to zero (extreme counterclockwise).
Place synchro switch (J) on NORMAL position.
Turn receiver gain (L) down.
Throw signal-markers switch (Q) to SIGNALS.
Turn bearing switch (R) to NORMAL.
Set rec-tune, normal, monitor switch (K) to NORMAL.
Steps 1 through 8 represent the normal settings of the range and train indicator unit when equipment is on STANDBY, and from which the SG can be placed in operation as follows:
Turn the standby-on switch (A) to the ON position. The amber pilot light will indicate that power is available. Check the line voltage on meter (B), which should read between 110 and 120 volts.
Throw the radiation switch (D) to LOCK position. After about one minute, the red pilot light will glow, indicating that the transmitter is ready.
Turn the variac (F) slowly to the right until the transmitter current meter reads 25 milliamperes or less.
Turn the receiver gain control (L) up until about 3/8-inch grass appears on the range scope.
Start antenna rotation by turning the switch (R) to right or left.
Turning off.
In order to shut down the equipment the above procedure should be reversed.
Stop antenna rotation by turning switch (R) to the center position, leaving antenna on 000° relative bearing.
4-SG-4
Turn receiver gain control (L) down.
Return variac (F) to zero (extreme counterclockwise).
Turn radiation switch appear along the time base on the range scope. The operator now turns the range crank (N) until the 15,000-yard marker just begins to "pull down" into the step. The diagram in figure 4 SG-2 illustrates how the step should appear when adjusted to the correct position. If accurate, the range counters should read exactly 15,000 yards. Next, the step is lined up with the center of the 5,000-yard marker. Now, the counter should read exactly
Figure 4 SG-2. Correct calibration at 15,000- and 75,000-yard ranges scales.
4-SG-5
be visible at the left end of the time base. However, there should not be any confusion as to whether the first visible marker represents zero or 5,000 yards. If the zero marker appears, it will just he seen at the extreme left end of the time base. lithe first visible marker is some distance from the beginning of the time base, it is the 5,000-yard marker.:
Turn the signal-markers switch (Q) to MARKERS.
Set the range switch (P) to the 15,000-yard position..
Turn the range crank (N) until the top counter reads 5,000. Unlock the 75,000-yard zero set control (4), and adjust it until the 5,000-yard marker (first or second from the left) begins to drop. Lock the control.
Switch to the 15.000-yard range, and turn the range crank until the bottom counters read 5,000. Now unlock the 15,000-yard zero set control (2) and adjust it until the 5,000-yard marker begins to drop. Lock the control.
Re-check the upper limits on both range scales.
External calibration.
It is important that the external calibration of the set he checked periodically. This may be done by using one of three methods. It may be determined by comparison with fire-control radar, by ranging on some target whose distance can he determined precisely, or by observation of a double range echo. A double range echo is a false echo that will sometimes appear on the same bearing as a target, but at twice the range of that target. These echoes are most evident when the target ship is on a parallel course, close abeam, and large. If the real echo appears at 800 yards and the double range echo appears at 1,800 yards, the correct range of the target will he the difference between the two, or 1,000 yards. Since, in this example, your radar measured the range as 800 yards, the set's individual, constant error would be 200 yards, making all ranges low by that amount.
4-SG-6
then estimating the mean (average) setting between these two points. During tuning, always keep the signal below saturation by adjusting the receiver gain control (L), and make the setting rapidly. search should use both the "A" and PPI scopes, with the following procedure:
4-SG-7
flat top drops off into the step. The illustration in figure 4 SG-4 shows the correct means of ranging on a saturated pip. may be estimated by simply rotating the scale to coincide with the target. This device has two disadvantages: first, the range scale is inaccurate; second, it obscures the view of the PPI. A more satisfactory device is under°
Figure 4 SG-4 Correct method for ranging on a saturated signal on the 15,000-yard range scale.
4-SG-8
possible to do very rough spotting in both range and deflection by estimation from the PPI. fix.
4-SG-9
Multiple-reflection echoes are caused by the beam reflecting between several ships in a group before returning to the antenna. The bearing of the echo will be the same as one of the ships. Because of the changing position of the ships, this type of echo will disappear very quickly. 81 miles away. Trouble will be experienced with this type of echo only when there is high land over 81 miles away. In order to know when second-sweep echoes are likely to be encountered, the operator should be constantly aware of the ship's position in relation to land. To check this type of false echo, the pulse rate should be changed. If the echo is of the second-sweep type, it will shift in range or disappear entirely. Although these echoes are rare, they should be recognized and understood. Figure 4 SG-5 shows a graphic representation of how the second-sweep echo pip will shift its position on the "A" scope as the pulse frequency is varied.
Figure 4 SG-5. Second-sweep echoes.
4-SG-10
interfering structure. The SG also has side lobes 60° to 70° on either side of the main lobe. They will often show up on a large target which is within 5,000 yards. the gain control up and down.
Try changing the receiver local oscillator tuning.
Keep operating. always be on some certain relative bearing regardless of radar receiver; echoes are visible "riding on top" of the jamming pattern.
* See Part 3, Defense Against Jamming and Deception.
4-SG-11
in some cases, this information should he reported if possible. If the equipment is provided with an anti-jamming receiver, the jamming may be reduced sufficiently for reading targets without any detuning of the receiver. Detuning should be undertaken as a last resort, and then should be done very carefully and cautiously; otherwise all targets may be lost and the procedure made completely ineffective. No special method is offered for setting the controls of the AJ receiver, except that they should be varied for minimum jamming, the gain control coming first, and then the A\TC control.
Above all, never.
Accuracy.
Range accuracy is ± 150 yards.
Bearing accuracy is ± 1°.° using the "A" scope, and 9,
4-SG-12
If the antenna and "bug" will not turn when the antenna is switched to automatic rotation, the bearing as a series of markers described through 360°. When this condition exists, the operator should do the following:
Shift the switch on the gyro-control panel from the forward gyro to the after gyro supply or vice versa..
4-SG-13
[B L A N K PAGE]
4-SG-14
Part 4
SG-1b Radar
CONTROLS
TURNING ON AND OFF
CALIBRATION
OPERATIONAL TECHNIQUE
Station Keeping
Composition
Jamming and interference
PERFORMANCE
TROUBLES
CONTROLS
Range and Train Indicator
In order to take advantage of new developments in radar, a major modification has been authorized for radars of the SG series. The resulting modernization of SG-1 produces the SG-1b radar. A line drawing of the range and train indicator is shown in figure 4 SG-6. Only those controls which have been added or have taken on new or additional functions are lettered and discussed in this section. See SG radar page 4-SG-2 and those following for description of all other controls. For ease in locating and identifying, control to be discussed are lettered in figure 4 SG-6.
Figure 4 SG-6. Range and train indicator.
(1) The switch marked (A) is the battle short switch. One of these switches is also provided on the transmitter. Normally these switches should be in the OFF position to provide interlock protection for personnel who may open the units without cutting off the power. During battle or other critical times these switches may be turned on thereby short circuiting the interlocks and insuring continuous operation.
(2) The range scope sweep expansion (B) permits expansion of any part of the A-scope trace enabling echoes and IFF responses to be spread out and examined more closely. The sweep expansion control
4-SG-15
(B) is operative whenever the IFF switch (D) is turned on.
(3) Switch (C) turns on the range step of the A-scope and the range mark on the PPI. See sections under OPERATIONAL TECHNIQUE for discussion of taking ranges and bearings without the necessity of stopping the antenna.
(4) Switch (D) is the same IFF switch described under CONTROLS, page 4-SG-3 and labeled (W) on figure 4 SG-1. In this modification it has the added function of enabling operation of the sweep expansion control (B) described above.
Switches (E), (F), and (G) are called A-J (anti-jamming) controls. The functions of these switches will be described more fully under OPERATIONAL TECHNIQUE.
(5) Switch (E) labeled STC (Sensitivity Time Control) controls the circuit which reduces the gain of the receiver from zero range to approximately 5,000 yards range, thus reducing the effect of sea return.
(6) Switch (F) labeled IAVC (Instantaneous Automatic Volume Control) controls the circuit which reduces the effect of interference, pulse type jamming, and return from clouds by reducing the gain on the receiver for each individual echo and allowing it to return to normal between echoes on the time base.
(7) Switch (G) labeled FTC (Fast Time Constant) aids in separating closely bunched targets by sharpening and narrowing video pulses so that heavy wide echoes become sharp narrow pips and do not clutter up the time base.
(8) Control (H) is the hand crank which rotates the cursor (I) on the PPI tube enabling the operator to read bearings from the dial beneath the cursor (I) without stopping the antenna.
TURNING ON AND OFF
This modification has made no changes necessary in the turning on and off procedure outlined on pages 4-SG-4 and 4-SG-5.
CALIBRATION
Calibration procedure is the same as outlined on pages 4-SG-5 and 4-SG-6. Since the range markers and range step have been considerably sharpened, greater care than before will be required to insure accurate setting of the calibration controls.
OPERATIONAL TECHNIQUE
Read the section titled "OPERATIONAL TECHNIQUE," pages 4-SG-6 through 4-SG-12.
Included in the following discussion are only those points of operation that are basically different from that described in the above named pages and new techniques made possible by the addition of new circuits and their controls.
Determination of Range
Two features have been added to improve range determination.
(1) The range step on the A-scope has been considerably sharpened to facilitate accurate reading.
(2) A range spot has been provided on the PPI sweep so that the accurate range of a target may be determined from this scope without stopping the antenna. The range spot moves with the range step on the range scope (A-scope).
To determine range on the PPI tube, rotate the range crank until the range spot coincides with the center of the target on the screen. The range counters will then indicate the accurate range to the target.
Determination of Bearing
The determination of bearing is greatly facilitated by the hand operated cursor (I) on the PPI. The cursor is rotated by means of the hand crank (H) until it bisects the target, after which, bearings can be read on the illuminated dial surrounding the PPI tube. Thus bearings can be taken without stopping the antenna.
Station Keeping
On other models of the SG series sea return clutter on the A-scope and PPI obscured nearby echoes. Station keeping was best accomplished by reducing the gain to the point where the sea return did not interfere. This procedure interrupted normal search and was avoided whenever possible. When the STC switch (E) is on, sea return is diminished enough to allow station keeping to be accomplished and at the same time keeping a gain setting that is best for search. The STC circuit eliminates sea return without seriously affecting echoes from nearby targets.
Composition
Composition on a particular target can best be obtained by setting the range step just to the left of the target pip on the A-scope and switching on
4-SG-16
the IFF switch (E). This enables the operator to operate the sweep expansion control (B) and spread the target over a greater length of the sweep. By reducing the gain and turning on the FTC switch (G) a more accurate estimate of the number of peaks can be made on the echo. This is not fool proof and cannot be expected to take the place of an experienced operator. It will, however, enable an inexperienced operator to obtain more accurate estimates of composition.
Jamming and Interference
When the radar is being jammed, the receiver gain and receiver tune are the most important controls for combatting the jamming. See 4-SG-11 for a full discussion of how to use the above named controls.
Switches (F) and (G), IAVC and FTC respectively, should be turned on during the presence of jamming and interference of a pulse nature. These circuits act to differentiate or sharpen received impulses from jamming and interference as well as impulses from targets. Since ordinary jamming and interference represent pulses of fairly long duration, their effect can be considerably reduced by such differentiation or sharpening. As land masses and other large targets are also differentiated, care must be taken in interpreting the echoes when IAVC and TC are used.
During normal operation, these switches should be left in the OFF position.
PERFORMANCE
See page 4-SG-12.
TROUBLES
See pages 4-SG-12 and 4-SG-13.
In the SG-1b the 500 yard error in range reading caused by the receiver tune-normal-monitor switch not being in the NORMAL position has been eliminated.
4-SG-17
[B L A N K PAGE]
4-SG-18
PART 4
SC-SK RADAR
4-SC/SK-1
SC-SK RADAR
The SC radar is now obsolete and will not be dealt with in this discussion. The controls on the control unit and the receiver indicator unit, which the operator uses, are the same as those of the SC-1. The SC-1 radar is a modification of the SC. The transmitter was re-designed to increase the power output, and the antenna was modified. A preamplifier unit has been added to most sets. control unit.
- The receiver indicator unit.
- The transmitter.
- The preamplifier.
- The plan position Indicator unit.
- The antenna, together with transmission line and duplexer units..
Main power switch: controls power to all units.
Transmitter-plate voltage: this switch, when snapped on, applies all power to the transmitter. As it is turned clockwise, it increases the high voltage applied to the transmitter tubes..
Figure 4 SC/SK-1. Receiver, indicator and control unit.
4-SC/SK-2
Remote bearing indicator switch: applies control power to remote bearing repeaters.
Remote bearing mark: buzzer or horn switch to notify remote station when readings may be taken.
Automatic-manual toggle switch: power switch to slewing motor, which gives automatic antenna rotation.
Antenna-control switch: center position is off. Right gives clockwise rotation. Left gives counterclockwise rotation. Speed is controlled by the amount of turning.
Hand crank: for antenna control.
BL power switch; may or may not be used.
Sweep: local-PH; PPI position used when in sector search. Local position is the normal operating position.
Overload relay reset.
Bearing indicator: inner dial--true; outer dial--relative.
Brightness control of bearing indicator light.
Brightness control of pilot lights.
Transmitter pilot light.
BL power pilot light.
Receiver unit.AA. Radio frequency tuning control.
XX. Local oscillator tuning control.BB. Receiver gain control.
Indicator unit.
CC. Receive-calibrate switch.
DD. Dial light brightness control: controls brightness of the pilot lights and range-counter lights on the indicator unit.-INTERNAL::
Range 1-30,000 yards
Range 2-75 miles
Range 3-375 miles
Figure 4 SC/SK-2. Plan position indicator.
4-SC/SK-3
VV. Remote range mark: remote alarm switch,
ZZ. Power switch for receiver indicator unit.
PPI unit.
Mark-IFF switch: normal operating position on IFF. When on MARK, range step is shown on PPI.
Dimmer control for PPI bearing dial light.
PPI power switch.
Brilliance control.
Bearing indicator switch; RADAR-PPI: when on RADAR, bug follows the antenna; when on PPI, bug follows the yoke (cursor).
Focus control.
Bearing indicator adjustment control: for synchronizing bug reading and cursor reading, when operating bearing indicator switch is in the PPI position. Depress knob and set cursor (bearing blade) to read with the bug, then release knob to again engage the cursor.
Sector search control: in normal position, which is DOWN, clockwise rotation of the control increases the sector. Counterclockwise rotation narrows the sector. When pulled UP to engage the cursor, the sector may be rotated by rotating the cursor.
Sector search off-on switch.
Remote alarm button.
Relative-true switch for PPI.
Calibration control.
Range selector switch:
Range 1-20 miles
Range 2-75 miles
Range 3-200 miles
Centering control: controls only centering of sweep along axis of sweep.
Preamplifier unit.
All controls on the preamplifier unit are tuning controls.
TURNING ON AND OFF
Turning on.
Turn the main power switch (A) ON. The dial light of the bearing indicator will light, and the amplidyne motor will start.
Turn the transmitter plate voltage variac to 10. The pilot light (R) will light up and the filaments in the transmitter oscillator and power supply will glow.
Turn ON receiver indicator power switch (ZZ). Pilot light (RR) and the lights on the range counter will light. After a few seconds, a trace will be seen on the range scope, unless the brilliance control (EE) is fully counterclockwise.
Turn ON the power switch of the PPI unit. The lamp for the bearing glass will light.
After waiting a half minute, the filaments of the transmitter tubes will be hot, and the plate voltage variac (B) should be turned slowly up to between 70 and 100. This value is determined by the technician.
Turn on BL power switch (J).
Start the antenna rotating by setting switch (F) on AUTOMATIC, and switch (G) to give a slow rotation of the antenna.
Turn up PPI intensity control (4) until a trace appears.
Adjust focus (6) to get fine uniform trace..
Turning off.
- Turn down (CCW) PPI intensity control (4).
- Turn off power switch for PPI unit.
- Turn off BL power switch (J).
- Turn off automatic switch (F).
- Turn switch G to OFF position.
- Turn off receiver indicator power switch (ZZ).
- Turn plate voltage variac fully CCW.
- Turn off main power switch (A).
CALIBRATION
Calibrating the range scope.
Turn switch (CC) to CALIBRATE.
Turn switch (WW) to Range 1.
Adjust brilliance (FE), focus (FF), and astigmatism (GG) for a fine uniform trace. These controls interact one on the other, and must he adjusted together.
Turn crystal switch (PP) to ON. A "figure of eight" with the lower half clipped will now he observed on the "A" scope. If this figure is not observed:
Release lock and adjust (KK)--frequency
4-SC/SK-4
calibration so that a stationary figure of eight is observed. Lock control. (See fig. 4 SC/SK-3.)
Turn crystal switch (PP) to OFF.
Crank (TT) so that 2,000 yards is observed on the first range counter.
Figure 4 SC/SK-3. Figure of eight determines when calibration pips are 2,000 yards apart.
Release lock on calibrate minimum (LL) and adjust position of range step with (LL) so that the top of the second marker just begins to drop. (See fig. 4 SC/SK-4.)
Crank (TT) so that counter reads 20,000 yards.
Release lock and adjust calibrate maximum (JJ) so that the top of the eleventh marker begins to drop.
Check the 2,000-yard setting and if it has changed, repeat step 9.
Check the 20,000-yard setting. If either (JJ) or (LL) is changed, it affects the other. Keep checking until no further adjustment is necessary; lock both controls.
Turn (CC) to RECEIVE.
This method of calibration differs from that given in the instructional manual.
We use this method for three reasons:
To make the calibration and ranging uniform on SC-2 and SG, the center of the range mark and the center of the target pip are used.
It is easier to range on the center of a pip than on the leading edge..
Turn the mark-IFF switch (1) to MARK.
Set the range selector (WW) to Range 2, and set the counter to 60 miles.
Set the PPI range selector (13) to Range 2.
With the antenna rotating rapidly, a circle will appear on the PPI scope. Set calibrate control (12) so that the inboard edge of the trace corresponds with the 60-mile ring on the scope face.
Set the range counter to 30 miles and check the calibration. If the internal calibration of the set is correct, the PPI will be calibrated for all three range scales.
Figure 4 SC/SK-4. Pattern for calibrating minimum range on range 1.
4-SC/SK-5
Modification of PPI scope..
Make a center for the drafting compass out of a small piece of plastiglass in which you have drilled a shallow hole to hold the compass point.
Secure this center to the center of the PPI scope with scotch tape..
OPERATIONAL TECHNIQUE
Tuning the receiver. all, or when there are one or more target indications on the screen which have been identified and are of interest to the CIC watch officer only, as to their general position. The CIC officer will get most of the information he desires from his repeater scope, but a rough plot should also he kept. Readings every three minutes are usually sufficient for this plot.
The range scale used on the scopes will depend on the tactical situation. In a carrier task force, initial contact at the longest range is highly desirable. Two methods of search are possible:
PPI scope on 200-mile range scale, and "A" scope on 75-mile range scale,½revolutions
4-SC/SK-6 to get them. search for new targets, the PPI should be operated on the 20-mile range. The gain should greater than 20 miles, but is the most effective method when the primary purpose is fire-control coaching. At GQ, the standby operator can keep the fighter director officer informed of the general situation outside 20 miles by observing the range scope and taking ranges and bearings with continuous antenna.
Composition. pips, that
4-SC/SK-7
move slowly with occasional fading out, are characteristic of these targets, although sharp narrow pips have been observed. If identification is difficult by looking at the pip, a plot should be made to determine the the type and bearing of jamming to CIC.
The first reason for obtaining a hearing on the jamming is to determine whether or not it could be accidental interference instead. Jamming will not only be directional, but its true hearing will not he changed by any sudden change in your ship's course. Interference originating aboard your own ship will either be non-directional and appear on all bearings, or else it will always be on some certain relative bearing regardless of changes in own ship's course.
4-SC/SK-8
time to time, and if you are persistent enough some information may be obtainable..
Above all, never turn off the radar.
Even when jamming and/or deception is encountered, full 360°.
PERFORMANCE.
Maximum reliable range.
SC-2 RADAR
Antenna 90 feet
SK RADAR
Antenna 130 feet
Minimum range.
Accuracy.
Reading directly from the PPI, range accuracy is 2,000 yards or better, and bearing accuracy 4°.
Bearing and range accuracies for the different ranges on the "A" scope and PPI, when the antenna is sweeping or stopped, are listed in the table below.
Resolution.
* See Part 3, Defense Against Jamming and Deception.
4-SC/SK-9
TROUBLES turn the high voltage variac back to its normal operating position. Should the relay continue to kick out, notify the maintenance man as to what occurred and what has been done..
4-SC/SK-10
PART 4
MARK 3 AND MARK 4 RADAR
(FC, FD)
4-Mk. 3/Mk. 4-1
MARK 3 AND MARK 4 RADAR
(FC, FD)
CONTROLS
Main unit.
Plate current meter of modulation generator: should read about 200.
Plate voltage meter of modulation generator: should read about 500.
Load voltage: should be set to 120 at all times by means of control No. 11. (A recent directive says 115, but do not set it at 115 unless the set has been adjusted for this.)
Magnetron plate current meter: should he set, to read about 30 by controls 13 and 12.
Magnetron plate voltage meter: should be set to 12 (12,000 v.) by means of control No. 12.
Magnetron filament voltage meter: should read 13.5. Can be seen by looking through the wire mesh on the front of the transmitter.
Frequency control of modulation generator: adjusted by technician.
Radio dial light dimmer: controls the brightness of the illuminated dial on the receiver.
Receiver tuning control.
Receiver sensitivity control:
Load voltage control.
Magnetron plate voltage control.
Field control: adjusts plate current to the magnetron.
Remote-local switch: determines whether the receiver sensitivity is controlled from the main unit by control No. 10, or whether the sensitivity is controlled by the receiver sensitivity knob on the range scope.
Main off-on switch or line switch.
Plate off-on switch.
Dim-bright switch: controls brightness of the pilot lights on the face of the main unit.
Mon jack: used in tuning up the receiver.
Audio jack: used to obtain a synchronizing voltage when tuning up the receiver.
Screw lock for 21.
Magnetron filament voltage adjustment.
Control and indicator unit (range scope).
Intensity control: controls the brightness of the picture on the scope.
Image spread control: controls the size of the notch and expanded sweep.
Receiver sensitivity control: controls height of the grass and echoes.
Focus control: focuses the image on the face of the scope.
Sweep gain control: controls the length of the sweep. Should be completely clockwise.
Figure 4 Mk. 3/Mk. 4-1. Main unit.
4-Mk. 3/Mk. 4-2
Lobing on-off switch: turns lobing motor on or off.
Transmitter standby switch: turns the transmitter on or off. Used as a stand-by switch.
Pilot light dim-bright switch: (to be replaced by an A.G.C, switch.) Some sets have an anti-jamming switch above control 2.
Figure 4 Mk. 3/Mk. 4-2. Control and indicator unit.
Range unit.
Inner knurled nut: locks friction drive between the range knob, No. 3, and the electrical system controlling position of pips on the lace of the scope.
Outer knurled nut: moves images across the scope.
Range knob: moves images across the scope.
Pilot light bright-dim switch.
Dial light bright-dim control.
Signal button.
Figure 4 Mk. 3/Mk. 4-3. Range unit.
Train or elevation indicator.
Intensity control: controls the brightness of the image.
Image spacer control: move one sweep with relation to the other.
Sweep expansion control: opens or contracts the two steps.
Figure 4 Mk. 3/Mk. 4-4. Train or elevation indicator.
4-Mk. 3/Mk. 4-3
Focus control: focuses the image.
Pilot bright-dim switch.
TURNING ON AND OFF
Turning on the main unit.
Make sure main off-on switch (15) and plate off-on switch (16) are turned OFF and the plate voltage control (12) is turned completely counterclockwise (against the stop).
Turn on line transformer switch (mounted somewhere on the bulkhead).
Check magnetic controller switches (if any).
Turn on stand-by rotary switch near C and I Unit (when installed).
Turn on transmitter stand-by switch (7) on C and I Unit..
Turn on the plate off-on switch (16). Wait at least 5 minutes before turning up the plate voltage. When the plate switch is turned on, the two tubes located in the front of the high voltage rectifier light up..
Check filament voltage meter (6) to see if 13.5 volts are applied to the filament of the magnetron. If not, adjust to this value by magnetron filament voltage adjustment (21)..
Turn the plate voltage control (12) counterclockwise slowly until it hits the stop.
Turn plate on-off switch (16) to OFF.
Turn main off-on switch (15) to OFF.
Turn bulkhead switches off.
Every time the main unit is turned on from a cold start, the wear on the set is equivalent to three hours steady running of the set. Thus, if the set is to be turned off and on eight times a day it would be more profitable to let the set run continuously..
Turn sweep gain control (5) completely clockwise.
Turn intensity control (1) clockwise until an indication is observed on the face of the scope..)
Turn the image spread control (2) completely counterclockwise.
4-Mk. 3/Mk. 4-4
Turn the receiver sensitivity control (3) clockwise until the grass is about a half-inch high.
Make your "zero set" and continue to check it as frequently as possible while operating the set..
The lobing motor should he turned on only when using the set. It should remain on while searching for targets and while tracking. But remember, whenever the set is not actually being used, turn the lobing motor off.
Turning off the control and indicator unit.
Turn off lobing motor (6).
Turn off transmitter (7).
Turn intensity control completely counterclockwise (1).
Turning on the trainer's and pointer's scopes.
Turn the image spacer control (2) completely clockwise.
Turn the sweep expansion control (3) completely clockwise.
Make sure the range scope operator has the lobing motor turned on.
Turn the intensity control (1) clockwise until two horizontal lines appear on the scope. These lines will not be straight, but will be slightly curved.
Focus the traces by means of the focus control (4). It is important that the sweep should be just bright enough to see and no brighter. It should be focused to a fine, sharp line.
The image spacer (2) and the sweep expansion controls (3) should now be turned counterclockwise until the sweeps are about 1/4 inch wide and separated by about 1/8 inch.
Turning off the trainer's and pointer's scopes.
Turn the intensity control (1) completely counterclockwise.
Tuning the receiver.
Connect a patch cord to the vertical input terminals of the test scope. The BLACK side is connected to the grounded side which on RCA scopes is marked with a zero. The RED, or high side is connected to the top of the two vertical terminals which are marked high. Plug this cord into the right hand plug of the four jacks in the radar receiver panel; this is marked mon (18)..
Plug in the scope to 110 volts AC and turn the intensity clockwise until a click is heard..
Turn the vertical amplifier to the ON position. Increase the vertical gain control until the pattern occupies about 10 divisions on the scope.
4-Mk. 3/Mk. 4-5
lock in and cease to move, The image thus formed will be the same picture that is on the C and I scope in the director, except there will be no notch and there will be no expanded portion of the sweep. It should be noted here, that the operator might find the actual tuning procedure, which is about to be described, easier if he stops the image on the screen with two pips on it rather than one. This is largely a matter of preference, By adjusting the horizontal gain and the horizontal centering knobs, the operator can make the two pips line up with the divisions on the graduated face of the scope. By counting the number of divisions between the pips, and realizing that this distance corresponds to 100,000 yards, it is possible for him to estimate roughly the distance to any target..
Turn the range dial to the zero set given by the technician. It is a minus value of range, usually about minus 200 yards, at which the range dial is set, (A value of minus 200 yards is the same as a range of 99,800.)
Loosen the inner knurled nut (1) located above the range crank,.
Check to see if the range dial is at the zero set. and then carefully tighten the smaller knurled nut with the right hand, while holding the larger nut with the left hand to prevent it from turning..
4-Mk. 3/Mk. 4-6
Double range echo method of obtaining zero set.
(See Part 1. General Radar Principles.)
Train on another ship-the larger the better, on a course parallel to your ship and not more than 2,000 yards from it. (Between large ships, greater distances may be used.)
Start getting ranges on the other ship. It is important that the pointer and trainer remain right on the target during the following procedure. distance between the first and second echoes, namely 1,500 yards.
The first pip is then placed in the notch and the range dial is set to the difference between the ranges of the first and second pips (in this case 1,500 yards), by means of the zero adjustment nuts..
Level and cross level should always he cut in when aligning the antenna.
To align the antenna in train, two men are placed on top of the director with wrenches to loosen the securing bolts, and move the adjusting screws holding the antenna. The trainer and painter
* Note: This is a technician or Navy Yard job.
4-Mk. 3/Mk. 4-7
stay on a small, distant target with their optics. The maintenance man watches the pips on the trainer's scope, and directs the men adjusting the antenna to move it to the right or left, as indicated by the pips on the trainer's scope. When the pips are even, the antenna is locked in place.
The antenna should never be checked for elevation accuracy at angles less than 15 range operator will find that after once setting up the scope correctly, there are only two knobs that require further adjusting. but those two knobs will have to be adjusted frequently. These are the image spread (2) control, and the receiver sensitivity (3) control. The receiver sensitivity must be readjusted as often as necessary, to prevent saturation of the pips seen on the pointer's and trainer's scopes. He should make all adjustments on the range scope with his left hand (or with his right if his left hand is on the range knob). He must know the position of all controls so well that he can make adjustments to the scope without groping for the knob or taking his eyes from the scope..
4-Mk. 3/Mk. 4-8
When the pips are of the same height, the pointer and the trainer say. mark," or "on train," or "on point." Occasionally you will notice that the pips will act in reverse, in other words, when you train or point toward the lower pip, it will get lower rather than higher. This indicates that you have a minor lobe contact. The target actually bears 15° to 20° to the left or right of this.° to 20°.
Below 12°) for the target. The elevation angle should be varied from zero to about 10 in the notch. To help speed op the process of getting the pip in the notch, the operator should have previously cranked onto his range dial the range given by the search gear. If the target should disappear, close the notch, hold the train and elevation and turn the range knob back and forth. Soon the pip will show up again, and this time the operator will be able to get it into the notch; the pointer and the trainer will also get a fix or an indication of which way to train or elevate before it disappears. This process should be continued patiently. If the pip is clear the range operator knows that the pointer and or trainer are on target. If the pip is cloudy, the trainer and pointer are off the target. On some targets, however, such as a flight of planes, it will be impossible to get a clear pip.°, the normal width of the beam, to 15°, the width of the radiation pattern between half-power points with the lobing on. This increased coverage accompanied by no loss in power, since actually
4-Mk. 3/Mk. 4-9
we are simply waving the same beam back and forth in front of the director. It is easier to spot a target quickly with the increased beam width than it would be if you had only the one 9° beam. computor the target, thus not transmitting ranges continuously. Accordingly, a set-up on the director can be made more quickly by using radar ranges and rate control on the director than by any other means.
4-Mk. 3/Mk. 4-10
width of the notch. Some ships have installed a scotch tape scale on the face of the range scope to aid in spotting. classified as unintentional interference rather than jamming.
4-Mk. 3/Mk. 4-11
the transmitter slightly by varying the field control, and the plate voltage of the magnetron, or by varying the duplexer tuning. This method is valuable, but the jammer may shift to your new frequency. Changing the receiver local oscillator tuning at the main frame may also be of some assistance.. The official policy is to keep your transmitter on at all times, attempting to work through the jammer, even though at first glance it may seem impossible to do so. Perseverance and patience will be rewarded many times by your being able to range on the target. Because the echoes increase more rapidly with decreasing range than the jamming signal increases, it may he possible to suddenly see the pip from a closing target. This is another reason for leaving the transmitter on at all times. 3 RADAR
RELIABLE RANGES OF MARK 4 RADAR
4-Mk. 3/Mk. 4-12
PERFORMANCE.
Resolution.
The range resolution of the Mark 3 and the Mark 4 is 400 yards. The bearing resolution of the Mark 3 (3' × 12' antenna) is 5°. The bearing resolution of the Mark 4 is 10 not perpendicular to the shore line, the bearing resolution of the set comes into the problem, and it will be more difficult to pick up the target. The greater the deviation from the perpendicular, the farther out from the beach the target will have to be to be distinguished from the land by the radar. This can be seen in figure 4 Mk. 3/Mk. 4-8.
The same dependency on accurate knowledge of the range and bearing resolution also conies into effect when there are a number of ships steaming in column making a target angle of 90° or 270°. If the ships are close together they will appear as one pip on the range scope. If they made a target angle of 0° or 180°) the radar, unable to distinguish each individual plane, would train at a point midway between them. The same would be true of two ships.
* Elevation data applies only when antenna is elevated above 10°.* Elevation data applies only when antenna is elevated above 10°.
4-Mk. 3/Mk. 4-13
What has previously been said regarding the horizontal plane, also applies to the vertical plane. The elevation resolution is 10°.
Figure 4 Mk. 3/Mk. 4-8.
TROUBLES.
4-Mk. 3/Mk. 4-14
PART 4
SA RADAR
4-SA-1
SA RADAR
CONTROLS indicator circuits. When it opens, no trace appears on the screen and no dial lights come.
4-SA-2
P-12. Fil. voltage meter (on transmitter): indicates voltage on the primary of the filament transformer that supplies voltage to the filaments of the oscillator tubes. Control P-11, should be adjusted until the meter reads the same voltage as that marked on the small card above it. depend on the TCA for power. If the TCA should fail, this switch permits a continuation of the search.
Figure 4 SA-2. Receiver indicator unit.
4-SA-3
the screen, and on the "osc. adj. scope" (2-inch CRT). When in position 1, any strong signal occurring at a rate of about 60 cycles per second will "synchronize the sweep" so that a strong pulse will appear fairly steady on the sweep. This is called internal synchronization. In position 2, the sweep on the scope is started by the transmitter pulse. white bug used when lobe switching and matching pips..
4-SA-4
Ad-12. First R.F.: receiver tuning adjustment..
TURNING ON AND OFF
Turning on.
See that these controls are in the proper position.
- Transmitter power OFF.
- Slewing motor OFF.
- L-R motor OFF.
- Emergency train-AUTO.
- Antenna train-TRUE (if ship's gyro compass is operating properly).
- Plate voltage control fully counterclockwise.
- Receiver gain down (fully CCW).
- Intensity down (fully CCW)..
Alter about 30 seconds, a relay will snap in the TCA.
Now snap transmitter power switch ON (up). The plate current meter should light up..
Turning off.
Turn plate voltage variac fully counterclockwise.
Snap transmitter power switch to OFF position.
Turn off main power switch.
CALIBRATION
If the cal-synch switch is in position 2 and cal-fid-IFF is in position 2, 3 or 4, the transmitter pulse will be visible on the scope when gain is increased.
Snap cal-fid-IFF switch to cal (No. 1) position and cal-synch switch to position 3. The trace will disappear from the range scope. Adjust focus (No. Ad-7) control until some indication appears on the 2-inch scope.
Now adjust cal-osc control until a stationary pattern appears on the 2-inch scope. Either a figure eight pattern or a horizontal V is satisfactory.
Then turn focus (No. Ad-7) control so that this picture disappears and snap cal-synch to position 2. Range marks should again he visible on the range scope. Snap range selector switch to the A position (30,000 yards).
Set the range counters to read precisely 6,000
Figure 4 SA-3. Pattern for calibrating minimum range on 15,000-yard scale.
4-SA-5
yards; next adjust cal-min so the step is accurately aligned with the beginning of the second range mark. This adjustment is correct when the little peak just beyond the right-hand end of the first range mark is leveled up with the end of that mark (at the beginning of the second range mark). (see fig. 4 SA-3.)
Adjust cal-max until the counter reads 26,000 yards when the step is lined up with the beginning of the seventh range mark. (see fig. 4 SA-4.)
Repeat steps 5 and 6 until no further adjustment is necessary to make the step read correctly at either end, then snap cal-fid-IFF switch to position No. 2.
Figure 4 SA-4. Pattern far calibrating maximum range an 15,000-yard scale.
OPERATIONAL TECHNIQUE
Tuning the receiver.
Increase the receiver gain until some grass appears. If any targets are present, adjust OSC., 2nd R.F., and 1st R.F. controls until the pip appears largest. Unless some target is present to tune on, this step should not vertical control until the trace appears directly above the scale.).
Long-range search.
4-SA-6
attention to the left-hand portion of the time base. Again readjust gain, astigmatism, and intensity controls slightly, if necessary. Repeat in order, the steps outlined.
Searching over land..
The operator must remember to keep searching. He should not find one target and "camp on it" from then on. the bug. For each individual, this time is practically constant; in other words, the bearing error will be practically constant. When an operator determines the magnitude of his individual "error" he can read the bug, correct for his "error" and report the corrected reading. An example will serve to make this clear..
Tracking.
4-SA-7
scale marked on the front of the scope. (Do not use the range step.) If the plane is close on initial contact, you can save valuable time by reporting it as a bogey without interrogating first. The next time around, interrogate, estimate composition, get accurate bearing and range, and see whether they are opening or closing range, or crossing. Report. Snap cal-fide-IFF switch to position 4 to check for IFF-response..
Fire-control liaison.
Use of the SA radar for antiaircraft. Also the antenna must be kept bearing on the target. The operator does this by keeping the two pips from the target matched in height; it may be necessary to reduce the gain to keep these pips below saturation. He keeps the two steps lined up with the two pips, and reads the ranges indicated on the counters. gain control up and down.
- Try changing receiver local oscillator toning.
- Keep operating.
- Report type and bearing of jamming to CIC.
The first reason for obtaining a bearing on the jamming is to determine whether or not it could be accidental interference. Jamming will not only be
4-SA-8
directional, but its true bearing will not be changed by any sudden change in your ships course. Interference originating aboard your own ship will either be non-directional and appear on all bearings, or else it will always be on some certain relative bearing regardless of your change from time to time, so if you are persistent enough some information may be obtain.
Antenna 89 feet
* See Part 3, Defense Against Jamming and Deception.
4-SA-9
Minimum range.
Range accuracy.
When using the step and the 30,000-yard scale, the accuracy is about ± 100 yards. When using the 75-mile scale and reading ranges from the transparent tape, the accuracy is about ± 1.0 mile.
Bearing accuracy.
With lobing ± 1°
Without lobing ± 3° - 5. Another common fault is called multiple pulsing. The trace appears to flicker and jump, especially when using the 375-mile scale. Sub-multiple pulsing is indicated when the normal opening below the pip is closed by a bright line..
4-SA-10
Part 4.
SA-1, SA-2 RADAR
SA-1, SA-2 RADAR
The SA and SA-2 radars employ almost identical operating procedures. Therefore, the discussion of SA-2 radar will only supplement and enlarge upon the information already presented on the SA radar.
The SA-1 radar is obsolete and practically nonexistent on ships of the fleet, and accordingly merits very little discussion.
Model SA-1 is a small, general-purpose detection radar. It does not incorporate the master PPI unit and accessory components furnished with the models SA and SA-2, and hence further falls by the wayside as an important air-search radar.
Model SA-2 is a medium-range aircraft search radar intended for use on certain small combatant vessels and auxiliaries. All the latest models of SA-2 have included a master PPI unit and its associated components, the Bearing Amplifier Converter, and the new Anti-Jam Receiver, and will be substantially equivalent to the latest model SA-2 equipments. The following discussion will therefore treat the PPI, Bearing Amplifier Converter, and Anti-Jam Receiver as being integral parts of the SA radar system.
CONTROLS
The controls the operator may come in contact with may be divided into five main classifications: operating controls and indicators, selector switches, power controls and indicators, adjustments, and alarms. The majority of the controls are found on the receiver-indicator panels. A few of these controls are mounted on the transmitter unit, which usually is installed elsewhere in the ship. In addition, once control (on-off switch) is mounted on the Bearing Amplifier Converter cabinet.
It should be emphasized that the most important operating controls are located on the receiver-indicator panel. Under normal operating conditions, this is the only unit upon which the radar operator must focus his attention.
The various controls will be explained by accompanying drawings and by frequent cross references to page 4-SA-2 through page 4-SA-10.
Power Controls
Controls P-1 to P-13, inclusive, are identically located in the SA and SA-2 radars and have the same functions in the sets. However, meter P-13 is called "tube hours" in the SA radar and "elapsed time" in the SA-2 radar.
If the fuse (P-8) opens, there will be no trace on the "A" scope, and no dial lights will appear on the receiver-indicator unit. In addition, there will be no receiver output fed to the PPI unit, and the set will be inoperative.
Due to the addition of the master PPI unit to the original model SA radar, two more power controls have been added.
P-14. PPI main power switch: Controls all power applied to the PPI unit. Power is applied to the PPI unit when the switch is in the ON position.
P-15. Fuse (labeled "heater"): this 3 amp fuse is in serries with a heater unit, the purpose of which is to prevent moisture from condensing inside the
4-SA-11
equipment. If P-15 should open, there would be no immediate visible indication.
P-16. Fuse (labeled "H.V."): This 5 amp fuse is in series with the primary of the high voltage transformer, T1202. If it opens, the PPI unit becomes inoperative.
P-17. Filament tuning: This control regulates the amplitude of oscillation (output) of the transmitter tubes. It is primarily a technician's and not an operator's control.
Selection Switches
Selection switches S-1 through S-8, inclusive, have the same general functions in the SA-2 radar as they do in the SA radar. However, the following minor differences exist:
S-2. Emergency train, CCW, normal, CW (called "emergency train, CCW, auto, CW," in the SA).
S-4. Range sel: The setting of this switch determines the range scale being used--40,000-yard scales when in position A, 80 miles when in B, and 400 miles when in position C.
S-5. Cal-oper IFF (called "cal-fid IFF" in the SA). S-6. Cal synch (calibrate, synchronizing) switch: With the cal-oper IFF switch (S-5) in position 3 and the cal synch switch (S-6) in position 2, it can be observed on the two-inch cathode ray tube (Ad-6) whether or not the transmitter is pulsing normally. In the SA radar there is no corresponding visual indication to show if the pulse repetition frequency is correct at 60 cycles. Typical keying indicator patterns are shown in figure 4 SA-7.
S-8. Lobing off (called "L.R. off" in the SA). Modification of SA equipments and early model SA-2 equipments to include the master PPI unit and "Anti-Jam" receiver makes necessary a discussion of several additional selection switches:
S-9. AVC bal (automatic volume control balance): This three-position switch adjusts the speed with which the AVC action takes place. Fast AVC action occurs with the switch in position 3 (switch turned clockwise all the way), position 2 of S-9 corresponds to medium AVC action, and position 1 (all the way counterclockwise) corresponds to slow AVC.
S-10. Range: Setting of this switch determines the range scale being used on the PPI. The range scales available are 20, 80, or 200 miles.
S-11. True bearing-relative bearing switch: With the switch in the relative bearing position, the antenna will stay on the same relative bearing when the ship changes heading, the PPI will indicate relative bearings, and relative bearings only are indicated on the bearing indicator. A green pilot lamp in the PPI unit will light with the switch in relative bearing. When the switch is in the true bearing position, the antenna stays on the same true bearing as the ship changes course, true bearings are read from the PPI, and both true and relative bearings may be read from the bearing indicator.
S-12. Sector sweep off: With the sector sweep in the up (or on) position, and the emergency train switch (S-2) in the CW position, the antenna will
4-SA-12
Figure 4 SA-6. Receiver indicator and PPI unit.
4-SA-13
train back and forth through approximately a 90° arc. The sweep on the PPI scope is synchronized with the antenna rotation and hence rotates back and forth over the same sector that the antenna is searching.
S-13. Sector train selector switch: This switch has eight positions, which enable the operator to choose any of the eight sectors that he may desire to have around a true bearing coinciding with any one of the four cardinal directions of the compass, or 45° off from any of these, or else around the corresponding fixed relative bearing. In other words, the center bearing line of any two adjacent sectors are separated by 45°. Turning the emergency train switch to the CCW position causes the antenna to sweep an arc of approximately 300°.
S-14. Operation switch: This is a five-position selector switch. The IFF & cal. (extreme CCW) and IFF positions of this switch (S-14) permit the PPI equipment to be used for recognition operation, respectively, with and without range calibration markers appearing on the screen of the indicator tube. In the normal Position (middle), the radar video output signal of the SA receiver is applied to the PPI unit. This constitutes normal radar operating conditions. Electronic calibration markers can be made to appear on the master PPI by putting the Operation switch on the cal-mas (calibrate markers) position. In the cal. rem. (calibrate remote) position of this switch, calibration markers appear on the remote equipments connected with the main radar.
S-15. PPI bearing repeat: Closing this switch enables either true or relative antenna bearing indications to be transmitted to remote positions. Whether true or relative bearing is transmitted depends on the mod of operation selected from the panel controls on the SA-2 radar.
OPERATING CONTROLS AND INDICATORS
Operating controls (Op-1) to (Op-7) inclusive, have the same general functions in the SA-2 radar, Op-2 (A-yards range counters) indicates the range in yards for a 40,000-yard nominal range, Op-3 (B-miles range counter) the rang in miles for an 80-mile nominal range, and Op-4 (C-miles range counter) the range in miles for a 400-mile nominal range.
Figure 4 SA-7. Keying indicator patterns.
4-SA-14
In addition to the operating controls mentioned above, inclusion of the PPI unit and the "Anti-Jam" Receiver in the SA-2 radar system makes necessary a discussion of several more operating controls.
Op-8. Gain control: This control is on the "Anti-Jam" Receiver, and is perhaps one of the most important controls that the operator has to manipulate. As its name implies, this control makes it possible to control the over-all amplification of the "Anti-Jam" Receiver, and hence regulate the size of the echo indication presented on the cathode ray tube.
Op-9. Cursor dial: Field change 31 added this improvement to the master PPI unit, the purpose being to enable the operator to get faster and more accurate bearings. The cursor dial consists of a transparent shield which covers the PPI screen. This screen is covered with range calibration circles but has only one single radial line on it from the center outward. Furthermore, this shield is mechanically connected to a hand crank located on the lower right hand side of the indicator screen window. To determine the bearing of a target, turn the hand crank until the radial line (cursor pointer) bisects the circular arc formed by the echo indication on the fluorescent screen. The bearing of the target can then be read off the azimuth scale to which the cursor is pointing.
Op-10. PPI tube: This is a cathode ray tube used in conjunction with the "A" scope (Op-1) in getting ranges and bearings.
Op-11. Bearing markers off: Throwing this switch on, turns lights illuminating the azimuth scale around the PPI scope.
Adjustments
Adjustments Ad-1 through Ad-19, inclusive, have the same general functions in the SA-2 radar as in the SA radar. However, several of these controls are named differently in the SA-2 radar. In particular, Ad-9 (cal max on the SA radar) is called max set; and Ad-18 (L.R. amp on the SA radar) is called lobe sep.
The new "Anti-Jam" Receiver contains two RF stages, just as did the original SA receiver. However, condensers for both RF stages have been ganged together and are controlled by one RF control (Ad-23). Hence, in tuning the "Anti-Jam" Receiver, the operator is making the same adjustments when he turns Ad-3 that he made on the original receiver when he turned both Ad-12 and Ad-13.
Ad-22 [sic: "Ad-19"?]. Duplexer adjustment: Is not used if an external duplexer is incorporated in the transmitter.
Ad-22. Video balance: This is an "Antijam" control designed chiefly to eliminate railings or to at least keep them of no larger amplitude than the echo. Under normal operating conditions (no jamming present), the Video balance control should be in the CCW position.
Ad-23. R.F. (Radio Frequency): This is a receiver tuning adjustment.
Ad-24. Rej. (rejection control), and Ad-25 Rej. bal. (rejection balance control): The rejection control and the rejection balance control are "Antijam" controls designed to work together to prevent an undesired signal from being passed through the receiver. If adjusted correctly, they constitute a wave trap for a particular undesired signal. These controls are designed to be used chiefly against an interfering continuous wave signal.
Ad-26. Video gain: This control is on the PPI unit. It is used to adjust the strength of the echo signals received at the PPI independently of the main gain control. Under normal operating conditions this control is not of much importance.
Ad-27. Focus: Controls the sharpness of the picture on the screen of the PPI (Op-20).
Ad-28. Intensity: Controls the brilliance (or intensity) of the trance on the screen of the PPI.
In addition to the above adjustments on the receiver-indicator, there are two adjustments on the SA-2 transmitter unit.
Ad-20. Grid tuning: This transmitter control will be manipulated by the technician and not by the operator. The SA-2 transmitter is designed to operate at the rate of 60 pulses per second. Any departure from this pulse repetition frequency (as evidenced by the picture on the 2-inch scope) can be offset by proper adjustment of the grid tuning control.
Ad-21. Locking voltage: This control is a fine adjustment of the pulse repetition frequency. In general, coarse adjustment of the pulsing rate is obtained by means of the grid tuning control (Ad-20), and find adjustment by means of the locking voltage control (Ad-21).
Alarms
A1-1 and A1-2: These alarms are the same on the SA-2 radar as on the SA radar. (Actually they are seldom used on either radar system.)
4-SA-15
Nomenclature
In line with Navy standard nomenclature, some of the controls mentioned above will be renamed. Consequently, it may be noted on some SA-2 radar systems that the name plates of the controls bear revised designations of the controls affected as listed below:
TURNING ON AND OFF
Almost identical operational technique is required for the SA and SA-2 Radars. Thus the section below on operation of the SA-2 Radar can be applied equally well to the SA radar. It should be noted, however, that the method of turning on and off given below for the SA-2 radar differs somewhat from that given for the SA radar on page 4-SA-5.
Turning on
1. See that the following controls are in the proper position before turning on:
- Gain down (fully CCW).
- Intensity down (fully CCW).
- Slewing motor OFF.
- L.R. motor OFF.
- Plate voltage variac down (fully CCW).
- Transmitter power switch OFF.
- Emergency train in center position.
- PPI intensity down (fully CCW).
- PPI video gain down (cully CCW).
- Sector sweep switch OFF.
- True--relative switch on TRUE if ship's gyro system is operating properly, otherwise both should be on RELATIVE.
2. Snap on the main power switch, and adjust the line voltage control to read 115 voltes on the line voltage meter (P-4). Immediately turn on the PPI power, and leave it on until ready to work on this unit. Then snap on the transmitter power switch (P-4), and when light appears in the plate current meter, it is ready to be adjusted as follows. While watching the plate current meter, turn the plate voltage variac clockwise until the needle on the plate current meter makes one sharp dip, and then continue to move it clockwise until the meter reads from 5 to 7 milliamperes, or until a stop is reached. If the overload relay should trip while doing this, it may be necessary to lower the plate voltage, reset the relay in the transmitter (turn the emergency control switch on the transmitter OFF and then ON again), and continue operation using a slightly lower plate current. As a final check, make sure the line voltage still reads 115 volts.
Turning Off
1. Turn the PPI intensity and the video gain fully CCW.
2. Snap the sector sweep switch OFF.
3. Snap the PPI main power switch OFF.
4. Turn down the gain and the intensity on the "A" scope (fully CCW).
5. Turn the plate voltage variac down and the transmitter power switch off.
6. Turn off the main power switch.
CALIBRATION
1. Turn the Cal-oper IFF switch to position 1, and the Cal synch switch to position 3. This allows the marker oscillater to be calibrated as follows: Vary the focus control (Ad-7) until a sharp trace appears on the 2-inch scope. Then adjust the cal-osc control until a clearly defined, stationary pattern appears on the 2-inch scope. (Either a figure eight or a horizontal "V" is satisfactory.) This will insure that the markers are exactly 4,000 yards apart in range.
2. Next, turn the cal synch switch to position 2 and place the range selector switch in the position A. Set the range counter to read exactly 6,000 yards, and adjust cal min so the step is accurately aligned with the beginning of the second range marker. This adjustment is correct when the little peak just beyond the right hand end of the range mark is leveled up with the end of that (at the beginning of the second marker). See figure 4SA-3.
3. Adjust the range counters to read exactly 34,000 yards, and adjust cal max so that the range step is accurately aligned with the beginning of the ninth marker or the trailing edge of the eight marker.
4. Repeat steps 2 and 3 as many times as necessary until the stop reads correctly at both ends.
4-SA-16
In other words, make sure that when the range dial reads 6,000 yards, the range step is lined up with the 6,000-yard range marker; and when the range dial reads 34,000 yards, the range step is lined up with the 34,000-yard marker. When calibration is completed, switch the Cal-oper IFF switch to position 3.
Tuning the receiver
1. First set the antenna, osc., and R.F. controls to approximately correct setting by use of the technicians calibrate chart (Ad-16). Then increase the receiver gain until grass appears on the "A" scope. Pick a steady pip to tune on, and readjust the tuning controls for maximum height of pips. Repeat each adjustment at least twice. While working with the receiver unit, check to see that the "Anti-Jam" controls are secured properly: rej. control CW, rej. Bal. control CCW, vid. bal. CCW, and AVC bal. CW.
Final adjustments for the "A" scope
Turn the cal-oper IFF switch to position 4, and adjust the IFF gain until approximately one-eight inch of grass appears below the "A" scope time base. Throw the cal-oper IFF switch to position 3, switch to the "B" range scale, and adjust the range step as follows. Move the step in until the range counters read 40 miles, and adjust the horizontal centering control until this step falls exactly on the 4-mile range mark of the transparent range scale. Recheck to make sure there is a clear picture on the "A" scope.
If the screen of the "A" scope has no transparent range scale, adjust the horizontal centering control so that the time base falls at a convenient position on the scope.
Turning on PPI Scope
Snap the emergency train switch from the normal position to CW. Turn up the intensity control until there is a faint time base. Increase the video gain for a brighter picture, and adjust the focus control. Select any range desired for the PPI. If sector sweep is wanted, select the area desired and energize the sector sweep power by throwing the sector sweep switch (S-12) to the up position.
Miscellaneous adjustments
If lobe switching is to be used, turn the plate voltage control completely down (counterclockwise), turn the L.R. motor ON (either right or left), and wait one complete minute before again increasing the plate voltage. (This procedure should be followed except in emergencies when the plate voltage may be increased again after about 30 seconds delay.) Turn the lobing off switch to position 1 and adjust the lobe sep. control until the traces are separated suitably. While matching pips, read the bearing given by the white bug.
To make IFF adjustments, first turn on the IFF unit, and then switch the cal-oper-IFF switch to position 4. Adjust the IFF gain until a reasonable amount of grass appears below the time base, and then turn the cal-oper IFF switch back to position 3. Turn the cal-oper IFF switch to position 4 to challenge a target.
On the SA-2 a check on the pulsing rate can be made by putting the cal-oper IFF switch (S-5) in position 3 and the cal-synch switch (S-6) in position 2 and observing the picture on the 2-inch cathode ray tube. If the circle is broken, and a small neck protruding upward, the set is pulsing correctly. (Refer to fig. 4 SA-7.)
OPERATIONAL TECHNIQUES
Search procedures
The SA radars were designed primarily for long-range air search--an early warning of approaching aircraft. Its effectiveness depends not only on the material condition of the set, but also on the efficiency of the operator. The following search procedures are recommended for utilizing the SA radars to their maximum efficiency.
For normal tracking and search, the 80-mile range scales should be used. The operator should adjust the "A" scope for one half [inch] of grass so that echo signals of sufficient amplitude will reach the PPI scope. Watch the PPI for targets with an occasional search on the "A" scope. When a target first appears, report its presence in the following manner. On the first sweep, for example, report "contact 180, 45 miles." On the next sweep, throw the emergency antenna train switch to normal approximately 30° ahead of the reported bearing. This will allow the antenna to coast up to the correct bearing, and with a minimum of time, the operator can go to the "A" scope, challenge for IFF, and get the approximate composition of the contact. The operator should start the antenna rotating again and then finish his report. Example: "Contact is few bogeys, estimate 3 to 5 planes, closing." This procedure has been used very effectively. It enables the operator to search and also
4-SA-17
track many raids at once, with a minimum of time lost in challenging the various raids. Occasionally the operator can switch to the longer and shorter ranges on both scopes as a double check on any possible new contact that might appear. It is felt the above described system of operation should be the SA operator's basic search and tracking procedure.
In the event that the PPI unit fails, the following "A" scope search procedure is recommended. Adjust the "A" scope for one-fourth inch of grass, and use low-speed antenna rotation. When a signal is noticed,immediately stop the antenna and rotate it by hand until the echo pip is at is maximum height. Report the bearing from the orange bug, and read the range from the transparent scale on the scope, also challenging for IFF. Start the antenna rotating again and finish the report.
If a track on a reported plane is needed, the following procedure can be used. As the pip reaches a maximum height on the "A" scope, glance over quickly at the bearing dial and report the bearing indicated. This procedure, of course, will probably develop a bearing error, but with some practice, the operator's own time lag can be measured in degrees and deducted by him in his report. This system is known as reading target information "on the fly," and with practice can be developed efficiently. It should be remembered that it is desirable to keep the antenna rotating as much of the time as possible.
If there is reason to believe long range search of an area is needed, the "A" scope can be adjusted and the area searched manually by turning the antenna train knob. If continual long range search is desired, operate on low-speed antenna rotation. Bearings and ranges can be called in by using the "on the fly" method.
In searching over land it must be emphasized that target pips will be mixed with land pips. However, plane pips will bob up and down more rapidly than land pips; also the plane pips will move with respect to the land. The antenna should be operated manually, and a close watch kept on the receiver gain, so that when echoes from land masses become saturated, the gain can be reduced in order that the plane pip can be followed. The operator must remember to keep searching, taking only a minimum of time to check the planes over land. Use of the "Anti-Jam" controls facilitates, to some extent, tracking over land.
"Anti-Jam" Receiver
Essentially the "Anti-Jam" receiver provided for the SA and SA-2 radars is a superheterodyne receiver which contains special circuits to allow for its operation through various types of jamming or intentional interference.
The A-J receiver contains four controls designed expressly for the purpose of eliminating, or at least reducing, jamming. These four control are:
- Rej bal control.
- Rej control.
- Time const control
- Bal control.
Originally, the time const. control was called the AVC bal control, and the bal control was called vid bal control. In line with standard Navy nomenclature, the four controls will be discussed as named in the list above.
For normal operation the bal control should be in a clockwise position, the rej bal control counterclockwise, the rej control clockwise, and the time const. counterclockwise.
Briefly, the rej bal control and the rej control work together to eliminate an undesired signal from being passed through the receiver. They constitute a wave trap for a particular undesired signal if they are adjusted correctly. They are designed to be used chiefly against an interfering continuous wave signal.
The time const. control varies the speed of the automatic volume control of the receiver. This control acts so as to automatically cut down the strength of a large signal more than it cuts down a small signal coming into the receiver. The faster its action, the greater is its differentiation between strong and weak signals. Position three is fast AVC action, position two is medium AVC action, and position one is slow AVC action.
The bal control is designed chiefly to eliminate railings, or at least to keep them at no larger amplitude than the echo.
To use the A-J controls intelligently, it is first necessary to decide what type of signal is causing the jamming. This is done by interpreting the form of the pattern appearing on the "A" scope screen, which then serves as a guide for choosing a possible adjustment procedure for the interference eliminating controls. Supposedly the A-J controls are most effective against interference due
4-SA-18
to CW (Continuous wave) signals, frequency modulated signals, amplitude modulated signals, and pulse modulated signals (railings). However, irrespective of the type of interference, it will be impossible to obtain as good a pattern as during normal operation. The echo may be difficult to distinguish, but will probably appear as a stationary line or break through the more confused and generally moving interference background. Even with optimum setting of the anti-jam controls the pattern is seldom fully restored to its normal appearance, but it will be cleared up enough to permit effective echo observations to be made. The antijam controls are to be operated in the manner set forth below. It should be noted that the rej control, which is normally in the clockwise position, and rej bal control, which is in the "zero" position for normal reception, should be operated only if all other controls fail to reduce interference satisfactorily.
Indication of corrective adjustments for various types of interference is given below. It should be emphasized that in almost all cases, only practice will teach the operator how to best cope with the various cases encountered.
A. Unmodulated CW interferences.--This type of interference produces a more or less complete shrinkage of the height of the pattern, which may go so far as to reduce the entire pattern to a single horizontal trace when the gain control is set for normal operation. In order to counteract this effect, it is best to readjust the gain control and leave all other controls in their respective normal positions. Then adjust the rej and rej bal controls alternately and in small steps until improvement of the signal is noted. The three positions of the time const. switch should also be tried, and the best one selected.
B. Modulated interference.--Depending on the setting of the range sel switch, frequency or amplitude modulated interference causes the entire pattern either to wobble bodily or flutter up and down, or to assume the shape of a wavy line moving from right to left or left to right across the screen. Since the effectiveness of the various anti-jam controls will depend oto some extent on the modulation frequency of the interfering signal, these controls should be operated in a logical sequence, as described below:
1. With all controls in their normal positions, readjust the gain control until the signal is improved or restored.
2. If the adjustment of the gain control is not effective, place this control in its usual position for normal reception. Then adjust the rej and rej bal controls alternately and in small steps until improvement of the signal is obtained.
3. The next step is to see if adjustment of the gain control will improve the signal.
4. Finally, try the three positions of the time const. switch and select the one giving the most readable pattern. During the entire procedure, the bal control should be kept in its maximum counterclockwise position.
C. Railings (or pulsed) interference.--This type of interference generally causes a number of vertical lines to appear on the screen, superimposed on the normal pattern and extending high above the radar echo pip. To combat this type of interference, the operator should first try the procedure outlined under Modulated Interference. If this fails, he should proceed as follows:
Set the time const. switch to position 3 (fast AVC).
Turn the bal control clockwise to a point where the railings will be displaced toward the horizontal base line or even below this, while leaving the echo pips above this line.
Vary the gain control to obtain optimum operation.
Repeat steps (2) and (3) with the time const. switch in positions 2 and in position 1, and select the best setting combination.
D. Nonintentional interference.--In case of nonintentional interference, such as may be caused by communication or electrical equipment or by other radars, the [procedure described in varying the gain and time const. controls in the section on Unmodulated CW Interference will generally be found satisfactory.
4-SA-19
If the type of jamming cannot be determined, the operator's problem will still be one of intelligently experimenting with the controls so as to counteract the jamming most effectively. Experience is the best guarantee to success!
PERFORMANCE
TROUBLES
Troubles in the SA-2 system are essentially the same as those listed for the SA on page 4 SA-10.
Another frequent source of trouble is found in reduced sensitivity of the receiver tubes. Those which are the worst offenders are the first RF amplifier, V201, and the converter, V203.
4-SA-20
Part 4.
SL RADAR
4-SL-1
CONTROLS
Power) When the switch is snapped to the right, the antenna and the deflection coil (around the PPI) rotate et 18 rpm..
Figure 4 SL-1. Indicator panel.
4-SL-2
Adjustment controls. of the azimuth mark (indicates relative bearing of the antenna at 000°. when properly adjusted).
A-10. Range mark: controls the brightness of the range mark which should appear at the outer edge of the scope.
A-11. Retard: indicator, antenna: these push button controls permit setting the azimuth mark to any desired direction on the screen (to 000.
TURNING ON AND OFF
Turning on.
Check controls for normal positions:
- Rec. gain-CCW.
- Azimuth mark-CCW.
- Drive motor-off.
- High voltage switch-off.
- High voltage adjustment-full CCW.
Power adjustments:
Turn power switch ON. The dial lights should come on and a motor should begin whirring inside the modulator unit. The scale light control should be adjusted to suit the operator.
Adjust the line voltage adjustment until load voltage meter reads 115 volts..
Turn drive motor on and listen for grinding of gears.
4-SL-3
Turning off.
- Turn rec. gain fully CCW.
- Turn azimuth mark fully CW.
- Turn high voltage adjustment CCW.
- Turn off high voltage switch.
- Turn off drive motor.
- Turn power switch off.
CALIBRATION.
OPERATIONAL TECHNIQUE
Preliminary operational adjustments.
Turn the azimuth mark increase clockwise, and set the position of the azimuth mark by operating the retard- indicator, antenna. If relative bearings are wanted, set the azimuth mark to 000.
Tuning the receiver.
Set the range selector switch as follows:
If at sea, with no objects in the vicinity, or with objects within five miles, set on 5-mile scale.
If at sea, and the nearest object is beyond 5-mile range, but still within radar range, set on 25-mile scale.
When within 25 miles of land, use 25-mile scale.
Tune the receiver, adjusting for maximum brightness of the targets. The receiver gain should be adjusted while doing this to keep the brightness low. If no targets are visible, tuning may be done by adjusting rec. tune for maximum sea-return. In case the sea is very calm, and you can not even get a satisfactory echo from your own ship's wake, it is possible to tune the receiver approximately by watching the converter current. This method is to be used as a last resort when no echoes of any kind can be seen.,
4-SL-4
faint arc or spot, which recurs at the same spot for two or more successive rotations of the antenna. (Snow splotches will not repeatedly appear in the same place, while indications from targets will.) Every three minutes, reduce the gain and search for pips near the center. These might have been masked by the sea-return while the gain was high. Search in this way for about 30 seconds. try to read the ranges through the interference. Try various settings of gain control. There is a chance the jamming will stop long enough for you to get range.
Keep reporting its bearing periodically.
Be ready to turn on a radar which operates on a different frequency band if ordered, provided that you have one,
Draw a picture of the jamming pattern while it is fresh in your memory, and send it to the Bureau of Ships without delay.
PERFORMANCE
Maximum reliable range.
The higher the antenna, the greater the maximum range; for this reason, performance figures are given on the following page for several antenna heights.
4-SL-5
Minimum range.
The average minimum range for ship targets is about 500 yards (1/4 mile), and on aircraft targets about 700-1,000 yards. These figures will be somewhat higher when sea-return is strong.
Range accuracy.
The figures for the possible error of the set, plus the probable error of estimation are approximately:
Bearing accuracy.
Approximately ± 2° - 3°
TROUBLES this condition, but if that does not help, you should notify the technician.°.
4-SL-6
Part 4.
SL-1 RADAR
Figure 4 SL-3. Indicator panel and range unit.Figure 4 SL-3. Indicator panel and range unit.
CONTROLS
Power controls
P-1. Main power switch: Controls all power to the set (except heater power). The power is off when switch is snapped to the left.
P-2. Load voltage, set to 115-volt meter: Indicates the voltage applied to the set.
P-3. Load voltage control: Adjusts the voltage applied to the set. It should be adjusted so that load voltage meter (P-2) reads 115 volts.
P-4. High voltage: wait 60 sec: Switches on and off the high voltage. The right-hand switch is used to apply the high voltage; the left-hand switch to remove it. High voltage should not be applied to gear until 60 seconds after turning on main power switch (P-1).
P-5. Magnetron-Converter current meter: Indicates either the magnetron current or the converter current, depending on the position of magnetron-converter current switch (S-2).
P-6. Tube hours meter: An electric clock indicating the total number of hours the set has been in operation.
P-7. Drive motors switch: Controls power to the antenna drive motor and to the indicator motor which rotates the sweep synchronism with the antenna. When the switch is snapped to the
4-SL-7
right, the antenna and the deflection coils around the PPI rotate at 18 rpm.
Figure 4 SL-4. Indicator modulator assembly with range unit.
Selector Switches
S-1. Range select switch: A three position switch permitting use of one of the three range scales provided--4 miles, 20 miles, or 60 miles. In the 4-mile position, a 2 mile sweep is available when switch S-5 is in ON position.
S-2. Magnetron-converter current switch: Permits use of the same meter (P-5) to indicate either magnetron current or converter current.
S-3. IFF switch: Turns on the IFF interrogator.
S-4. Bearing switch: In TRU position, connects the gyro compass to the radar so that true bearings will be indicated, regardless of the changes in ship's heading. If relative bearings are desired (or necessary, due to failure of the gyro compass), this switch can be turned to REL position, disconnecting gyro compass.
S-5. This switch makes a 2 mile sweep available when range select switch (S-1) is in the 4 mile position.
S-6. Dial light switch (on range unit): Turns on and off the lamp which illuminates the range dial.
S-7. AFC switch: Controls AFC (automatic frequency control) circuit. In the ON position, the AFC circuit automatically keeps the receiver in tune, while in the OFF position the receiver must be tuned manually using the rec tune control (A-6).
S-8. Tell tale switch: Throws on and off the telltale mark on the PPI. With the bearing switch (S-4) in the TRU position, the mark shows own ship's course. With the bearing switch in REL position, the mark will be at 000 degrees.
S-9. Measure-calibrate switch: Determines whether the electronic range ring or the calibrating ring used in calibrating the Range Unit will appear on the PPI.
S-10. Remote bearing switch: Should be in the TRU position if true bearings are desired at a remote repeater, and in REL if relative bearings are desired.
Adjustment Controls
A-1. Intensity: A screwdriver adjustment controlling the overall brilliance of the trace on the PPI screen.
A-2. Focus control: A screwdriver adjustment used to bring the sweep into a sharp, clear line.
A-3 and A-4. H--centering--V: Screwdriver centering adjustments used to shift the complete picture to the right or left, up or down, respectively.
A-5. Rec gain; The volume control of the receiver. It controls the brightness of the echoes on the scope.
A-6. Rec tune: Permits manual tuning of the local oscillator in the receiver.
A-7. Dial light control: Permits adjustment of the brightness of the dial lights on the meters and behind the PPI cursor.
A-8. Bearing mark: Controls the brightness of the azimuth mark which flashes at 000 degrees relative when the antenna and the PPI sweep are synchronized.
A-9. Retard: indicator, antenna; Push button controls which permit setting the azimuth mark to any desired bearing on the screen (to 000 degrees when relative bearings are to be read, and to the ship's heading when reading true bearings). The indicator button stops the indicator trace while the antenna continues to rotate and, consequently, makes the azimuth mark move counterclockwise. The antenna button retards the antenna without stopping the indicator, and, hence, the azimuth mark moves clockwise.
A-10. IFF gain: Controls the strength of the IFF responses applied to the SL-1 scope.
4-SL-8
A-11. A screwdriver adjustment which controls calibration of the 2 miles sweep.
A-12. Range yards crank: Moves the range dial on the Range Unit as well as the electronic rang ring appearing on the PPI.
A-13. Range-calibrate control: Permits calibration of the Range Unit.
A-14. Intensity control: Varies the intensity of the electronic range ring on the PPI.
A-15. Bearing cursor: rotates the cursor mounted above the PPI scope.
TURNING ON AND OFF
Preliminary Checks
Before applying power, check the following:
1. Turn the rec. gain (A-5) counterclockwise.
2. Turn the drive motors switch (P-7) to OFF position.
3. See that the bearing switch(S-4) is in the proper position (TRU if gyro power is available).
4. Turn the switch (S-5) to OFF.
5. Turn the dial light (S-6) to ON.
6. Turn the AFC switch (S-7) to ON.
7. Turn the telltale switch (S-8) to ON.
Turning On
1. Turn the main power switch (P-1) to ON position.
2. Wait one minute after turning the main power (P-1) to ON before operating the high voltage switch (P-4) momentarily and releasing it.
3. During the one minute wait:
Switch the range select (S-1) to the proper setting for initial adjustment (20-mile scale at sea, 4-mile scale in port).
Adjust the load voltage control (P-3) so that load voltage meter (P-2) reads 115 volts.
Rotate the bearing cursor (A-15) handwheel until the range of the first inscribed range circle on the cursor is read on the range dial (in preparation for centering).
4. After the one minute delay, turn the high voltage switch (P-4) to the ON position momentarily. A relay will operate and high voltage will be applied to the modulator. A 800-cycle tone will be heard.
5. Check the reading of the magnetron-converter current meter (P-5). If the magnetron current does not show between 16 and 21 ma., notify the technician.
6. Again adjust the load voltage control (P-3) for 1155 voltes on meter (P-2).
7. Turn the drive motors switch (P-7) to the ON position.
Initial Adjustment
1. Adjust the intensity screwdriver control (A-1) so that sweep is just visible on the PPI.
2. Adjust the range ring intensity and the focus (screwdriver controls A-14 and A-2) to give best appearance of the electronic range ring on scope.
3. Turn the H and V center control (A-3 and A-4) until the sweep is accurately centered by making the range ring coincide with the first inscribed range circle on the cursor, or by placing the small circle at the inner end of the sweep in the center of the screen.
Adjust the rec. gain (A-5) until some "snow": appears on the scope.
5. Turn the IFF gain (A-10) full clockwise. this can later be adjusted to suit the operator.
Synchronizing the Antenna and Deflection Coil Motors
1. Turn the bearing mark control (A-8) toward INCREASE until the azimuth and telltale marks are visible on the PPI. The telltale switch (S-8) should be in the ON position.
2. With the bearing switch (S-4) in the TRU position, check to see that the telltale mark on the scope indicates own ship's course.
3. Operate the retard: indicator, antenna push buttons (A-9) as required until the azimuth mark and telltale mark coincide to form a single radial line.
4. Adjust the bearing mark control (A-8) until the coincident telltale and azimuth marks are just visible.
Turning Off
1. Turn the rec. gain (A-5) counterclockwise.
2. Throw the drive motors switch (P-7) to the OFF position.
3. Operate the left-hand high voltage switch (P-4) momentarily and then release it. This will remove the high voltage from the modulator.
4. Turn the main power switch (P-1) to the OFF position.
CALIBRATION
The following procedure is used to adjust the zero setting of the range unit. The sweep speed will not be adjusted by the operator.
4-SL-9
1. Operate the range select switch (S-1) to the 4-mile scale.
2. Turn the range yards crank (A-12) until the range dial reads 400 yards (unless the notice on the range dial window reads "CALIBRATE AT 500 YARDS", in which case adjust the crank for 500 yards).
3. Operate the measure-calibrate switch (S-9) alternately to the MEASURE and CALIBRATE positions. If there is no change in the radius of the electronic range ring, the zero setting of the range unit is correct.
4. If a change in radius of the ring is noted, loosing the locking nut under the range-calibrate control (A-13), and adjust this control until no change of radius is obtained when measure-calibrate (S-9) is switched from one position to the other.
5. Lock the rang-calibrate control (A-13) by tightening the locking nut under the knob. The range unit has now been calibrated.
6. Throw switch (S-5) to the ON position.
7. Turn the range yards cranks (A-12) until the range dial reads 2,000 yards.
8. Adjust the screwdriver control (A-11) until the electronic range ring lies directly under the second inscribed marker on the cursor. The 2-mile sweep is now calibrated.
OPERATIONAL TECHNIQUES
Tuning the Receiver
1. Set the range select switch (S-1) as follows:
If at sea, with no targets in the vicinity, or with targets within 4 miles, set on the 4-mile scale.
If at sea, and the nearest target is beyond 4 miles, but within radar range, set on the 20-mile scale.
When within 20 miles of land, use the 20-miles scale.
2. Turn the AFC switch (S-7) to the OFF position.
3. Adjust the rec. tune control (A-6) for maximum brilliance of targets. The rec. gain (A-5) should then be adjusted while doing this to keep the intensity low in order to prevent the screen from becoming damaged by too bright a spot. If no targets are available, tune for maximum sea return. If the sea return is not strong enough, operate the magnetron-converter current switch (S-2) to the converter position and adjust the rec. tune (A-6) for maximum current reading on the megnetron-converter meter (P-5). This last method will only give fair results, and should be used as a last resort.
4. Observe the scope with the AFC switch (S-7) turned to its OFF and ON positions alternately. (This should be done only after the gear has been in operation for over 15 minutes to allow time for the AFC circuit to warm up sufficiently.)
5. If echoes are stronger with the AFC switch (S-7) turned OFF, the AFC circuit requires readjustment by the technician, and the switch should be left in the OFF position. If there is no change in strength of echoes as the switch is thrown from one position to the other, operate with the AFC switch (S-7) in ON position.
6. Operate the magnetron-converter switch (S-2) to the Converter position and check the reading of magnetron-converter current meter (P-5). If should read between 5 and 10 scale divisions (0.5 to 1.0 ma.).
7. Adjust the rec. gain (A-5) for noticeable "snow" on scope. Note that the tuning of the SL-1 should be checked once every watch regardless of whether the AFC switch (S-7) is in the ON or OFF position.
Recommended Operation
When relieving the watch, the operator should check the following: Intensity, focus, centering of trace, azimuth and telltale mark alignment, calibration, tuning, and meter readings. Tuning should not be attempted unless targets are available or sea return is present. Check to see if the AFC circuit is operating properly by comparing echoes on the scope with the AFC switch in the ON and OFF positions.
Search Procedure: Use the 20-mile scale primarily, with a normal amount of gain--not too bright to obscure indications nor too low to prevent small echoes from appearing on the scope. Search for 3 minutes on the 20-mile scale, 1 minute on the 60-mile scale, and 1 minute on the 4-mile scale. During the 4-mile search, check the 2-mile sweep for three or four revolutions of the antenna. The gain setting must be changed slightly when switching from one scale to another; it should always be lowered when switching to the 4-mile scale. It is possible to detect such small contacts as PT boats and submarines on the 2- and 4-mile sweeps.
4-SL-10
Station Keeping: IF radar information is needed for station keeping, the 4-mile scale should be used unless operating with a large convoy where the guide ship is more than 4 miles distant. When using the 4-mile scale, the gain should be reduced sufficiently to show ships in formation clearly and to cut out the effect of side lobes.
Clouds: Echoes from clouds are very common on the radar screen. Operators can usually recognize clouds by their hazy and distorted appearance. However, on the 60-mile scale especially, clouds may appear as sharp and well-defined echoes and can be mistaken for ship contacts. The operator should report all contacts, even if he is sure that they are clouds, giving all the information he can.
Jamming
See page 4-SL-5.
TROUBLES
See page 4-SL-6.
PERFORMANCE
Maximum Reliable Ranges
The higher the antenna, the greater the maximum range; for this reason, performance figures are given below for several antenna heights.
Submarine Contacts: See pages 4-SL-4 and 4-SL-5.
Surface Contacts: When a surface contact is first detected, it should be challenged for IFF and reported as either "skunk" or "friendly" together with information as to bearing, range, and composition. Composition is determined by the size and number of indications, and by the range at which the contact si first picked up. After the initial contact report is made, the recorder will give a 5-second "stand-by" and "mark" every minute (unless the 60-mile scale is being used when "marks" will be given every 2 minutes). Ranges will be determined by aligning thew electronic range ring with the inner edge of the indication, unless ranges are greater than 20 miles, in which case they must be estimated using the inscribed circles on the cursor as a guide. If two or more targets are being tracked, they should be reported in order after each "mark." In each report, the operator will give the destination of the contact, the bearing, range, and additional information on target movement (opening, closing, crossing, holding).
If the target is beyond 4 miles but inside 20 miles, normal search routine should be followed. If the operator is searching on a different scale when the "stand-by" is called, he must switch scales and report the contact as soon as possible after the "mark."
If the target is within a range of 4 miles, search should be performed primarily on the 4-mile scale, switching to the 20-mile and 60-mile scales for 30 seconds each, every 3 minutes. Possibility of the appearance of other contacts must not be overlooked.
If the target is first detected at a range greater than 20 miles, the 60-mile scale should be used primarily until the target has closed to within 20 miles. Search fo 3 minutes on the 60-mile scale, then switch to the 20-mile and 4-mile scales for 30 seconds each. The recorder should call "stand-by" followed by "mark" every 2 minutes while the 60-mile scale is in use.
Characteristics
Pulse repetition frequency--800 p.p.s.
Pulse length--1.25 microseconds.
Beam width--
Horizontal: 6 degrees.Minimum range--300 yards.
Vertical: 12 degrees.
Range accuracy--
4-mile scale ±100 yards.Bearing accuracy ±1 degree.
20-mile scale ± 200 yards.
60-mile scale ±1,000 yards.
Range resolution--400 yards.
Bearing resolution--5 degrees.
4-SL-11
Part 4.
SO RADAR
4-SO-1
CONTROLS.
Pilot: adjusts the illumination of the bearing scale around the PPI tube (9).
Start stop: controls the application of high voltage to the transmitter. (Do not confuse this with the bulkhead start stop switch used with SO-1, SO-2, SO-8.)
Humidity indicator: when this becomes pink, the technician knows that the dehydrators are saturated with moisture.
S W L: a screw driver control of sweep length. Sweep length may be varied to show a minimum of three range circles, and a maximum of six range circles..
INT: this is the PPT intensity control for adjusting the brightness of the sweep and the range circles.
The PPI (plan position indicator) tube.
The Cursor: by means of this the relative bearings of contacts are read.
CCW off CW: this is the antenna rotation toggle switch. When in the CCW position the antenna goes counterclockwise automatically at 12 rpm. In the CW position it goes clockwise at 12 rpm. There is no provision for manual rotation.
Focus: used to focus the PPI tube for maximum definition.
Center: this control positions the start of the sweep. The sweep can be made to start from
Figure 4 SO-1. Plan position indicator unit.
4-SO-2
the center of the PPI, or may be offset from the center as much as a half-inch. This leaves a dark circle in the PPI center which indicates our own ship's position. All contacts move out from the center when the sweep is offset, and it is easier to get bearings of near-by targets. The, calibration of the set is not changed in any way by this control. Normally, there will be a small dark circle about 1/16-inch in diameter at the PPI center.
Tune: this is the fine tuning adjustment. When it is adjusted for maximum echo brightness, the receiver will be tuned to the transmitter.
Marks: controls the intensity of the range marking circles on the PPI.
Gain: corresponds to the volume control on any radio receiver, it controls the sensitivity of the receiver.
Tune set: a rough tuning adjustment. It tunes the receiver approximately to the transmitter. It is adjusted for maximum echo, while the tune control (14) is in the mid-position. This is a semi-permanent adjustment.
Bulkhead stop start switch, used with SO-1, SO-2, SO-8.
TURNING ON AND OFF
Turning on.
Operate NE switch (2) to N. marks counterclockwise, pilot counterclockwise.
Be sure INT (8) is turned full counterclockwise; this is done to prevent burning on PPI.
Turn off-on switch (1) to ON if an SO. Press start button (18) on SO-1; dial light will come on when turned up.
The blower in the transmitter will be heard to start.
After two or three minutes, press start button (4), a relay will be heard to click, and the 400-cycle hum will be distinguished.
Turn INT (8) clockwise until the trace on the PPI can be seen with moderate intensity. It is possible to burn the PPI if the trace intensity is too high.
Adjust focus (12) for sharpness of sweep trace on PPT.
Operate CCW off CW switch (ii) to either CCW or CW, and the trace will rotate on the PPI at 12 rpm automatically.
Set the range switch (7) to the range on which contacts are most likely to be seen. If there are no ship or land targets within radar range, set this switch to short range so that sea-echoes or sea-return may be used for tuning.
Turn gain (16) completely clockwise.
Adjust tune (14) until contacts or sea-return (echoes from waves nearing your ship) can be seen on the PPI indicator..
With switch 11, start the antenna in automatic rotation again in either direction..
Turn marks clockwise until range-mark circles appear on the PPI, and adjust SW-L (16) until 5 range circles show on the SO, or 4 range circles on the SO-1.
Note that no calibration is necessary. The set is permanently calibrated at the factory.
Turning off.
Operate CCW off CW switch to OFF.
Turn INT (PPI intensity control, 8) completely counterclockwise.
Turn marks (15) completely counterclockwise.
Turn pilot (3) completely counterclockwise.
Push stop switch :
Put the operate lever in a horizontal position. (See illustration of echo box, fig. 4 SO-1.)
With the radar operating, stop the antenna on the bearing of the echo box pick-up antenna; this will be either 000°, or 180°,
4-SO-3
depending upon the type of set you have. Adjust the echo box for the brightest indication from the neon bulb. The glowing of the light indicates that the transmitter is functioning..
To detune the echo box when not in use, pull the operate lever into a vertical position.
OPERATIONAL TECHNIQUE½ between a contact and its background, and the weakest contacts are seen best in complete darkness. ±2° or ±3
4-SO-4
keeping. The range selector switch (7) will be on short scale, and the gain control (16) will be turned down (counterclockwise) just enough to rid the PPI of excessive sea-return. Sea-return means echoes from waves near your ship, which causes interference from 3/4 miles to one mile in all directions, in even a moderate sea. With gain reduced, close range detection is now possible down to 200 yards, although the detection sensitivity at longer ranges will be lessened. If a contact is made at close range, it will be seen so close to the center of the PPI that it may be hard to get its bearing with normal accuracy. To facilitate getting a bearing on such a target, de-center the PPI trace by turning center (13) clockwise. The origin of the trace has now moved away from the PPI center, and the contact has moved out a corresponding distance. Its bearing can now be read more accurately. To facilitate station keeping, a dot may be put on the PPI where the guide should be, then when you get off station, the guide's contact will move out from under the spot. target to be seen on a wrong bearing; rarely visible, except when many ships are traveling together. These contacts are often distorted, and not as well defined as the usual contact. Their appearance and disappearance is usually related to course changes.° or more in width in a typical
4-SO-5
case (SO-1 radar). If two targets have the same range, but differ in bearing by no more than 15°, they will merge into one contact on the scope. bearing is changing fast use CCW off CW switch, as described previously in the section titled "Reading Bearings.".
4-SO-6
When you are approaching an unfamiliar shore, it is well to study charts and topographical data, and try to predict the way it will appear on the PPI, keeping in mind your approach course. This will facilitate an early radar fix and confusion will he avoided. trying to read ranges through the interference. Try various settings of gain control (16). There is a chance the jamming will stop long enough for you to get range.
Keep reporting its bearing periodically.
Be ready to turn on a radar which operates on a different frequency band if ordered, providing you have one.
Draw a picture of the jamming pattern while it is fresh in your memory, and send it to the Bureau of Ships without delay.
PERFORMANCE
Maximum reliable range.
Minimum range.
Range accuracy.
The possible errors of the set may add to the probable errors of estimation, so that the following figures result for contacts that are not exactly on a range circle.
Bearing accuracy.
± 2° for SO, SO-A, SO-1, SO-2, SO-8, provided your own ship is not yawing on its course.
TROUBLES
Reports from forces afloat indicate operational difficulties caused by moisture getting into the equipment. The transmitter-receiver, and PPI unit of the SO series radars are mounted in watertight cases, and sylica
4-SO-7
gel dehydrators (protek plugs) are provided to keep the units dry inside. A few reports have stated that condensation appeared on the scope after the equipment had operated for a few hours, but disappeared after the unit was shut down and allowed to cool. This is an indication that the heat generated by the equipment has driven the moisture out of the dehydrator plugs.
The instruction hook requests that the dehydrator plugs he changed when they have turned from deep blue when dry, to light pink after they have absorbed moisture, and are near saturation. Replacement plugs are sealed at the perforated end to prevent saturation; be sure to remove the seals before inserting in the units..
4-SO-8
Part 4
SF RADAR
4-SF-1
CONTROLS
"A" indicator: used to identify targets at extreme ranges, for studying composition of echoes, and for accurate ranges.
Range scale: read the one that is illuminated.
PPI indicator: used to show tactical situations, for station keeping, and the most watched "scope" during general search. It is surrounded by a relative bearing scale.
Range knob: moves the range step on the "A" scope, and the range circle on the PPI scope when getting range.
Cal synch: a semi-permanent adjustment made by the technician.
"A" scope intensity: controls the brightness of the picture.
"A" scope focus: controls the clarity or sharpness of definition of the "A" scope picture.
16,000-yard set: used in calibrating 16,000-yard range, and to put the first range mark on the step; the first range mark represents 2,000 yards.
16,000-yard range set: used in calibrating the 16,000-yard range, and to put the seventh range mark on the step.
48,000-yard range set: used in calibrating the 48,000-yard range, and to put the 20th range mark on the step.
48,000-yard zero set: used in calibrating the 48,000-yard range, and to put the first range mark on the step; first range mark represents 2,000 yards.
PPI focus: controls the clarity or sharpness of definition of the PPI scope picture.
PPI intensity: controls the brightness of the picture on the PPI indicator.
Calibrate-operate switch: when in calibrate position, range marks appear on the two scopes for
Figure 4 SF-1. Indicator unit.
4-SF-2
use in calibration. When in operate position, grass and target echoes appear on the two scopes. 15. Dial light control: illuminates the PPI bearing scale. This is to be used only when a bearing is being read.
Green tuning eye: intended to be a tuning aid, but its use is not recommended.
Rec-gain control: adjusts the sensitivity of the receiver; it controls the height of the echoes and the grass.
Stop-start buttons: for turning set off and on.
Range switch: selects either the 16,000-yard or 48,000-yard scale,
Figure 4 SF-2. Transmitter unit.
Lo-tunning: this tunes the receiver to the transmitter; it is adjusted to give maximum pip height. This is an extremely critical adjustment, and the one on which the ability of the set to detect targets chiefly depends.
IFF gain: to be turned clockwise when interrogating with identification equipment. This is inoperative unless BL or its equivalent is used in conjunction with the SF radar.
Warning-training error: a light which indicates that the antenna (and consequently the target) is not on the indicated bearing. When lighted, it tells us that the antenna training equipment is out of commission and bearings will be wrong until repairs are made.
Antenna train control: when pushed in, the antenna can be trained by hand; when pulled out, the antenna will rotate automatically.
IFF on-off switch: when BL or its equivalent is connected to the SF radar, this switch is used to interrogate a desired contact.
TURNING ON AND OFF
Turning on.
Assuming ship's power is on and adjusted to 115 volts DC:
Press the black start button (18), on the receiver-indicator. In about 30 seconds, the pilot lamps will illuminate the range scale (2). See that PPI intensity (13) is counterclockwise.
Be sure the training control (23) is pushed in for manual operation.
After two and one-half to three minutes, the transmitter will automatically go into operation. If you are close to it you can hear the blower motors go on at this time.
Look at the meter on the transmitter unit. Set the toggle switch near the meter to MAG and the current should be five to six milliamperes.
Set the same toggle on CRYSTAL, and the meter should read between 0.2 and 0.6 milliamperes, if not, the lo-tuning (20) is probably off adjustment. (This is to be discussed later.) Full scale deflection represents 1.0 milliampere.
Turning off.
Push the red button marked stop (18 on the receiver-indicator unit).
Turn PPI intensity (13) down (counterclockwise).
Push in the training control (23) to manual the operation position.
CALIBRATION
16,000-yard scale (at the receiver-indicator unit)
Throw calibrate-operate (14) toggle on the receiver-indicator unit to CALIBRATE position.
Turn PPI (plan position indicator) intensity control (13) located near the right-hand indicator down to secure PPI during calibration. This prevents burning of its florescent screen during a prolonged period of calibration.
Adjust intensity of the "A" scope trace with the "A" scope intensity control (6), located under the left-hand indicator. Do not make it unnecessarily bright.
Adjust the focus knob, located under the left-hand indicator, until the "A" scope trace is sharp and clear.
Set the 16,000-48,000-yard range selector switch (19), located on the lower left side of the center to the 16,000-yard scale.
4-SF-3
Set range dial (2), upper center, carefully to 1.75 on the bottom scale (1,750 yards)..
Now set the range dial to read 13.75 on the lower scale (13,750 yards). together. They still represent 2,000-yard intervals.
Figure 4 SF-5. Pattern far calibrating 2,000-yard range an 48,000-yard scale.
Set the range knob (4) to read 1.75 (1,750 yards) on the upper scale (2). Adjust the 48,000-yard zero set (11) to put the first range mark on the edge of the step. See figure 4 SF.
OPERATIONAL TECHNIQUE
Receiver-indicator adjustments.
Throw the calibrate-operate toggle (14) to OPERATE.
Turn up rec-gain (17), located in the lower-left-hand corner, until grass appearing on the sweep (25) is about 1/8-to-1/4-inch high. It will look like figure 4 SF-7.
Figure 4 SF-7. Normal grass height.
4-SF-4
of lo-tuning (20) which make echoes peak up. use the setting which makes them the highest. Do not try to tune by the green tuning eye (16).
Figure 4 SF-8. Tuning for maximum echo.
Targets may be found now by training antenna with the train wheel (23), (located under the right-hand PPI indicator). Train on a ship or land target if possible.
Make the final adjustment of lo-tuning (20), by tuning for maximum height of the target pip.
Adjust the PPI intensity knob (13), located under the PPI indicator, so that the trace is just visible on the PPI with rec-gain (17) at minimum, turn completely counterclockwise.
Adjust the focus knob (12), located under the PPI indicator, for a clearly defined sweep.
Pull out on the antenna training knob (23), and the antenna will rotate automatically.
Adjust the rec-gain (17) for the best picture while watching the PPI. About 4-inch of grass is best if the PPI is to be watched. The PPI is now in operation.
Reading bearings. magnetic fields always being present, the trace will not line up with the bug (pointer) at all points around the dial. Therefore, bearing readings should always be made from the bug rather than the trace. If true bearings are desired, it will be necessary to install a gyro-repeater near the operator, unless the true bearing modification has been made on your set. Always read bearing in three figures, zero zero five instead of 5 degrees. To read bearings in the dark turn tip the dial light intensity knob in the center of the panel..
4-SF-5
Notice that the range circle on the PPI, and the range step in the "A" scope move in unison and always indicate the same range, which may be read on the illuminated range dial. evaluator, as the case may be, to give assurance that lie is alert, and that he can be relied upon at night for instance, when the watch officer can see nothing, and the operator is likely to become drowsy. If a report is made to the OOD by way of a bridge talker, the latter should give his report in such a way that the radar operator may listen and sing out if an error is made,° to 3
4-SF-6
operator should learn how to recognize these countermeasures, and. The two general methods of using the gain control are:
Reduce the setting; this prevents overload of the radar receiver; echoes are visible "riding on top" of the jamming pattern.°.
* See part 3, Defense Against Jamming and Deception.
4-SF-7
PERFORMANCE
Maximum reliable range..
Minimum range.
The minimum range with all controls adjusted for shortest range detection will vary somewhat, depending on the roughness of the sea. A rough sea, means more sea-return interference and greater minimum range, especially on smaller targets. The figures below show approximately what to expect:
Minimum range.
The minimum range with all controls adjusted for shortest range detection will vary somewhat, depending on the roughness of the sea. A rough sea, means more sea-return interference and greater minimum range, especially on smaller targets. The figures below show approximately what to expect:
Range accuracy.Range accuracy.
The range accuracy of this radar will be best when the ranges are read from the "A" scope using the step. The accuracy under these conditions is about ±200.
Bearing accuracy will he best when the contact is strong and steady. By using manual antenna train, that is, stopping the sweep in the center of the contact seen on the PPI, a good operator will usually be within ±2° of the correct bearing of such a target. If the contact is E-1*, and visible only periodically the error may rise to 3 degrees or 4 degrees.
TROUBLES.
* See Part 1, How Does Radar Determine Bearing--E Units.
4-SF-8
Part 4. SJ-a, SJ-1 Radar
4-SJ-1
CONTROLS
Main control unit.
Main off and on switch: applies AC voltage to the SJ radar set.
Green light: when illuminated this indicates the main switch is on.
Load voltage meter: indicates the voltage applied to the radar set.
Load autotransformer: controls the voltage reading of 3.
Regulated rectifier voltage meter: indicates the DC voltage output of the regulated rectifiers.
Meter switch: positions 1 and 2, determines which regulated rectifier voltage is indicated on 5.
High voltage rectifier off-on switch.
Red light: indicates when the AC power is applied to the high voltage variac.
Figure 4 SJ-1. Main control unit.
High voltage variac: controls the DC output of the high voltage rectifier.
High voltage rectifier voltmeter: indicates the DC voltage applied to the transmitter-receiver unit.
High voltage rectifier current meter: indicates the current in the rectifier circuit.
Antenna control on-off switch: controls the applied to the automatic training device.
Heater switch on-off: controls the AC plied to the heating elements in the range and transmitter-receiver unit.
Pilot lights: bright-dim switch.
Transmitter-receiver unit.
Figure 4 SJ-2. Transmitter-receiver unit.
Crystal current meter: reads 0.5 to 0.7 milliamperes when the equipment is properly tuned (this, however, is not the maximum crystal current reading obtainable).
Fine pulse rate control: will vary the pulse repetition rate from 1,300 to 1,700 pulses per second.
A.F.C. on-off switch: the automatic frequency control (automatic tuning circuit) will tune the receiver when ON, however, this circuit drifts and should be used only to check manual tuning.
Wave-guide transmission line to antenna.
Range-indicator unit.
Horizontal centering control: controls the position of the sweep or picture on the scope.
4-SJ-2
Lobe separation on-off: allows separation of pip, on the scope for lobe switching.
Lobe separation: determines the amount of separation of the pips when 2 is on.
Sweep control: determines the length of sweep on the scope.
- Main sweep: 0 to 60,000 yards.
- Expanded sweep: 0 to 20,000 yards.
- Precision sweep: 3,000 yards (1,500 yards each side of the range step).
Figure 4 SJ-3. Range-indicator unit.
IF gain: controls output of the receiver (determines height of grass and pips).
Focus control.
Lobe motor on-off switch: applies power to the lobing motor.
Intensity control: screwdriver adjustment, to be set by the technician.
Range zero knob: used to zero the sweep.
Receiver-tuning: tunes the receiver to the transmitter frequency.
Noise suppression: screwdriver adjustment, to be set by the technician.
Scope: cathode-ray tube.
PPI-indicator unit.
PPI cathode-ray tube.
Sweep selector switch: (8,000, 40,000, 80,000 yards range).
Scale light: azimuth circle.
Driving cable.
Video gain: screwdriver adjustment.
Focus: screwdriver adjustment.
Horizontal centering: screwdriver adjustment.
Vertical centering: screwdriver adjustment.
Range circle: adjusts intensity of the range dot.
Intensity: adjusts brilliance of the scope.
Figure 4 SJ-4. PPI unit.
Range unit.
Dial light dimming switch.
Heating circuit indicator lamp.
Range counter dial.
Zero adjustment: to be adjusted by the technician.
Counter adjustment: to he adjusted by the technician.
Clutch adjustment: to be adjusted by the technician.
Range crank.
Figure 4 SJ-5. Range unit.
4-SJ-3
TURNING ON AND OFF
Turning on.
Open antenna wave guide valve and perform the following operations from the main control unit:
Turn on heater switch (13) 30 minutes before attempting to operate, if at sea, leave heater switch on at all times.
Turn on main switch (1), a green light will glow if set is operating correctly.
Check to see if blower motors can be heard in the transmitter-receiver unit, If not, turn the main switch off and call the technician.
Check the load voltage meter (3) for 120 volt reading. If this is not indicated, make adjustment of load variac control (4) for 120 volts.
Check regulated rectifier voltage meter (5) for 300 volts, check both positions of switch 6. If either one is off more than 15 volts, call the technician..
The high voltage rectifier current meter (11) should read between 140 and 160 milliamperes.
Check the load voltage meter (3) again, for a value of 120 volts.
Turn on antenna control switch (12).
Turning off.
Turn off antenna control switch (12).
Turn off high voltage switch (7), do not reduce high voltage variac (9).
Turn off load voltage switch (1).
Do not turn off the heater switch (13) unless the set is to be worked on. Other units need not be touched.
CALIBRATION the paper and because the scale of the chart is too small. The range of a reference target, to be used for calibrating purposes, should be known within 5 yards..
Turn on the set and tune properly.
4-SJ-4
At range unit, turn range crank counter-clockwise until range dials read exactly 99,940 yards, or a more accurately determined figure found by double range echoes.
Turn IF gain fully clockwise (5 on range indicator unit).
Set sweep selector switch on precision sweep (4 on range indicator unit).).
Check sweep switch (4) on all three positions to see if a sweep and step are present on the scope for each position. If any are missing, notify the technician.
Turn IF gain (5) fully counterclockwise; and adjust focus (6) for narrowest sweep or line possible.
With sweep switch (4) on expanded, rotate IF gain fully clockwise.
Adjust receiver tuning control (10) for maximum pip height on scope if pip is present. AFC switch (3) on transmitter-receiver unit must be off during this adjustment.
If pip height is saturated (pip has a flat top and not a sharp point), reduce IF gain (5) until pip is pointed, and make further adjustment of receiver tuning control (10) for maximum pip height. false echo on the scope. The receiver can he reliably tuned on such an echo, as soon as the antenna is above the water..
Adjust wave guide valve for maximum tuning or echo height.° searches, reporting the results of each search. These searches should he made on expanded sweep. Continue to search with hand train of the antenna until surfacing is complete.
Reading bearing and range.
To obtain approximate bearing of the target, rotate the antenna crank back and forth (lobing
4-SJ-5
off), until maximum height of the pip is found. Read the bearing on the bearing indicator and subtract 2½° from this reading. The result will be an approximate or non-lobing bearing.
When an accurate bearing of the target is desired:
Turn the lobe motor switch (7) on the range indicator unit on.
Turn on the lobe separation knob (2) on the range indicator.
Rotate lobe separation knob (3) clockwise, until two pips and two steps are present, as illustrated in figure 4 SJ-7.
Figure 4 SJ-7. Scope with and without lobing.
Rotate antenna crank back and forth until the two echoes are at the same height.
Read bearing dial for correct bearing of the target with respect to own ship-relative bearing.
To measure the range, first turn lobing switch (7) off; then rotate the range crank, which moves the step on the scope, until the step is approximately at the pip being measured.
Turn sweep switch to precision sweep.
Advance the step until the beginning of the pip sets exactly in the corner of the step as in figure 4 SJ-8.
Figure 4 SJ-8. Position for correct ranging. touched. Minimum time will then he required for obtaining lobe bearings.°, and target speed within 3 knots from this data. The following suggestions will speed the obtaining of data from the PPI and increase the accuracy:
Add inked circles on the face of the PH tube for estimating range (four solid circles, interspaced by four dotted circles). Care must he taken not to scratch the tube in any way.
Improvise a more accurate 360
4-SJ-6
make the latter effect negligible, but at the same time reduce long range sensitivity.
The following search routine is suggested for SJ-a and SJ-1 equipment: 360° searches are to be made at all times; suggested antenna speeds are 6 rpm, or less, for PPI search, and 1/2 rpm for "A" scope search.
Use the PPI 80,000-yard scale (high gain) for 2 minutes.
Use the PPI 40,000-yard scale (high gain) for 5 minutes.:
Designate multiple targets on the PPI as Able, Baker, Charlie, etc.; escorts as escort one, escort two, etc.
Have the plotting officer look at the disposition of the targets on the PPI when approach begins. He may assign designations.
Keep the antenna in hand training while obtaining bearings for TDC.
Obtain data for the TDC by use of the "A" scope.
The best estimates possible of target size and type must be passed to the plotting officer and to TDC, as well as apparent changes in the course of target. These generally become widest due to changes in the echo strength on the PPI and "A" scope.. It suggested that operation of the SJ-a underway, be carried on with half-hour watches, if possible. In no ease, should the watches be for more than one hour. Radar watches may be combined with sound, radio, or both, but should under no circumstance be combined with lookout watches. When relieving the watch, all meters should be checked for proper readings, and the three indicator sweeps checked for proper operation. Tuning and zero-set should be checked, and special information, such as maximum range on wave pips, interference present, etc., should be obtained from the operator. Any indication of trouble should be reported to the radar technician or radar officer. In case trouble occurs in the set during the watch, immediately turn off the high voltage in the transmitter' and secure the set, reporting the sequence of events which occurred when operation failed. Location of trouble may be greatly speeded in this way.bing motion, and in some cases the speed. The first two factors will be affected by the following:
- Target size.
- Sea condition.
4-SJ-7
- Target type (amount of freeboard, lines, superstructures, etc.)
- Target course (presentment).
- Target speed (variation of reflecting surfaces).
- Own speed (variation of our antenna pattern).. Where uncertainty exists, as to whether a particular signal is real or a minor lobe echo, positive check can be made by attempting to lobe-switch on the echo in question. It will be found, that the two pips from a minor lobe echo will tend to rise and fall together, instead of sea-sawing, as a main echo does when the antenna is trained through the bearing of the target.
Jamming.
4-SJ-8
voltage applied to the transmitter, and retuning the receiver may° bearing when not in use, especially while running on the surface.
PERFORMANCE
Maximum reliable range.
The range capability of a given installation is effected mainly by the following conditions:
General condition of the radar.
Accuracy of the tuning, particularly the rec-tuning control.
Height of the antenna above the water.
Size and height of the target, also, material of the target..
Minimum range.
4-SJ-9
Accuracy.° on large steady pips. Range approximately, ± 25 yards, + .1% of the indicated range.
Resolution.
Bearing: 5 degrees.
Range: 40 yards.
TROUBLES
There are two factors which can cause had bearing readings (other than minor lobe and extended close-in echoes as described previously). These are changes in the transmitter frequency and obstruction, or distortion, of the antenna pattern by periscopes or the SD radar mast. The bearing indicator alignment can be thrown off up to 2 degrees by changes in the frequency, due to shifted tuning of the antenna or internal transmitter adjustments, or by replacement of the magnetron. Whenever any of these troubles occur, bearings should he checked against one or both periscopes. During this check care should be taken that the antenna is not pointing within 30 degrees of the periscope to avoid distortion of the pattern. Presence of a periscope or the SD mast within 30 degrees of the antenna beam can cause varying hearing errors up to some 5 degrees..
4-SJ-10
Part 4
SD RADAR
4-SD-1
CONTROLS
Receiver-indicator.
Focus control: controls focus of the sweep.
Intensity control: controls brightness of the sweep.
Markers: allow markers to be put on the scope. Used for obtaining ranges of targets; use of IFF in extreme right position.
Centering: controls position of the sweep on scope-horizontal positioning.
Stand-by light: when illuminated indicates power switch is on.
Power switch on-off: controls AC power applied to the set.
Transmitter plate light (red): when illuminated indicates switch, No. 14, is on.
Oscillator control: tunes the receiver to the transmitter frequency.
Sensitivity control: volume control of the receiver, controls height of the grass and pips.
Fuse F-202-Fuse F-201: protection for the AC supply.
Scope: cathode-ray tube.
Transmitter plate current meter: reading determines setting of the high-voltage variac, No. 15. 13. Transmitter plate power off-on switch: controls AC power applied to the high voltage variac, No. 15.
Transmitter plate variac: controls the amount of DC voltage applied to plates of the transmitting tubes.
IFF gain control: varies amplitude of IFF signals appearing below the time base.
Transmitter.
Red pilot light: when illuminated, indicates that the power switch is on at the receiver-indicator unit.
Transmitter plate current meter: reads the same as meter No. 13 on the receiver-indicator unit.
Filament primary voltage meter: indicates voltage applied to the primary of the filament transformer, which supplies AC power to filaments of the transmitting tubes.
Filament control variac: controls the amount of voltage applied to the filament transformer.
Operation hour meter: registers the total number of hours the set has operated.
Emergency switch off-on: is in series with main power switch, to be used only in case of emergency.
Figure 4 SD-1. Range indicator unit.
4-SD-2
Diplexer tuning dial: indicates position of the tuning condenser in the diplexer.
Diplexer tuning control: varies the position of the condenser in the diplexer: to he set by radar technician.
Exhaust of blower: maintains cooling for the transmitter.
Figure 4 SD-2. Transmitter unit.
Diplexer.
(Diplexer unit is to be adjusted by the radar technician only.)
Figure 4 SD-3. Antenna mast and diplexer, with most raised.
TURNING ON AND OFF
Turning an.
Check to see that the transmitter plate high voltage switch is off.
Turn on the power switch at the receiver-indicator.
Red pilot light on the transmitter should illuminate.
Check to see that the blower motor in the transmitter is operating.
Rotate the primary filament variac slowly clockwise, white watching the filament primary voltage meter increase to a value determined by the radar technician (110 to 120 volts).
At the receiver-indicator unit, check to see that the transmitter plate variac and the intensity control are fully counterclockwise.
Raise the antenna mast until the top insulators on the mast shoes are even with the top insulators of the diplexer shoes (see fig. 4 SD-3.)
Turn on the transmitter high voltage switch on the receiver-indicator unit. Check to see that the red pilot light on the receiver-indicator unit is illuminated.
If the line switch has been on for at least 30 seconds, proceed to turn transmitter plate variac clockwise until the plate current meter reads 8 milliamperes (or value specified by technician).
4-SD-3
Turning off.
Turn the transmitter plate variac to zero.
Turn off the transmitter plate switch.
Turn off the power switch.
Do not touch other controls.
Lower the antenna mast.
Abbreviated procedure.
It is suggested that the following controls he left at the proper settings at all times, thus decreasing to a minimum the time required for tune-up:
Filament control variac on the transmitter unit.
Intensity, focus, tuning, sensitivity, and horizontal centering controls on the receiver-indicator unit.
Turning on is then reduced to the following procedure:
Turn on the power switch on the receiver-indicator unit.
Check the green pilot light on the receiver-indicator unit; blower motor in the transmitter, and the filament primary voltage meter on the transmitter.
Raise the antenna mast as described above.
Check to see that the transmitter plate variac on the receiver-indicator unit is at zero..
The power switch should he on for 10 minutes before using the set.
Raise the antenna mast while at periscope depth.
When depth decreases to a point at which the antenna is clear of the water (7 to 10 feet), turn on the transmitter plate high voltage switch.
CALIBRATION, just below the sweep line; carefully indicate, in ink. each 2-mile point on the tape (the first marker represents a 2-mile point on the sweep, and each marker thereafter is a 2-mile point)..
OPERATIONAL TECHNIQUE
Tuning the equipment.
Increase the intensity control until the sweep is visible on the scope.
Adjust the, focus control for clearness.
With the sensitivity control near minimum (counterclockwise), rotate the oscillator control until a point of maximum response is noted on the scope (increase sensitivity control if necessary).
Adjust the sensitivity until the flag at the top of the transmitter pulse (left end of the sweep on the scope) is about 1-inch above the base line.
Adjust the oscillator control for maximum height of the flag. Now rotate the oscillator control through 360°, checking for another tuning point which may increase the altitude of the flag. Leave the oscillator control on the best tuning point.
Increase the sensitivity control until grass appears on the screen. If a steady echo is present, cheek the oscillator tuning for the maximum echo
4-SD-4
height. This check should he made with the sensitivity control adjusted so the echo tuned on is just visible above the grass. be made as quickly as possible during the surfacing procedure.
Air search during surface cruising.
Watches of a half-hour duration should be adopted whenever possible. Only those men who have had previous SD radar experience, if available, should be used as operators. When an operator is standing an SD search watch, he must stay within three feet of the equipment, keeping a continual watch on the screen.
Report all targets and IFF signals, giving their ranges. Identify the composition of targets, using the following characteristics as a guide to your interpretation of target pips.
Land (sharp, fairly steady pip).
Single plane (narrow pip, fuzzy at the top, fading and bouncing rapidly)..
Diving procedure.
When the word "stand by to dive" is passed, the operator will perform the following operations:
Turn the transmitter plate variac to zero and turn the transmitter plate voltage switch off.
Lower the antenna mast..
PERFORMANCE
4-SD-5
Due to the fact that low flying planes will usually not be detected, lookouts must be alert for aircraft flying at low elevations during daylight hours.
Minimum range.
The minimum range on aircraft is about 2,500 to 3,000 yards.
TROUBLES
Trouble is indicated in the SD radar by the following operational difficulties:
From 1/4 to 1½ inches of grass are not present at all times when the sensitivity is turned to maximum. 2. Sweep position, intensity, and focus do not remain constant when untouched by the operator.
Appearance of the transmitter flag does not remain substantially the same.
Internal interference is heavy and persistent.
Arcing is audible in the antenna during normal operation.
Bi-directional, or a non-uniform pattern of transmission is suspected.
Echoes and ranges on known land and friendly planes, appear to be below normal.
Figure 4 SD-6. Typical screen interference.
4-SD-6
Part 4.
SU RADAR
CONTROLSThe operator of the SU radar is concerned primarily with the Control and Range Unit, although inspection of the Modulator and Bearing and Gyro Switch Units will occasionally be necessary. A line drawing of the Control and Range Unit is shown in figure 1 and of the Modulator and Bearing and Gyro Switch Units in figures 2 and 3. The operator will be called on to make adjustments on these other units of the radar: Transmitter-Receiver; Control Rectifier; Antenna Motor-Generator; and Antenna Assembly.
Identification and Function
All of the controls are plainly labeled on the SU radar. A brief summary of the functions follows: Identifying letters and numbers refer to line drawings in figures 1, 2, and 3.
Figure 4 SU-1. Control and range unit.
Control and Range UnitA. Line Voltage meter: Reads the AC voltage input to the unit from the ship's line after the power switch (W) has been pressed. The reading should be within the red lines marked on the scale, 105 and 125 volts, and preferably above 112. volts.
B. Operate-stand-by switch: Controls the operation of the transmitter. When in STAND-BY position, the transmitter does not operate, but the filament supplies are kept on. Operation may be resumed immediately by throwing to the OPERATE position.
C. Stand-by lamp: Lights when the operate-stand-by switch (B) is in the STAND-BY position.
D. Battle short on lamp; Lights when the battle short switch (7) is in the ON position, indicating that safety interlocks are shorted out.
E. Range dimmer knob: Controls the intensity of the range scale dial lights.
F. Range handwheel: Controls the position of the step on the A-scope trace, the position of the ranger marker spot on the PPI, and the reading of the range counters.
G. Stabilization correction meter: Shows the angle between the (vertical) position of the stabilized antenna and a line normal to the deck of the ship. This meter should read zero when the Stow-stabilized switch (H) is in the STOW position.
H. Stow-stabilized switch: Normally in the STABILIZED position. In this case, the antenna stabilizing system operates to keep the reflector
4-SU-1
vertical. In the STOW position, the reflector locks in a position normal to the deck of the ship.
I. Danger R.F. unit overheating lamp: Lights if the temperature of the Transmitter-Receiver Unit becomes too high. This is an indication of trouble in this unit.
J. Bearing dimmer: Controls the intensity of the dial lights on the PPI bearing scale.
K. For manual train, push in: The training control. When pushed in, the rotation of the antenna and of the PPI trace is controlled manually by the handwheel. When pulled out, the antenna and trace rotate automatically at 6 r.p.m.
L. Receiver gain: Controls the amplitude of the echo signals and "grass" on the A-scope and brilliance of echoes and amount of "snow" on the PPI.
M. Intensity: Controls the intensity of the trace on the A-scope.
N. Echo box tuning knob: Used to tune the echo box cavity to resonate at the frequency of the transmitter. It controls a motor which, in turn, moves a plunger either in or out of the cavity resonator, depending upon the direction in which the Echo Box Tuning knob is turned.
O. Echo box amplifier switch: When in the ON position, applies the echo box crystal output to the IFF trace. This switch must be in the ON position for tuning when using the echo box method, and in the OFF position for reception of IFF signals. Normally this control is left in the OFF position.
P. Focus: Controls the focus of the image appearing on the A-scope trace.
Q. Intensity: Controls the intensity of the PPI trace.
R. IFF Gain: Varies the amplitude of IFF signals appearing on the A-scope and the PPI.
S. Focus: Controls the focus of the image appearing on the PPI.
T. IFF ON-OFF Switch: produces the IFF trace on the A-scope when in the ON Position. Note that the Echo box amplifier switch (O) must be OFF to allow IFF signals to appear on the IFF trace.
U. L.O. Tuning: Adjust the frequency of the local oscillator in the Transmitter-Receiver unit provided the Manual-afc switch (V) is in the MANUAL position.
V. Manual-afc: Switches in or out the automatic frequency control circuit in the Transmitter-Receiver unit. In MANUAL position, the L.O. Tuning control (U) may be used as a fine adjustment of the local oscillator frequency. In AFC position, the local oscillator frequency is controlled by the AFC circuit.
W. Power (PUSH ON, PUSH OFF): A button used to apply line voltage to, or disconnect line voltage from, the various units.
X. Range Selector switch: Allows the operator to select one of the following scales for the A-scope and PPI. 8,000 yards, 40,000 yards, or 80 miles. The appropriate set of range counters will be illuminated.
Y. Power-on lamp: Lights when power is supplied to the equipment.
Z. Marker intensity potentiometer: Varies intensity of the calibration pips on the PPI scope only. Markers on-off switch (1) must be in the ON position.
1. Markers on-off switch: Controls the markers circuit. When this switch is in the ON position, calibration pips appear on both scopes. The number of pips appearing depends on the setting of the Range selector (X).
2. Relative bearing only lamp: Lights when the SHIP'S GYRO-REL. BEARING ONLY switch located on Bearing and Gyro Switch Unit is thrown to REL. BEARING ONLY position. When lamp is lighted, only relative bearings can be read on the bearing indicator on the PPI. When the lamp is not lighted, both true and relative bearings may be read.
3. Warning Training error lamp: Lights if the antenna and PPI trace fall out of synchronism to an excessive degree.
4, 5, 6. Min. set knobs: Adjust the zero set of the 8,000-yard, 40,000-yard, and 80-mile scales, respectively.
7. Battle short switch: In the ON position, shorts out all interlocks in the Control and Range Unit so that the power remains on even if the chassis is pulled out and the cover is raised. It may be necessary to place this switch in the ON position if gun fire or other vibration opens the interlocks.
8. IFF Delay: Controls the timing of the IFF trace in relation to the transmitted radar pulse. This is adjusted as follows: Rotate Range Selector (X) to 8,000-yard scale and Range crank (F) to the 0-yard position. IFF on-off (T) must be in the oN position. Then turn the IFF Delay control (8) until the trailing edge of the upward pulse
4-SU-2
on the IFF trace (the image of the IFF transmitted pulse) coincides with the leading edge of the range notch.
9. Range step on-off switch: Controls the range step on the A-scope. In the OFF position, the step will no longer appear on the A-scope trace.
10. PPI Bias: Controls the intensity of PPI trace.
11, 12, 13. Max set knobs: Adjust the sweep speeds of the 8,000-yard, 40,000-yard, and 80-mile scales, respectively.
14. PPI-IFF switch: Permits IFF signals to appear ln the PPI when the switch is in the ON position.
Figure 4 SU-2. Modulator unit.
Modulator Unit
15. Magnetron current meter: normally reads magnetron current, but if the switch marked Push to read modulator current (16) is pressed, it reads modulator current. When the gear is properly adjusted, modulator current should read between 7.5 and 10 ma. when the magnetron current is adjusted to 5.0 ma.
17. AC Line voltage meter: measures the voltage applied to the input of the unit from the ship's line, whether the main power switch in the Control and Range Unit is on or off.
18. All safety switches inoperative lamp: When lighted, indicates that interlocks in the unit have been shorted out by the Battle short switch located behind the lower front panel.
19. High voltage supply on lamp: Lights when the gear is in operation.
20. Accumulative hours meter: Indicates the total length of time the gear has been in operation.
21. AC Power on lamp; Lights when power is applied to the gear.
22. Magnetron current control variac: Should not be adjusted by the operator. The technician will set this control so that the megnetron current will read 5 ma. with power on.
Figure 4 SU-3. Bearing and gyro switch.
Bearing and Gyro Switch Unit
23. Ship's gyro-rel, bearing only switch: Normally should be set to SHIP'S GYRO position. In this position, relative and true bearings are indicated on the outer and inner PPI bearing scales, respectively. When the switch is in the REL. BEARING ONLY position, the movable outer scale swings around and locks in at the position where its readings agree with those of the stationary inner scale, and both scales give identical relative bearing readings.
TURNING ON AND OFF
Preliminary Checks
These checks should be made before power is applied to gear:
1. Turn ship's gyro-rel. bearing only switch (23) to SHIP'S GYRO position unless gyro power is unavailable. In this case, turn to REL. BEARING ONLY position.
2. Stow-stabilized switch (H) in STOW position.
3. For manual train-push in (K) crank should be pushed in.
4. IFF gain control (R) should be fully counterclockwise.
5. Echo box amplifier switch (O) should be in the OFF position.
4-SU-3
6. PPI intensity control (Q) fully counterclockwise.
7. PPI bias (10) fully counterclockwise.
8. A-scope intensity control (M) fully counterclockwise.
9. Receiver gain control (L) should be fully counterclockwise.
10. Operate-stand-by switch (B) should be in STAND-BY position.
Turning on
1. Press power (push on-push off) button (W) applying power to the set. Stand-by lamp (C), power on lamp (Y), and C power on lamp (21) should light and the fan motor in the Control and Range Unit will be heard.
2. Check reading of line voltage meter (A). If it does not read between 105 and 125 volts, call a technician.
3. Approximately 1 minute after applying power as above, a clicking noise will be heard indicating that an internal relay has closed. If the intensity controls are then turned up, sweeps will be visible on the scopes.
4. Stow-stabilized switch (H) is thrown to STABILIZED position. It will take 15 minutes or so for the stabilizing circuit to warm up sufficiently to operate satisfactorily.
5. As soon as step number 2 in this procedure has been accomplished, Operate-stand-by switch (b) should be thrown to OPERATE position. Stand-by lamp (C) will go out.
6. Turn on IFF gear.
7. About 3 minutes after the Operate-stand-by switch has been turned to OPERATE, the modulator time delay mechanism will operate, and a click will be heard. High voltage supply on lamp (19) will light. Plate voltage is now supplied to modulator tubes and the gear is transmitting.
8. Check magnetron current by reading meter (15) in the Modulator Unit. If this does not read 5 ma., call a technician.
9. Push switch marked Push to read modulator current (16). If modulator current does not show between 7.5 and 10 ma., call a technician.
10. Turn up A-scope Intensity (M) until the trace is of sufficient brilliance.
11. Focus the trace using Focus control (P).
12. Start the antenna on automatic rotation, and switch to 40,000 yards range scale.
13. Adjust PPI Bias control (10) until the PPI trace is just visible.
14. Turn the Receiver gain control (L) until about three-eights inches of grass is visible.
15. Adjust PPI Intensity (Q) for a faint indication of snow.
16. Throw IFF on-off switch (T) to the ON position. A second sweep will now appear on the A-scope.
17. Adjust the IFF Gain (R) for grass on the IFF trace.
18. Throw the IFF on-off (T) switch to the OFF position.
To place the gear in stand-by condition, merely throw the Operate-stand-by switch (B) to STAND-BY. Stand-by lamp (C) will then light indicating that no radiation is leaving the transmitter.
Turning Off
In order to shut down the gear, the above procedure should be reversed:
1. Push the antenna crank into the manual position. The antenna may be left at any bearing since it is covered from view by a dome.
2. Throw the Stow-stabilized switch (H) to STOW. This will remove power from the stabilizing circuit.
3. Turn PPI Intensity control (Q) fully counterclockwise.
4. Turn A-scope Intensity control (M) fully counterclockwise.
5. Receiver gain (L) counterclockwise.
6. IFF Gain (R) counterclockwise.
7. Throw switch Operate-stand-by control (B) to STAND-BY.
8. Turn off IFF gear.
9. Press Power on-off (W) removing power from the SU gear.
Figure 4 SU-4. How to calibrate.
4-SU-4
CALIBRATION
To make sure that the SU gear will give accurate range readings, the operator should check the calibration of the ranging unit every half hour for the first hour of operation and every hour thereafter. Each of the three range scales must be calibrated independently. Adjustment of one range scale will not affect the calibration of the other scales. In lining up the range step with the calibration pip, it is suggested that the steps be brought to the left-hand edge of the pip. It is important that the same method of positioning the range step used during calibration be used when ranging on echoes. The preferred method is shown in figure 4-SU-1.
1. Turn the Markers on-off switch (1) to the ON position.
2. Set the Range selector switch (X) on the 8,000-yard scale.
3. Rotate the Range handwheel (F) until the counters read 0 yards.
4. Adjust the Min. set knob (4), aligning the FIRST calibration pip with the range step.
5. Rotate Range handwheel until the range counters read 8,000 yards.
6. Adjust the Max. set knob (11), aligning the FIFTH calibration pip with the range step.
7. Repeat steps 3 through 6 until no further adjustment of Min. set or Max. set is necessary.
8. Set the Range selector switch on the 40,000-yard scale.
9. Calibrate this scale as indicated above, aligning the SECOND calibration pip with the range step at 2,000 yards, and the TWENTY-FIRST pip with the range step at 40,000 yards. Vary Min. set (5) and the Max. set (12).
10. Set the Range selector switch on the 80-mile scale.
11. Calibrate this scale as above, aligning the SECOND calibration pip with the range step at 4 miles and the SIXTEENTH pip with the range step at 79 miles. Use Min. set (6) and Max. set (13).
Note that on the 8,000-yard scale and the 40,000-yard scale, calibration pips appear 2,000 yards apart. On the 80-mile scale, the pips are 5 miles apart, with the exception that the first and second pips are 4 miles apart.
The technician can check the calibration markers circuit of the SU with a double range echo or by knowing the exact range to a given target. The range markers can be moved left or right (before or after in time) with respect to the transmitted pulse to get them lined up correctly. This should be done periodically when such targets are available, but only after the SU is thoroughly warmed up.
OPERATIONAL TECHNIQUES
Tuning the SU
Tuning the SU may be accomplished using echoes from land, surface targets, clouds, or sea return. If none of these is available, the SU may be tuned using the echo box gear with which the radar has bee equipped. Under normal conditions, the AFC (Automatic Frequency Control) circuit will hold the receiver in proper tune. However, the tuning should be checked each watch to determine whether the AFC circuit is operating properly.
(A) Tuning With Echoes.--
1. Stop the antenna on the best target available.
2. Throw the Manual-AFC switch (V) to MANUAL position.
3. Turn the Receiver gain down until the echo is not saturated. (Until it is considerably below maximum height.)
4. Push in the L.O. Tuning control (U) and turn it through its entire range, about three-quarters of a turn. One or more points where the echo will appear on the scope may be found.
5. Select the point at which the echo comes in the strongest, and carefully adjust the L.O. Tuning until the echo pip is at maximum height.
6. Throw the Manual-AFC switch to the AFC position and compare the height of the echo pip with the height when the switch is in the MANUAL position.
7. Normally an echo will appear to be of the same height or slightly higher with the switch in the AFC position. If it is smaller, the AFC circuit is not operating properly, and the switch should be left in the MANUAL position. Tuning should be checked each watch.
(B) Tuning with Sea Return.--The same method is used as described above, except that the sea return should be maximized in range rather than in height. By this, it is meant that the L.O. Tuning control should be adjusted until the sea return extends out to the greatest range possible.
(C) Tuning using Echo Box.--
1. Set the Range selector switch (X) on the 8,000-yard range scale.
4-SU-5
2. Stop the antenna at the desired bearing. Any bearing may be used, but the same relative bearing should be used whenever the echo box is used for tuning.
3. Turn the IFF on-off switch (T) to ON.
4. Turn Receiver gain (L) fully counterclockwise.
5. Throw the Manual-AFC switch (V) to MANUAL.
6. Throw the Echo box amplifier switch (O) to the ON position. No IFF indications will now appear.
7. Turn the Echo Box Tuning knob (N) customarily clockwise and hold it until a negative pulse appears at the left end of the IFF trace. Carefully turn the knob back and forth, maximizing this negative pulse. Now the echo box is tuned to the frequency of the transmitter.
8. Adjust the L.O. Tuning control (U) for maximum ringing time (positive pulse) on the upper trace. The receiver is now tuned to the frequency of the echo box and, hence, to the frequency of the transmitter. This ringing time should be measured in yards by aligning the step with the point where the lagging end of the pulse reaches the base line. This measurement gives a method for determining the efficiency of the gear. If the transmitter decreases in power or the receiver in sensitivity, the ringing time will be decreased.
9. Check the AFC circuit as in the ordinary tuning procedure. If the AFC gives the same or a longer ringing time, as it should, leave the Manual-AFC switch (V) in the AFC position.
10. Detune the echo box by turning the Echo box tuning knob (N) clockwise and holding it until the negative pulse disappears. If the echo box is not detuned, the minimum range of the g ear will equal the ringing time in yards.
11. Throw the Echo box amplifier switch (O) to the OFF position so that IFF responses may appear on the IFF trace.
12. Set the range selector switch (X) on the 4,000-yard scale, and adjust the Receiver gain (L) for the desired grass.
Normal Search
Normally, the 40,000-yard scale will be used for search. Both the A-scope and the PPI should be watched, though echoes will usually appear on the PPI as soon as they are visible on the A-scope. It will be necessary to stop the antenna to obtain accurate evaluation of the composition of targets. Since it is imperative that the antenna be stopped for as short a time as possible, the operator should check for IFF at the same time that he is estimating composition. The antenna need rarely be stopped for over 12 to 15 seconds. If it is impossible to stop the antenna because of orders from the bridge, during complicated maneuvers or other emergencies, it is possible to obtain ranges form the PPI by aligning the range spot, appearing on the PPI trace, with the target. When obtaining ranges, either using the step on the A-scope or the PPI range spot, it is suggested that the step, or spot, be aligned with the leading edge of the target, rather than with the center.
Short Range Search
Short range search is primarily used when submarines, PT boats, or other small targets are anticipated, as well as for station keeping. For this type of search the 8,000-yard scale is used. Attention should be directed principally to the PPI and the antenna should be rotated automatically.
A different gain setting than that used for search on the 40,000-yard scale must be employed unless the gear is equipped with an STC (Sensitivity Time Control) circuit. The operator can discover whether this circuit has been added to the gear by questioning a technician. If this circuit has not been installed, the gain control must be set at a lower value so that the sea return will not make the detection of small targets close to the searching ship impossible. Because of the extremely high frequency of the SU (considerably higher than that of most surface search gears such as the SG and the SL), sea return will be of greater magnitude and will extend to greater ranges.
Long Range Search
This type of search is conducted using the 80-mile range scale. The antenna is rotated manually with the bearing crank. The A-scope should be watched closely, although targets will usually appear on the PPI as soon as on the A-scope. The determination of ranges and bearings is accomplished in the same manner as in the Normal Search procedure.
General Operation
Each ship will have its own search procedure, and it is important that every operator become familiar with the methods used. Ordinarily,
4-SU-6
normal search will be conducted on the 40,000-yard scale, with a 360° long range (80-mile scale) hand sweep every 5 minutes. Ranges and, possibly, bearings to the guide ship will be requested occasionally. Thus it is very necessary that the operator be capable of switching rapidly from one scale to another, making adjustments of gain, focus, intensity to give the best obtainable picture for each scale. A good operator will make these small adjustments instinctively each time he changes from one scale to another.
Station Keeping
If radar is used to supplement regular station keeping methods, it is preferable that a remote indicator such as the VD or VF be employed rather than obtaining information from the SU itself. It should be remembered that the primary function of this gear is surface search, and that any stoppage of the antenna or change in range scale cuts down on the time available for search. All OOD's should realize that while radar give more accurate ranges than the stadimeter, bearing information from optical gear is more reliable. If the SU is used for station keeping, the 8,000-yard range scale should be employed and, if possible, ranges should be taken using the range spot on the PPI without stopping the antenna.
Auxiliary Fire Control and Navigation
(See pages 4-SG-8 and 4-SG-9 of RADTHREE.)
Composition
It is impossible to do more than state a few generalities on the subject of composition. The ability to make intelligent estimates as to the composition of a contact comes only with experience at sea. However, the following may prove to be of some aid to the inexperienced operator.
Type and Number of Ships.--Large ships will be detected at greater ranges than smaller craft. For normal installations aboard DE's, carriers, and battleships will appear at 42,000 yards, cruisers at 38,000 yards, destroyers at 30,000 yards, surface submarines at 20,000 yards, and periscopes at 5,000 yards. These ranges, of course, are only approximate and are dependent upon the exact height of the antenna, weather conditions, and the condition of the gear. The echoes from larger ships will appear to be steadier; fluctuations will be slower than those from small vessels.
The number of ship in a group may be estimated more accurately if the gain is turned down to a lower value than that used for search. Count the peaks on large pips rather than expecting a separate pip for each ship. If ships are closer together than 300 yards in range or 4° in bearing, separate pips will not appear.
Aircraft.--The SU will detect bombers flying close to the water (300 feet) at about 30,000 yards. An aircraft echo will bob, or fluctuate, and will change range and/or bearing much more rapidly than that of a ship.
Land.--Land masses give wider and steadier echoes than ships. Of course, they have no course or speed.
False or Misleading Echoes.--Second-sweep echoes can appear from targets whose range is greater than 1387 miles. These will rarely be observed, and then only from very high land masses.
A more common phenomenon, experienced when operating close to other ships, is the multiple-range (or double-range) echo. If other ships are near by, within 3,000 or 4,000 yards, the returning echo from one of these ships can reflect off the searching ship, strike the target ship again, and finally return to the antenna of the searching ship. The double-range echo may be recognized easily since (1) it will always be on the same bearing as one of the larger targets and (2) it will always be at exactly twice the range of that target. The double-range echo will be very weak under most conditions.
Mast reflections are caused by energy from the radar striking a mast or superstructure, reflecting from this interfering structure, hitting the target, and returning over the same route. The false echo will appear at the same range as the real target and at the bearing of the interfering structure.
Anti-jamming Operation
Although the SU is an X-Band radar, and no practical transmitter has yet been developed to jam such high frequencies, there is every reason to suppose that such a transmitter can be designed in the near future. Therefore, the operator should learn to expect jamming or deceptive measures and know best how to combat them. Deception by the use of dummy targets such as "window," "kites," corner reflectors, and so on will not be covered here. The reader should refer to the section on deceptive countermeasures on RadThree.
It is necessary that the operator know the procedure to be followed in case he finds himself
4-SU-7
jammed. The following is a brief list of rules that should be remembered:
1. Keep Operating. This is most important, since the enemy has no way of knowing whether his jamming is effective and, if operation continues, he may conclude that his efforts are a failure and may secure the jammer. Also, a close watch should be kept of the unjammed sectors to prevent sneak attacks from coming in undetected.
2. Try to get a bearing on the jamming. If two ships can take bearings on a jammer, the approximate position of the jammer may be plotted and positive action can be taken.
3. Report the type and bearing of the jamming to the CIC watch officer. Recognition of the type of jamming may be difficult if not impossible. The operator should refer to Part 3 of RADTHREE for the more common types and their appearance on the A-scope and PPI.
4. Attempt to read through the jamming.
The most important anti-jam device on the SU is the gain control. There is always an optimum setting for any particular type of jamming and this setting will usually be different from that used for search. The proper amount of gain to be used in a particular case must be found by trial and error. When jammed, rotate the gain control back and forth to find this best setting.
Sometimes, some relief may be experienced by changing the receiver local oscillator tuning. This will be true if the jamming is not exactly on the same frequency as the radar, since detuning may detune the jamming signal more than the echo. This measure has a very bad disadvantage, however, which makes it ordinarily inadvisable. The receiver may be detuned and, if no known targets are in the vicinity, the operator will not be able to bring it back into tune quickly. Thus there is considerable chance of missing targets that may be within radar range. Once the receiver is detuned and there is a lack of known targets, the echo box must be used to retune.
Stopping the antenna on the jamming in hopes of reading through with the A-scope is often effective since pips can be detected Through jamming on the A-scope more readily than on the PPI. However, stopping the antenna will inform the enemy that his jamming is, at least, troublesome. Also, of the antenna is stopped, there is more chance of enemy raids coming in undetected on unjammed sectors. The decision of whether to stop the antenna or not, will depend upon the tactical situation.
TROUBLES
Although most troubles will be handled by the technician, the operator should recognize the symptoms of some of the more common failures.
If, when the gear is first turned on, the power-on lamp (Y), the AC power-on lamp (21), and the fan motor in the Control and Range Unit do not operate, the fuses in the power line should be checked by a technician.
If no echoes, sea return, or transmitted pulse appear on the scopes and the high voltage supply on lamp (19) does not light when the operate-standby switch (B) has been in the OPERATE position for over 3 minutes, the fuses in the modulator plate voltage supply should be checked as well as the modulator time delay mechanism.
The danger r.f. unit overheating lamp (I) will light if some trouble in the Transmitter-Receiver Unit on the mast causes dangerous overheating. This may be due to faulty circuit components or shorts in this unit.
Trouble in the antenna drive system may be indicated by the warning training error lamp (3) lighting. When this lamp is lighted, the "bug" on the bearing indicator no longer indicates the direction in which the antenna is pointing. If the antenna has stopped rotating and the "bug" and the PPI trace continue to rotate, the picture on the PPI will appear as a series of markers described through the full 360°. If there are no targets in the vicinity, or if the antenna has stopped on a bearing where no targets are located, nothing will appear on either screen except sea return. The trouble will not be so apparent, but the sea return on the A-scope will not change as the "bug" rotates. If the antenna system does not appear to be operating properly, the operator should try turning the ship's gyro-rel, bearing only switch (23) to the REL. BEARING ONLY position. In this position, only relative bearings can be read off the bearing indicator. If this measure fails, a technician should be notified.
4-SU-8
CHARACTERISTICS AND PERFORMANCE
Antenna-Reflector: Type, dishpan with radome; shape, paraboloid; size, 24 inches diameter.
Feed: Dipole feed from waveguide.
Beam width: Horizontal, 3.8°; vertical, 3.8°.
Rotation speed: Manual train or automatic at 6 r.p.m.
Pulse width, 1 microsecond.
Pulse repetition frequency, 600 pps.
Minimum range, 200 yards.
Range accuracy, 8,000-yard scale: plus or minus 200 yards; 40,000-yard scale; plus or minus 500 yards; 80-mile scale: plus or minus 1,000 yards.
Bearing accuracy, plus or minus 1°.
Range resolution, 300 yards.
Bearing resolution, 3°.
Performance--Maximum Reliable Range:
Carriers and Battleships, 42,000 yards.
Cruisers, 38,000 yards.
Destroyers, 30,000 yards.
Surfaced Submarines: 20,000 yards.
Periscopes, 5,000 yards.
Bombers at 500 feet, 30,000 yards.
4-SU-9
ST RADAR (AS USED WITH SJ)
CONTROLS
The ST radar is used in conjunction with the SJ to provide a search radar to be used by submarines while submerged at periscope depth. It can also be used as an emergency search while surfaced. The ST and the SJ both use the same units with the exception of the transmitter-receiver, wave guide, antenna, and the adapter switch box, which is used to switch from SJ to ST. All units except those noted above are fully explained in the SJ section pages 4-SJ-2 and 4-SJ-3.
Figure 4 ST-1. Selector control unit (for the ST as used with the SJ).
Selector Control Unit
A. ST antenna switch: selects the ST antenna in the up or ON position or the dummy antenna in the down position.
B. Red lamp which lights when the ST antenna is in use.
C. ST-SJ switch: determines which radar is to be used.
D. Red lamp which lights when the ST radar is selected.
E. Red lamp which lights when the SJ radar is selected.
F. ST echo box switch: turns on the echo box when in the up or ON position for normal operation this is left in the down position.
G. ST rep rate control: varies the pulse repetition rate. The PRF is 1500 ± 10 percent (when the ST is used with the SJ).
Transmitter-receiver Unit
A. Crystal current meter: reads 0.5 to 0.9 milli-amperes when the equipment is properly tuned.
B. Wave-guide transmission line to antenna.
Figure 4 ST-2. Transmitter-receiver unit.
TURNING ON AND OFF
In general the procedure for turning on and off is similar to that outlined in the section on the SJ page 4-SJ-4. The asterisks marks (*) are used to indicate the operations which differ from those where the SJ alone is used. These operations are performed from the main control unit and the selector control unit. (NOTE. --The antenna wave guide valve should be left in the open position at all times.)
Turning On
1. Turn ON heater switch (13) 30 minutes before operating. If at sea, leave heater switch ON at all times.
2. Flip ST-SJ switch (C) to ST position.
3. Put ST antenna switch in the down position (selecting the dummy antenna).
4-ST-1
4. Turn ON main switch (1). A green light will glow if the set is operating correctly.
5. Check to see if the blower motors can be heard in the transmitter-receiver unit. If not, turn the main switch OFF and call the technician.
6. Check the load voltage meter (3) for 120-volt reading. If this is not indicated, adjust the load autotransformer control (4) for 120 volts.
7. Check the regulated rectifier voltage meter (5) for 300 volts. Check this in both positions of the meter switch (6). If either one is off more than 15 volts, call the technician.
8. After a time of approximately 1 minute (sufficient to allow the time delay to act), turn on the high voltage switch (7). If the time delay has operated, the red lamp (8) will light, and the high voltage should be on. The needle on the high voltage rectifier meter (10) should immediately jump to between 0.9 and 1.2 kv. providing the high voltage variac (9) has been left at its proper setting when the set was last secured.
9. The high voltage rectifier current meter (11) should read between 140 and 160 milliamperes.
10. Check the load voltage meter (3) again, for a value of 120 volts.
11. When the ST antenna breaks surface, flip the ST antenna switch (A) to the ON position.
Turning Off
1. Turn off the high voltage switch (7). Do not turn down the high voltage variac (9).
2. Turn off the main switch (1).
3. Do NOT turn off the heater switch (13) unless the set is to be worked on. Other units need not be touched.
4. Put the ST antenna switch (A) in the down (or dummy) position.
5. Flip the ST-SJ switch (C) to the SJ position.
CALIBRATION
Calibrate using the procedure outlined for the SJ on page 4-SJ-4. The ST must be calibrated each time after switching from SJ to ST.
OPERATIONAL TECHNIQUES
In general the operational techniques for the SJ and the ST are the same. Tuning
The ST must be tuned each time after switching from the SJ to the ST. Follow the outline for the SJ on page 4-SJ-5, for tuning.
NOTE.--The ST does not have AFC (automatic frequency control); therefore tuning should be done with the echo box before surfacing and checked when surfaced with available targets or sea return.
The PPI is not used with the ST.
Reading Bearing and Range
Bearings are obtained visually through the periscope. Radar bearings may be obtained by rotating the periscope across the target, stopping when the pip is at maximum height. The ST does not use lobing.
Ranges are obtained in the same manner as that used with the SJ. There is one thing that the operator should remember; in the event there are more than two targets on the scope he must check with the periscope operator to be sure that they are both on the same target. Due to the 40° beam width, it is quite possible to give range readings on the wrong target. Practice and cooperation between the two operators will help correct this trouble.
The ST is not generally used while surfaced. The ST may be used to the best advantage for submerged approaches or obtaining navigational fixes where it is impossible to surface.
NOTE.--AJ operations are the same as those discussed for the SJ on page 4-SJ-8.
PERFORMANCE
The same general conditions affecting SJ ranges are also true with the ST.
Maximum reliable ranges while submerged to 52 feet:
Surfaced, the ranges are about two-thirds for those obtained with the SJ.
ACCURACY
The bearing accuracy of the ST is that of the periscope optics. Radar bearing accuracy is about ±5° due to the 40° beam width.
The ST range accuracy is the same as that of the SJ.
RESOLUTION
Bearing: Very poor due to the wide beam. It is about 20°.
Range: 40 yards.
4-ST-2
SR RADAR
SR RADAR
The SR is the first of a series designed to standardize air search radars. More complete standardization has been achieved in the subsequent SR-1, SR-2, and SR-3. The SR-2 and SR-3 operate on different frequency bands. Thus, with SR, SR-2, and SR-3 in a task force, three different frequency radars would be available. The SR-1 and SR-4 are developmental models.
The SR-6 is a junior version of the SR-3 and on the same frequency band. It is designed to exploit the possibilities of the current practice of using search radars in conjunction with remote scopes. Planned for destroyer installations, it will have slightly lower power output than the SR-3, a 500-pound antenna and no Servo-Antenna control. The SR-3 characteristics make it suitable for heavier ships. The SR-2 is designed for destroyers and cruisers.
The SR is the only one of the series which has reached the fleet in any great quantities.
The antenna is normally rotated clockwise or counterclockwise by a drive motor which revolves the antenna at two speeds, 1¼ and 2½ r.p.m., or 1¼ and 5 r.p.m., depending on the particular installation. An emergency source of power is provided for the antenna drive motor which can be cut in immediately should something occur to the normal system. This emergency system rotates the antenna at 6 r.p.m. clockwise with no servo-control.
An echo box is provided to permit tuning the set when no targets are available and to enable comparative readings to be made which, over a period of time, give an indication of dropping off in performance. The echo box antenna is mounted at the antenna pedestal. In order to tune or take an echo box reading, the operator trains the SR antenna toward the pick-up antenna on the echo box, energizes the echo box by turning on switch (C) of Panel 1, (1-C), and tunes on the echo which will appear on the 4-mile range scale. Over a period of time a "par" range reading may be determined. Deviation from this "par" will indicate the condition of the set.
The SR radars are composed of two major consoles as follows:
1. The transceiver console.
2. The indicator console.
The operator is concerned principally with the indicator console. Complete control is ordinarily accomplished from the indicator console. This is done by placing the remote--local switch on the transceiver console in the REMOTE position. All other controls on the transceiver console are the concern of the technician.
4-SR-1
Figure 4 SR-1. Indicator console.
4-SR-2
The SR Indicator Console is composed of four sections, each of which contains one or more standard units as follows:
Panel No. 1:
Receiver Unit.Panel No. 2: PPI Unit.
Control Unit.
IFF Coordinator.
Panel No. 3:
Range Scope UnitPanel No. 4: Rotation Control Unit.
Bearing Indicator Unit.
Identification and Function.--Panel No. 1
Receiver Unit.--A. Receiver band-pass pulse-length selector switch: This switch performs two functions. It selects any desired pulse length with its corresponding pulse repetition frequency from the three combinations available--1, 4, and 20 microseconds; and it also adjusts the receiver band pass characteristic to give best results for each pulse length. The switch positions are labeled according to the sharpness of the band pass characteristic desired, thus the " sharp" position is used when the 20-microsecond pulse is desired, the "medium" position is used when the 4-microsecond pulse is desired, and the "broad" position is used when the 1-microsecond pulse is desired. Note that this labeling is just the opposite of what it would be if pulse lengths rather than band pass characteristics were used as a basis for the labels.
B. PPI Markers: This toggle switch introduces the A-scope range markers into the video input of the PPI Unit. This enables the operator to check the calibration of the PPI against the A-scope and thus insure that ranges to the same contact read on the two indicators will agree.
C. Echo box: switch: This switch energizes the echo box when it is desired to tune the receiver and no steady echoes are available.
D. IF Gain control: This controls the amplification of the receiver and hence affects both the amount of "grass" on the A-scope and the amount of' 'snow'' on the PPI scope. Since there is another gain control (video gain) (2-C) provided which affects only the "snow" on the PPI, the IF gain control should be adjusted for the proper amount of "grass" on the A-scope; and after this adjustment is made the video gain control should be set to give the proper amount of "snow" on the PPI. If any change in the amount of "grass" on the A-scope is subsequently desired, it will be necessary to readjust both the IF gain control and the video gain control.
The following five controls are located inside the door on the Receiver Unit and are marked A-J (anti-jamming) controls on the outside of the door.
E. Balance control: This control is used only when attempting to read through jamming. It is normally left fully counterclockwise.
F. IF tune control: This is the only control the operator will use in tuning the receiver. It is operative only when the 4- or 20-microsecond pulse lengths are being used. Tuning from the indicator console is not possible during use of the 1-microsecond pulse.
G. Time constant switch: Position one is used for normal operation of the set. The other two positions provide two different fast-time constants for use as an aid in reading through jamming and as an echo separator when tracking over land.
H. Rejection filter 1: An anti-jamming control.
I. Rejection filter 2: An anti-jamming control.
J. Jamming indicator: The meter normally reads 0.1 to 0.2 milliamperes. During jamming, the reading increases. The A-J controls are used to minimize the reading of this meter.
Control Unit.--K. Local control indicator light: When lit, this indicates that the operator may take control of the transmitter from the console by use of the controls on the control unit. If this light is not on, it will be necessary to turn the control switch on the transceiver to the REMOTE position before the console controls will be effective.
L. Transmitter on indicator light: When lit, this indicates that the set is in a stand-by condition.
M. Radiation switch: This switch controls the generation of high frequency energy in the transmitter. When the switch is in the counterclockwise position no energy is being generated.
N. Power-on button: This button energizes the plate voltage circuits in the transmitter as well as making power available to the console.
O. Power off button: This button removes plate voltage from the transmitter and power from the console.
P. Plate voltage raise button: This button allows the operator to raise the plate voltage applied to the transmitting tubes.
4-SR-3
Q. Plate voltage lower button: This button allows the operator to lower the plate voltage applied to the transmitting tubes.
R. Indicator console power switch: This switch applies power to the PPI Unit and Range Scope Unit.
IFF Coordinator Unit.--
S. IFF challenge switch: This puts the IFF system into operation from a stand-by condition.
T. IFF overload relay reset button: This will reset the overload relay of the interrogator connected with it. It is not found on all SR's.
U. Echo suppressor switch: This is used to suppress echoes appearing on the IFF time base at ranges less than 10 miles when tracking over land.
V. IFF receiver gain control: This controls the gain of the IFF receiver.
Panel #2
PPI Unit.--
A. Bearing marker dimmer:
B. Miles--The range scale indicator window.
C. Video gain control: This controls the amount of "snow" on the PPI, the strength of the echoes applied to the PPI, and the strength of the markers that may be brought from the range scope by means of switch (1-B).
D. Fine intensity control: This controls the intensity of the trace on the PPI and hence affects the sensitivity of the PPI.
E. Range selector switch: This switch selects one of the four operating ranges, 4, 20, 80, or 200 nautical miles. The range scale selected appears in the window (2-B).
F. Focus control: This adjusts the sharpness of the trace on the PPI.
G. Center expand switch: This throws the inner end of the time base outward about three-eighths of an inch from the center of the tube to allow bearings to be read easier on nearby contacts.
H. Markers control: This controls the intensity of the markers produced in the PPI unit. There are four such markers on each range scale.
I. Relative bearing indicator: This light glows when bearings on the PPI are relative and is out when they are true bearings.
J. Power switch for PPI unit:
K. AC: 115-volt outlet for maintenance purposes.
Panel #3
Range Scope Unit.--A. A-scope intensity control: This controls the brightness of the trace on the scope.
B. Vertical centering control: This controls the up and down position of the trace on the scope.
C. Markers switch for A-scope: This turns on the four range markers which appear as downward pips on each range scale.
D. Miles: This is the range scale indicator window.
E. Focus control: This adjusts the sharpness of the trace on the A-scope.
F. Horizontal centering control: This is used to align the zero range marker with the zero range mark printed on the glass over the scope face.
G. Sweep length control: This should be used to align the remaining three markers with the corresponding marks on the scale printed on the glass over the scope face.
H. Range switch: This switch selects one of the four operating ranges available. The four range scales are 4, 20, 80, 400 nautical miles.
I. Range step control: When this knob is pulled out, an offset appears on the A-scope trace coincident in range with the reading of the range counters. There is no range step on the 80- and 400-mile scales.
Bearing Indicator Unit.--
J. True bearing indicator light: This green light glows when true bearings appear on the left hand dial in the window on this unit.
K. Relative bearing indicator light: This red light glows when the left hand dial in the window is indicating relative bearing.
L. Slewing motor or antenna speed control: The middle position of this switch is OFF. Other positions of this switch rotate the antenna at l}i and iy2 or 5 r.p.m. clockwise or counterclockwise.
M. Emergency antenna rotation control: In case of a casualty to the servo-generator or associated devices this switch can be thrown from the NORMAL to the PPI or EMERGENCY position, and the antenna will rotate clockwise at about 6 r.p.m.
N. Hand slew control: This control allows the operator to rotate the antenna manually.
4-SR-4
Panel No. 4
Rotation Control Unit.--
A. Remote indicators switch: This must be in the ON position for remote indicators to be operative.
B. Synchro system--true relative bearing switch: On some SR's this switch is labelled OSC-AC. With the switch in the OSC or TRUE position, true bearings may be read from the bearing indicator and from the PPL If the gyro compass is out, the antenna will stall and remain still until this switch is thrown into the AC or RELATIVE position. In this position all bearings from the bearing indicator and PPI will be relative bearings.
C. Circuit breaker for antenna train motor: In case of a temporary or permanent overload of the antenna train motor, this breaker will cut off its power.
D. Circuit breaker for servo-generator motor: This breaker will protect the servo system from damage during a temporary or permanent overload.
E. Power light.
F. Power switch for Rotation Control Unit: When this switch is on, power is furnished the Rotation Control Unit and (E) is lighted.
TURNING ON AND OFF
Turning ON
Preliminary Checks
1. Synchro system switch (4-B) to OSC or TRUE.
2. Remote indicators (4-A) to ON.
3. Rotation Control Unit power switch (4-F) to ON.
4. Rotation switch (3-M) to NORMAL.
5. Slewing motor (3-L) to OFF.
6. A-scope intensity control (3-A) counterclockwise.
7. PPI video gain control (2-C) counterclockwise.
8. Fine intensity control (2-D) counterclockwise.
9. Center expand switch (2-G) to the LEFT.
10. Markers control (2-H) counterclockwise.
11. PPI Unit Power switch (2-J) to ON.
12. IF gain control (1-D) counterclockwise.
13. Echo box switch (1-C) to OFF.
14. PPI markers switch (1-B) to OFF.
15. Radiation switch (1-M) to OFF.
Applying Power
1. Press power ON button (1-N). If remote--local switch at the transceiver is in remote position, the plate volts indicator light will glow and the plate volts meter will read minimum voltages.
2. Check all fuse lights. No fuse alarm should be lighted. If any is lighted, replace the fuse with one from spares, making certain one of the same size is used in the replacement.
3. Throw radiation switch (1-M) to ON or LOCK.
4. Press the RAISE button on the raise--lower switch until the plate volts meter reads 11 kilo-volts.
Setting up the A-Scope
1. Turn up intensity control (3-A) until the line on the A-scope is about the same brilliance as the dot which appears at the beginning of the sweep and adjust the focus control (3-E) until the line is fine and clean. It may be necessary to readjust the intensity and focus controls together until the fine, clean line appears on the scope face.
2. Adjust the horizontal centering control (3-F) until the sweep or line starts at the zero figure on the glass over the tube face and adjust the vertical centering control (3-B) until the sweep is slightly above the zero figure.
3. Set the range switch (3-H) so that the numeral 20 appears through the small window indicated as miles (3-D) on the panel. This places the A-scope on the 20-mile range.
4. Turn the markers switch (3-C) to ON. Four markers should appear as vertical depressions in the sweep.
5. Adjust the sweep-length control (3-G) until each of the four markers falls behind a figure on the glass over the tube face.
6. Turn the range switch (3-H) to the 4-mile, 80-mile, and 400-mile ranges and make certain that the markers appear on all the range scales. They will not necessarily fall behind the numbers on the other ranges. Therefore it will be necessary to repeat step (5) above each time the range scale is changed during operation.
7. Pull out the range step control (3-1). A vertical break, or step, should now appear on the sweep if the range switch (3-H) is in the 4-mile or the 20-mile position. There will be no range step present when this switch is in the 80-mile or 400-mile position.
4-SR-5
8. Push the challenge switch (1-S) to the MOMENTARY position and hold it there a moment. A second trace should appear about three-eighths of an inch below the sweep on the A-scope face. If this second trace does not appear or is out of proper position, a technician should be called to adjust the IFF coordinator.
Setting Up the PPI
1. Set the slewing motor control (3-L) to the 1¼ position in either direction.
2. Set the range selector switch (2-E) to the 200-mile range scale as indicated by the numeral which appears through the small window directly above the switch labeled miles (2-B).
3. Turn up the fine intensity control (2-D) until a fine trace is barely visible on the scope face.
4. Adjust the fine intensity (2-D) and focus (2-F) controls alternately until the trace appears sharp and clear and just barely visible.
5. Turn up the markers control (2-H) slowly until four bright dots appear along the sweep on the face of the tube. These should be approximately equally spaced.
6. Throw the range selector switch (2-E) to the other three positions and check to see if the dots appear as above.
7. Leave the range selector switch (2-E) set on the range scale to be used and adjust fine intensity (2-D) focus (2-F) and markers (2-H) until the sweep is sharp and clear and the concentric circles traced by the markers are as narrow and clear as possible.
Turning off
1. Stop the antenna rotation about 3-5° away from 000° relative. At 000° relative bearing the PPI sweep is intensified to act as a ship's head marker. If the antenna is secured at that bearing the bright trace may do damage to the PPI tube face when the set is turned on and before the antenna is put into motion.
2. Turn down the A-scope intensity (3-A).
3. Turn down the PPI video gain (2-C) and fine intensity (2-D).
4. Turn down the IF gain (1-D).
5. Press the plate voltage lower button (1-Q) until the meter reads zero.
6. Press the power OFF button (1-O).
CALIBRATION
Calibrating the A-scope
1. Turn markers switch (3-C) to ON.
2. Set the range switch (3-H) so that the numeral 4 appears through the small window indicated as miles (3-D) on the panel. This places the range scope on the 4-mile range.
3. Adjust the horizontal centering control (3-F) until the sweep starts at the zero figure on the glass over the tube face and adjust the vertical centering control (3-B) until the sweep is slightly above the zero figure.
4. Adjust the sweep length control (3-G) so that each of the four markers falls behind a figure on the glass over the tube face.
5. Pull out the range step control (3-I) and rotate the range step handle until the break or range step just touches the left-hand side of the first marker. The range yards counters should now read 2,000 yards. Repeat this operation with the other markers. The counters should read 4,000, 6,000, and 8,000 respectively for these markers. All range counters should read correctly to within 100 yards on all marker points. If the range counters do not indicate to the required accuracy, a technician should be called to adjust the circuit.
6. Repeat the above steps for the 20-mile scale as selected by the range switch (3-H).
Calibrating the PPI
1. Turn the slewing motor control (3-L) to 1¼.
2. Turn the PPI markers switch (1-B) to ON.
3- Switch to the 20-mile scale on both scopes (2-E) (3-H).
4. Turn up the video gain (2-C) until four bright dots appear along the sweep on the face of the tube. These four dots will draw 4 concentric circles on the PPI and should be approximately equally spaced.
5. Turn up the markers (2-H) until four more bright dots appear along the sweep on the face of the tube. This second set of markers should produce concentric circles coincident with the others to within a mile.
6. Switch to the 80-mile scale on both scope (2-E) (3-H) and repeat steps 4 and 5 above. If the two sets of markers are found not to be coincident within the tolerance of 1 mile, a technician should be called to make the necessary adjustments. Under no circumstances should the operator attempt to make these adjustments.
4-SR-6
OPERATIONAL TECHNIQUE
Tuning the Receiver
The technician will have the transmitter tuned for maximum power output and it should not be touched by the operators. The duplexer, R. F. lines, pre-amplifier, and mixer are also tuned by the technician. The adjustments necessary for the operator to make are few and are outlined below:
1. Turn up IF Gain (1-D) until echoes appear or until there is some grass on the A-scope.
2. Switch to the 20-mile scale (3-H).
3. Operate IF tune control (1-F) for maximum echoes on the A-scope adjusting IF Gain (1-D) as necessary to keep the target from becoming saturated. Tune for maximum echo height by going a little over and then a little under maximum. Jockey back and forth rapidly stopping between the two points, a little over and a little under, for optimum tuning. When available, land echoes should always be used for tuning.
Assuming the Watch
When taking over the watch, the SR operator should make the following checks as soon as possible:
1. Check search procedure set-up.
2. Check the tuning of the receiver.
3. Check A-scope calibration.
Initial Contact Reports
Since the primary function of an air-search radar is served only when the antenna is in motion, operational technique should be such that the antenna is kept moving a maximum amount of time. The importance of this is generally under estimated, except by fighter director officers who have their own obvious reasons and by anyone else getting information from a remote PPL
Since most of the time lost is in reporting a new contact, a quick, efficient, and standard method of submitting an initial contact report is required. This should include:
1. Bearing.
2. Range.
3. Identification.
4. Composition.
5. Apparent relative movement (opening, closing, crossing) is possible.
On the SR the quickest way to obtain this information is to read the bearing and range from the PPI as soon as the target appears, without the use of the range step. With a little practice, almost anyone can read ranges from the PPI with facility and accuracy to within 1 mile using only the 20-mile markers as indicators. This is sufficient accuracy for an air-search radar. The bearing is obtained by merely splitting the target on the PP with the cursor. After the bearing and range are reported, the operator should stop the sweep under the cursor, adjust the IF gain (1-D) so that he can check composition on the A-scope, and check identification. Before reporting this information, he should put the set back into operation by adjusting the gain and starting the antenna rotating. He should then report. The total time the antenna is stopped normally should not exceed 20 seconds. The information will come to CIC in a manner similar to the following:
Combat, SR. I have a contact zero zero three, fifty-two. (Pause while interrogating, noting composition and relative movement.)
Bogie, three to five, crossing.
Thereafter, the good operator should obtain fixes from the PPI only, never stopping his antenna on that same target again unless it must be tracked over land.
When a contact has disappeared or is starting to disappear, the fade should be reported immediately and reappearance of a raid from a fade should be reported with the same promptness since this information can be a means of determining the approximate altitude of the raid.
Long Range Search
Searching for initial contacts at any range while striving for optimum performance of the radar to obtain these contacts at maximum range is the meaning of long-range search. It is conducted with or without indications being present on the scopes.
The range scale used on the scopes will depend on the tactical situation. In a carrier task force, initial contact at long range is highly desirable. Two methods of search are possible:
1. PPI on 80-mile range scale, and A-scope on 400-mile range scale, or
2. PPI on 200-mile range scale and A-scope on 80-mile range scale. Check the calibration when changing range scales on the A-scope.
When using the first method, most careful watch is made on the A-scope with an occasional search on the PPI.
4-SR-7
Method No. 2 indicates that the most careful watch will be maintained on the PPI with an occasional search using the A-scope.
Except when tracking over land, the PPI is used almost exclusively in giving target ranges and bearings to the plotter. Thus the advantage lies with method No. 1 since most tracking will be done within 80 miles. This can be done immediately since no change of scale on the PPI is necessary.
If the task force has no air support, 80-mile warning of approaching aircraft is sufficient, and both scopes may be operated on the 80-mile range.
The IF Gain or receiver gain (1-D) setting should be such as to give about one-fourth to three-eighths of an inch of grass on the A-scope at all times. The Video Gain control (2-C) should be turned up until there is considerable "snow" on the PPI, but not so high that a target which appears as a "cucumber," will be obliterated.
The 20-microsecond pulse width is the best to use on long-range search since targets will appear in greater thickness and can be detected at greater distance.
The antenna should be rotated at its slow rate--1¼ r.p.m. A plot should be started on the first indication no matter how weak the signal. Stop the antenna on the next sweep, study the blip on the A-scope for composition, and challenge the plane with IFF equipment. This pause in searching should consume as little time as possible.
Searching Over Land
When the radar is used for searching over land, target pips will be mixed with land pips and in many cases obliterated. Since planes give less steady echoes than land on the A-scope, these bobbing echoes can be followed through the land clutter somewhat readily. The PPI, of course, is almost valueless while tracking over land and should be used only as an auxiliary scope on a different range scale than the A-scope. Bearings cannot be obtained very accurately, but the bearing of maximum fluctuation of the pip on the A-scope should be reported.
It will be well to use the 20-mile range scale of the A-scope, leaving the PPI on the 80-mile scale. Use manual control of the antenna rotation; and since better definition is obtained with a shorter pulse, use the 4- or 1-microsecond pulse widths. The gain setting will be shifted as needed to reduce land echoes from saturation. When the Time Constant switch (1-G) is in one or the other of the two fast time constant positions available, echoes from land masses can be broken up to further enable the operator to see the bobbing moving pip produced by the plane.
The operator must remember to keep searching. He must not find one target and stay there from that time on.
Multiple-target Tracking
Multiple-target tracking must be done on the PPI. The 80-mile range scale will be found to be most suitable in most cases. When tracking targets over 40 miles in range, better performance will be obtained using the 20-microsecond pulse. In tracking targets closer than 40 miles, the advantage of better range definition makes the 4-microsecond pulse most useful. The antenna rotation speed should be increased to 2½ or 5 r.p.m. Report half the targets on each revolution of the antenna if the 2½ r.p.m. speed is the one available. Report half the targets for each two revolutions of the antenna if the 5 r.p.m. speed is available. The IF Gain (1-D) setting should be high--from one-fourth to three-eighths inches of grass on the A-scope. The Video Gain (2-C) should be high enough for plenty of "snow" on the PPI. All bearings are obtained by rotating the ring around the PPI until the cursor splits the target and then reading the bearing from the illuminated dial. All ranges are estimated from the PPI using the markers as guide. An experienced operator can estimate these ranges to within 1 mile.
Fire Control Liaison
Fire control liaison may be conducted on the 80-mile range with normal gain setting at about 10 miles, provided there are not many targets at the same range. When there are several targets on different bearings within 10 miles, their echoes and side lobes will ring the PPI and cause too much confusion for fire-control coaching.
When the primary interest is fire-control coaching, the PPI should be operated on the 20-mile range. The gain should
4-SR-8
greater than 20 miles, but is the most effective method when the primary purpose is fire-control coaching. At GQ, the stand-by operator can keep the fighter director officer informed of the general situation outside 20 miles by observing the range scope and taking ranges and bearings with continuous antenna rotation.
Composition
Determination of composition of the target requires more operator experience and closer observation than any other phase of operation. Determination of composition involves use of IFF to determine whether or not a contact is friendly, and observation on both range scope and PPI to determine number and size of planes in the group.
Large planes will have a low rate of fluctuation in echo amplitude, while small planes will have a high rate of fluctuation. The range scope is a better source of information on composition than the PPI. When a contact is made, the antenna should be stopped on the target, the gain reduced to one-sixteenth inch of grass on the A-scope, and a thorough examination of the echo made. The echo received from one plane will always be sharply pointed, and its shape will remain essentially the same. This is true of all types of planes. The echo from two or three planes will give a slightly rounded point with the top of the pip filled in so that it is brighter than the remainder of the pip and a somewhat wider base. Five to eight planes will have an echo pip with its peak showing two or more points. The top will be filled in and the base will be fairly wide. In all cases, the point is the telltale feature of the pip. Remember that the larger the flight, the larger the echo pip will be. Ten or more planes cause the top of the pip to become quite jagged. The pip may be filled in halfway down. Watch also for indication of a tendency for the echo pip to pull apart in several places. For large groups of planes, watch the break in the base line. This will tell the operator if the group is stacked (at various altitudes) or spread out at the same altitude. Remember to turn down the gain to see. The range at which the target comes in is not conclusive proof of either its size or altitude, but is a major factor contributing to these estimations. The operator should give his estimate of the composition of every contact and this estimate should be substantiated or corrected by visual means whenever possible. The operator should then be notified of the exact number, size, formation, and altitude. Continuous repetition of this process is the only means of improving the operator's technique in determining composition.
With the 20-microsecond pulse, all echoes will be larger than with the 4- or 1-microsecond pulses. Therefore, at first the tendency will be to overestimate when interpreting during use of the 20-microsecond pulse and to underestimate during use of the 4- and the 1-microsecond pulses.
Clouds, rain squalls, and ionized masses of air are readily detected on the A-scope, and are usually easily identified on the PPI. Broad fuzzy pips, that move slowly with occasional fading out, are characteristic of these targets, although sharp narrow pips have been observed. If identification is difficult by looking at the pip, a plot should be made to determine.
The broadcast of radio signals with the intent that our radar receive them, and that they show a confusing pattern on the screen, is called jamming. Use of dummy targets (tinfoil, kites, balloons, etc.) is called deception. More precise definitions are sometimes given, but these are satisfactory for this discussion.
The SR radar can be jammed, and it will show echoes from the tinfoil "window" which the enemy sometimes throws out to confuse the operator. The operator should not become alarmed when either of these things happen.
4-SR-9
The anti-jamming features of the SR receiver include two rejection filters rej 1 (1-H) and rej 2 (1-H), a receiver balanced video control--bal video (1-E) a fast time constant switch (I-G), and a jamming indicator (I-J). During normal operation the above controls should be to the left or all the way counterclockwise. The jamming indicator will read 0.1 to 0.2 milliamperes. In addition to these special controls the IF gain (1-D), IF tune (1-F) and the receiver band pass selector switch (1-A) (pulse length selector and therefore PRF selector) are extremely helpful in antijam technique.
To the uninitiated, sudden appearance of jamming on the scopes appears impossible to combat. It is not that serious if the following procedures are adhered to:
When jamming is first noted, the operator should not stop the antenna on the bearing from which the jamming appears to come. This would immediately reveal to the jammer that he was right on frequency and therefore effective. Instead, take the following steps:
1. Report the presence, intensity, bearing and any other information available while the antenna is rotating.
2. Request permission to attempt to "read through" the jamming. From this step on, the IF gain control (1-D) should be turned to various positions for the different tests tried.
3. Using the jamming indicator (1-J), operate the first and second rejection filters--rej 1 and rej 2 (1-H) (1-1) until the jamming indicator reads a minimum value, relative to one setting of the gain control.
Note: It should not be expected that a normal A-scope picture will be obtained. With close observation, the merest break or hook in the time base will be enough to reveal the bearing, range, and perhaps even composition of a target. The PPI is valueless when attempting to read through jamming of any appreciable intensity.
4. Try first one of the time constant switch (1-G) positions and then the other.
5. Operate the receiver Balance control (1-E) through its entire range using different settings of the rejection filter controls as well as the gain control.
6. Shift PRF.
7. Detune the receiver, first noting the original setting of IF tune (1-F), in order to reset it, should detuning prove ineffective.
8. If none of the above steps is effective, request permission to secure the transmitter by turning off the radiation switch (1-M) for a period of 2 to 4 minutes. Turning the set off informs the enemy that his jamming is effective and this should never be done unless there is sufficient reason to believe the enemy already knows he is effective. Turning off the transmitter might also lead the enemy to believe that your set is secured and that you have given up. At the end of the silent period^ with the antenna trained on the last known bearing of the jamming, turn the radiation switch (1-M) back on in the attempt to pick up the source of the jamming before the enemy realizes the transmitter is back on the air. Under no circumstances should the operator secure the radar for more than the 2 to 4 minutes prescribed.
The reason for obtaining a bearing on the jamming is to determine whether or not it could be accidental interference instead of jamming. Jamming will not only be directional, but its true bearing will not be changed by any sudden change in your ship's course. Interference originating aboard your own ship will either be nondirectional and appear on all bearings, or else it will always be on some certain relative bearing regardless of changes in own ships' course.
Moving the gain control up and down is probably one of the most important countermeasures to be taken and the the jamming but it is possible to obtain the desired information. The extra effort is worthwhile because the enemy would not be jamming unless he were trying to conceal something important".
Two general methods of using the gain control, both of which should be tried, are as follows:
(a) Reduce the gain: This prevents overload of the radar receiver; echoes are visible "riding on top" of the jamming pattern.
(b) Increase the gain: This limits (or clips) jamming; echoes are visible as a break in the base line.
4-SR-10
Be sure to return all controls to their normal setting when no jamming is present. The gain control must be returned to normal every time the antenna is turned to an unjammed bearing.
Perseverance is a particularly valuable quality in operational technique when attempting to "read through" jamming. The effectiveness of the jamming may change from time to time, and if you persevere some of the information may be obtainable. The necessary information may be presented on the scope for only a few seconds. Alertness and close observation will make these few seconds valuable. A point to keep in mind is that the echo signal strength of the jamming ship or aircraft increases faster as it closes than does the strength of the jamming signal.
PERFORMANCE
Maximum ranges obtained on planes will vary greatly with the altitude of the plane, because of fade areas and the curvature of the earth. Large, high-flying planes have been observed at 130 miles. Average ranges on medium altitude planes are from 70 to 90 miles, and on low-flying planes, from 25 to 40 miles.
Maximum ranges on surface targets will vary with antenna height, size of the target, and weather conditions. In most cases, the maximum ranges will be 6,000 to 10,000 yards less than those obtained on the same targets with surface-search gear.
Maximum Reliable Range
Minimum Range
Accuracy
Reading directly from the PPI, range accuracy is ±2,000 yards or better, and bearing accuracy ±2°.
Range accuracy is dependent on the pulse length chosen. Listed in the table below are range accuracies, for the A-scope for the three possible pulse lengths:
Resolution
TROUBLES
1. Transmitter kicking out: This may occur due to jar of gunfire or surge currents. Sweep traces will disappear from both scopes, the transmitter plate voltage meter will read zero and the transmitter ON indicator light (1-L) will go out. After some time, the light (1-L) will go back on. When this occurs, press the plate voltage Raise button (1-P) until the meter reads 11 kilovolts.
2. IFF interrogator kicks out: This trouble is recognized by lack of the IFF transmitter pulse and grass on the IFF time base. Press the relay reset button (1-T) which is installed in the IFF panel on some SR's. On gear not having this control, it is necessary to go to the interrogator itself.
3. Servo-generator motor circuit breaker (4-D) operates automatically to OFF: When this trouble occurs, the antenna, the sweep on the PPI, and the bearing dials will stop. Operate rotation switch (3-M) to the PPI on EMERGENCY position.
This will give an antenna rotation of 6 r.p.m. clockwise with no speed control and no manual train control. Notify the technician.
4. Antenna train motor circuit breaker (4-C) operates automatically to OFF:
When this trouble occurs, the antenna, the PPI sweep and the bearing dials will stop. Notify the technician immediately. There is now no way of training the antenna until the trouble is corrected.
A second type of trouble, that producing a gradual decrease in the operating efficiency of the set, is much harder to detect. The operator must be on the lookout for this second type of trouble at all times. One indication can be the point to which the IF gain control and video gain control must be
4-SR-11
turned to get the normal amount of grass. A knowledge of the "par" range reading of the echo box will aid in detecting a gradual decrease in operating efficiency. The best indication is the ranges that are being obtained on objects with which the operator is familiar, such as ships in his group or land in the vicinity. If poor results are being obtained, the operator may try retuning. If this does not help, the maintenance man should be notified.
On all troubles, the operator can greatly assist the technician by giving a true and accurate description of what happened on the scope when the set went out of operation. This is especially true of intermittent troubles.
4-SR-12
SP RADAR
SP RADAR
UNITS OF THE CONSOLE (Fig. 4 SP. 1)
1. IFF Coordination Unit.
2. Power Control.
3. Indicator.
4. Plan Position Indicator.
5. Range Unit.
6. Radar Receiver Unit.
7. Main Power Unit.
8. Precision Alignment Unit.
9. Auxiliary Power.
10. H. V. Power Unit.
IDENTIFICATION AND DESCRIPTION OF CONTROLS AND INDICATORS ON THE CONSOLE
1. IFF Coordination Unit
1A. "A" band High Voltage Indicator (yellow).-- When lit indicates that the "A" band is actually challenging a target.
1B. "A" band Tower Reset Push Button.--When pressed in the high voltage overload relay is held in.
1C. "A" band Power Control.--Varies the amount of high voltage supplied and thus the strength of the challenge signal. If 1A goes out during challenge, turn 1C down, press 1B and return 1C to desired position.
1D. Panel Light.
1E. Height Computer Meter.--Solves the altitude (above the surface) at which a target would be at the range indicated by the Coarse and Fine Range Dials having an angle of elevation from the set indicated by the elevation dial. Some sets have a circuit which also solves earth's curvature error and adds this to the meter's reading automatically. Note: Switch 5C must be in position 1 (height) to make meter active.
1F. Panel Light Variac.
1G. Relative Bearing Dial.--Indicates by the arrow the direction of the antenna with respect to ship's heading (ship's heading being at top of dial). The relative bearing is read in degrees on the dial at the top.
1H. "G" band High Voltage Indicator (yellow).
1J. "G" band Power Reset Push Button.
1K. "G" band Power Control.
4-SP-1
Figure 4 SP-1. Schematic SP console.
4-SP-2
1L. A" band Power Switch.--When on, the "A" band interrogator is ready to start challenging.
1M. "A" band Receiver Gain Control.--Controls the gain of the IFF receiver.
1N. "A" band Echo Suppression.--When on, suppresses echoes from large nearby targets for the first 12 miles on IFF sweep.
1P. "A" band Challenge Switch.--When "ON" the "A" band interrogator is challenging as long as the switch is held. When on "LOCK ON" the "A" band interrogator is challenging continuously.
1Q. Selector Switch.--Gives "A" band return on "A" scope IFF trace and "G" band on PPI trace or "G" band return on "A" scope IFF trace and "A" band on PPI trace.
1R. "G" band Challenge Switch.
1S. "G" band Echo Suppression.
1T. "G" band Receiver Gain Control.
1U. "G" band Power Switch.
2. Power Control Unit
2A. Relative Bearing Indicator (red).--When lit, indicates antenna is operating on relative bearing. When out, indicates antenna is operating on true bearing.
2B. Relative--True Bearing Switch.--Causes antenna to operate on relative or true bearing.
2C. Panel Light Variac.
2D. Modulator Primary Voltage Meter.--Indicates input voltage used in the modulator unit. Regulated to give proper Oscillator Current. Range 90 to 110 volts.
2E. Panel Light.
2F. Oscillator Current Meter.--Indicates plate current of R. F. oscillator. Range 25 to 30 ma.
2G. Line Voltage Meter.--Indicates input voltage to the set. Range 115 to 120 volts.
2H. Overload Indicator (yellow).--If 2Y is in normal position 2H will light if overloads exist in one of ten different motors or generators used to control the antenna.
2J. Transmitter Filament Indicator (green).--When on, indicates R. F. oscillator filaments are hot.
2K. Stable Element Indicator (green).--When on, indicates stable element is being supplied with power.
2L. Pedestal Control Indicator (green).--When on, indicates antenna is being supplied with power.
2M. Modulator Indicator (white).--When lit, modulator is in operation.
2N. Stand-By Indicator (yellow).--When lit, indicates transmitter is ready to go.
2P. Radiate Indicator (red).--When lit, transmitter is in operation.
2Q. Scanner Motor Indicator (green).--When lit, scanner or wobbler is in operation and Precision Scope is ready to receive signals.
2R. Azimuth Tell-Tale (white).--When lit, error exists between the actual and indicated antenna position.
2S. Elevation Tell-Tale (white).--When lit, error exists between the actual and indicated antenna elevation.
2T. Cross Level Tell-Tale (white).--When lit, error exists between the cross level position of the antenna and the stable element.
2U. SP Radar Start-Stop Switch.--Controls the main power source to the set.
2V. Modulator Primary Voltage Control.--Raises or lowers the input voltage to the modulator and is adjusted to give proper Oscillator Current.
2W. Radiate--Stand By Switch.--Thrown up, the switch puts transmitter in operation. Thrown down, puts transmitter in stand-by.
2X. Scanner Motor Switch.--When on, the scanner is operating and the precision scope is ready to receive signals.
2Y. Overload Selector.--When in "NORMAL," it will detect an overload in any of 10 units (listed on the switch) by lighting 2H. Specific unit is indicated by turning switch until 2H stays lit in 1 of 10 positions--each position being one of the units.
3. Indicator Unit
3A. "A" Scope.
3B. "R" Scope.
3C. Echo Range Timebase (upward deflection).
3D. IFF Range Timebase (downward deflection).
3E. Echo Range Timebase.
3F. Ditch or Short Gate.
3G. Test Jack.--Allows use of "A" and "R" scopes for oscillographs when 3M is in position 3.
3H. "A" Intensity Control.--Controls brightness of time trace.
3J. "A" Horizontal Control.--Controls right and left movement of time trace.
3K. "A" Vertical Control.--Controls up and down movement of time trace.
3L. "A" Focus Control.--Controls sharpness of time trace.
4-SP-3
3M. Selector Switch.--Position 1: Places IFF time trace on "A" scope. Position 2: Places IFF time trace on" A" and " R" Scopes. Position 3: Allows "A" and "R" scopes to be used as test scopes with 3G. Allows calibration markers to be presented on "A" and "R" scopes.
3N. "JR." Intensity Control.
3P. "R" Horizontal Control.
3Q. "JR" Vertical Control.
3R. "H" Focus Control.
4. Plan Position Indicator Unit
4A. L. 0. Tuning Control.--Adjusts local oscillator frequency (tunes the receiver) and is operable only if 4M is in the "MANUAL" (down) position.
4B. PPI Screen Illumination Control.
4C. Dial Illumination Control.
4D. Antenna Control.--Controls the speed and direction of revolution of the antenna.
4E. PPI Focus Control.
4F. PPI Scop.
4G. Precision or Target Alignment Scope.--Receives signals only when scanning motor is on.
4H. Etched Cross-hairs.--Used to align the winged dot.
4J. Winged Dot.
4K. PPI Intensity Control.
4L. Video Gain Control.--Varies the level or strength of echo necessary to cause a visible signal to appear on the PPI screen.
4M. AFC Switch.--Changes control of local oscillator frequency from "MANUAL" (down), for which 4A is used, to "AUTOMATIC."
4N. Dial Lights.
4P. Elevation Handwheel and Dial.--Controls elevation of antenna. Dial calibrated in degrees.
4Q. PPI Pattern Selector.--
Position 1--"Range Mark." Places a strobe on the sweep at the range of the ditch on the "R" scope.
Position 2--"Normal." Places the normal sweep on the PPI with zero range at the center.
Position 3---"Delayed." Makes the center of the scope the range of the ditch on the " R" scope and makes the sweep length that indicated by 4R.
4R. PPI Range Selector.--Provides successive ranges of 4, 20, 50, 100, and 200 miles for the PPI sweep.
4S. Bearing Handwheel and Dial.--Controls azimuth position of antenna and indicates in true bearing.
4T. PPI Markers Switch.--Provides range marks at 1-, 5-, 10-, 20-, 50-mile intervals for the 4-, 20-, 50-, 100-, and 200-mile sweeps.
5. Range Unit
5A. Dial Illumination Control.
5B. Dial Lights.
5C. Crystal Check Switch.--
Position 1--"Height." Switches height meter into the height circuit.
Position 2--"Crystal Current." Height meter indicates the mixer crystal current. 1 ma. d.c. full scale.
Position 3--"Forward Resistance." Height meter indicates forward resistance of mixer crystal (ohms).
Position 4--"Backward Resistance." Height meter indicates backward resistance of mixer crystal (ohms).
Position 5--"Meter Zero." Permits height meter to be zeroized by 5F.
5D. Notch or Ditch Width Control.--
5E. Coarse Range Handwheel and Dial.--Calibrated in 5 mile steps, moving strobe in 5 mile jumps on "A" scope and placing indicated 5 miles on "R" scope.
5F. Meter Zero Adjust.--Zeros the height meter when 5C is in position 5.
5G. Fine Range Handwheel and Dial.--Calibrated to 0.02 miles over a five-mile range, moves notch over five-mile range of "R" scope. Actual range of notch is sum of coarse and fine range dials.
5H. Range--Bearing Remote Read Alarm.--Used to signal remote stations to read range and bearing when suitable system has been installed.
5J. Coarse Range Zero Adjust.--
5K. Coarse Range Rate Adjust.--With 5J, used to adjust coarse range circuit to proper calibration with aid of marker pips.
5L. Calibrate--Operate Switch.--
Position 1--"Calibrate." With 3M in position 3 throws markers pips on "A" and "R" scopes at one mile intervals beginning at zero miles.
Position 2--"Operate." Normal position for regular operation.
5M. Fine Range Zero Adjust.--
5N. Fine Range Rate Adjust.--
6. Radar Receiver Unit
6A. Cloud Suppressor Switch.--When on, introduces a special circuit into receiver by which targets
4-SP-4
wide in range are attenuated, enabling strong ship or plane echoes to be seen through the interference.
6B. Wings Level Control.--Sets the level of strength which an echo must have to cause wings to appear on moving dot of precision scope provided echo is in " R" scope notch. Control must be set so that grass will not activate wings after control 6C has been set.
6C. Main Gain Control.--Controls gain of radar receiver. 6B must be adjusted after 6C has been set.
6D. Pulse Length Control:--Set on "1" or "5" for modulator "A" or "B" respectively.
6E. AGC Level Adjust.--Adjusts sensitivity circuit of precision scope for proper operation.
6F. Gain Balance Adjust.--Adjusts gain of receiver for use with modulator "B" to achieve same sensitivity as when used with modulator "A."
7. Main Power Unit
7A. Rectifier Current Meter.--Reads the current supplied by the power unit. Range 0.6 to 0.7 amps.
7B. Battle Short Indicator (red).--When lit, indicates that protective interlocks of console are shorted out.
7C. Power Fuses.--
7D. Plate Power Switch.--When on, power is supplied to the main power unit.
7E. Plate Voltage Indicator (red).--Indicates main power unit is operative when on. Switches 7D and 7H must be on.
7F. Battle Short Switch.--In "ON" position switch shorts all interlocks of console.
7G. Console Power Indicator (yellow).--When on, indicates console tube filaments are lit.
7H. Console Power Switch.--In "ON" position furnishes power to all console tubes.
7J. Filament Fuses.--
8. Precision Alignment Unit
8A. Horizontal D-C Balance Adjust.--Centers spot right and left on precision scope (6C must be in extreme counterclockwise position).
8B. Vertical D-C Balance Adjust.--Same as 8A but for vertical centering.
8C. Horizontal A-C Balance Adjust.--Used to balance spot horizontally to center with scanner motor on (switch 2X). 6C and 6F in normal operation position and no echo in the notch.
8D. Vertical A-C Balance Adjust.--Same as 8C but for vertical balance.
9. Auxiliary Power Unit
9A. Fuse Blowout Indicators (neon).--When lit, fuse below neon light is blown.
9B. Power Fuses.--
9C. Voltage Adjust.--200-volt Power Supply.
9D. 200-volt Supply Voltage Meter.--This meter must be kept exactly at 200 volts.
9E. 300-volt Supply Voltage Meter.--This meter must be kept exactly at 300 volts.
9F. Voltage Adjust.--300-volt Power Supply.
9G. Local Oscillator Switch.--In "ON" position the local oscillator is connected to the oscillator-preamplifier.
9H. Local Oscillator Indicator (red).--When on, indicates 9G has completed circuit.
9J. Spare Fuses.--
10. High Voltage Power Unit
10A. Scope Plate Voltage Indicator (red).--When on, indicates scopes are operative.
10B. Scope Plate Voltage Switch.--With 7D and 7H "ON" switch will apply high voltage to scopes on console.
10C. 115-volt AC Convenience Outlet.--
10D. D-C Convenience Outlet (ship's supply).--
10E. Heating Unit Indicator (yellow).--When on, heaters are lit.
10F. Heating Unit Switch.--In "ON" position switch will energize heaters when 7D is "OFF".
TURNING ON AND OFF
The antenna unit, mounted on the mast, has three mechanical "stow" controls, (1) elevation, (2) azimuth, and (3) cross level. The antenna must be stowed and unstowed only by an experienced person. The operator must ascertain that the antenna unit is ready for remote control from his console before turning the set on. Azimuth, Elevation, and Cross Level Telltale Indicators (2R, 2S, 2T) will flash on if controls are turned away from true position of antenna.
Turning on SP RADAR
1. Throw bulkhead switches admitting ship's power to entire set. Usually the stable element is energized from the same switches.
2. Determine whether you are to use the "A," CG-35ABD (serial 1) 600 cycle, 1-microsecond or the "B" CG-35ABE (serial 2) 60 cycle, 5-micro-second modulator.
4-SP-5
3. On the console turn Pulse Length (4D) to "1" for modulator "A" or "5" if using modulator "B."
On transmitter unit close transmitter "ON-OFF."
On modulator close modulator" ON-OFF."
On console hold "STOP-START" switch (2U) on "START" for three seconds.
The following events will occur.
Line Volt Meter (2G) will indicate.
Illumination Lamps 1D, 2E, 5B, and 4N "on."
White Modulator Indicator Lamp (2M) " on."
Green Stable Element (2K) and Green Pedestal Power (2L) "on."
Green Transmitter Filament (2J) "on."
Sixty seconds later, Yellow Stand-By (2N) "on." Identical indicators on modulator and transmitter units.
4. On console turn Console Power Switch (7H) "ON." White Lamp (7G) "on."
Close Plate Power Switch (7D). Red Lamp (7E) "on."
Close Local Oscillator Switch (9G). Red Lamp (9H) "on."
Close Scop Plate Power Switch (10B). Red Lamp (10A) "on."
Heater Switch (10F) is left "ON" at all times. Energizes automatically when set is secured.
Meters (9C) and (9D) must be set accurately at 200 volts and 300 volts respectively.
5. Throw Radiate Stand-By (2W) to "RADIATE." Red Lamp (2P) "on." Identical indicators on modulator and transmitter units.
6. Operate Raise-Lower (2V) to obtain correct reading on Oscillator Current Meter (2F). Modulator Primary Voltage Meter (2D) indicates rise or fall. Identical controls on modulator and transmitter units.
IFF Gear
at the "A" Band Interrogator
1. Main Power Switch on outside panel is turned "ON."
2. Power Switch on inside panel is turned "ON."
3. Sync Switch is turned to "EXTERNAL." High Voltage Toggle Switch turned "ON."
R. F. output should be turned to maximum (control at console will vary output). Other controls left as technician has set them.
4. Main door on gear must be closed.
At the "G" Band Interrogator
1. Steps to turn on exactly the same as above for "A" band interrogator.
At the Console, "A" band Interrogator
1. " A" Band Power Toggle (1L) to " ON."
2. Selector Switch (1Q) to the " BM-A Scope" position.
3. "A" Band Challenge Switch (IP) set to "lock on" or "key" as desired will start the IFF to challenge. Yellow Lamp (1A) "ON." NOTE: If yellow lamp does not flash on during challenge, turn "A" Band Power Control(1C) extreme counterclockwise. Press Reset Switch (IB) and turn 1C clockwise to desired output level. Call technician if this reset procedure will not work.
4. Adjust Receiver Gain (1M) clockwise to desired IFF return level. NOTE: The IFF Time Trace should appear about ¼ inch below the range time base. This can be adjusted by the technician from an inside control.
At the Console, "G" Band Interrogator
1. A similar set of control is available on the unit for "G" band control and are labeled correspondingly.
Placing the Gear in Ready Stand-by Position
SP RADAR
1. Throw Radiate Stand-By (2W) to "STANDBY."
2. Throw Scop Plate Power (7D) to "OFF."
3. Secure antenna at usual bearing (dead ahead). Do this by throwing Relative-True Bearing Switch (2B) to "RELATIVE" and rotating antenna to 000 on Relative Bearing Dial (1G). Red Lamp (2A) will be "on" as long as antenna is cut into Relative Bearing.
IFF Gear
1. Throw Challenge Switch (IP) and (1R) to "OFF."
2. Throw Power Toggle (1L) and (1U) to " OFF."
Placing the Gear in Complete Off Position SP RADAR
1. Reverse steps 5, 4, 3, and 1 in order. See Turning On SP Radar. IFF Gear
1. Throw Power Toggle (1L) and (1U) to "OFF" on console.
2. Throw Height Voltage Toggle and Main Power Toggle on inside panel of "A" and "G" band interrogators to " OFF.
3. Throw Main Power Switch on outside panel of "A" and "G" band interrogators to "OFF."
4-SP-6
Emergency Off
1. Push SP Radar Stop-Start Switch (2U) to "OFF." This will shut down console, modulator and transmitter units.
CALIBRATION
Calibration of the SP Radar scopes must be done by an experienced and qualified person. This person will be, except under unusual circumstances, a technician. The operator, however, should know how to check the calibration and do so each time the watch is relieved.
Checking the Calibration.--fine Range "R" Scope
1. Throw Calibrate-Operate Switch (5L) to" CALIBRATE" and Selector Switch (3M) to position 3. (Be sure Stand-By Radiate Switch (2W) is at "STAND-BY"). Marker pips will appear on "A" and "R" scopes. "R" scope will have 7 pips at one mile intervals, the first pip being at zero range.
2. Rotating Fine Range Dial (5G) each pip should coincide with leading edge of ditch as "whole" miles are brought to Fine Range Indicator. (If the pips are more than 0.1 mile off a balance of adjustments must be made between 5M and 5N, fine range adjusters. A technician should do this).
Coarse Range "A" Scope
1. The "A" scope will have pips at 1 mile intervals on its 100 mile range. To check, start Coarse Range Dial (5E) at zero and watch the strobe (bright dot) jump 5 pips (about ¼inch) on the time trace each time the dial is moved one "5-mile" click. Go through entire range. (If strobe light on trace fails to jump at any time or if the trace on the " R" scope disappears on one of the Coarse Range settings, a balance of adjusters 5J and 5K is necessary).
2. To secure calibration circuit return Calibrate-Operate Switch (5L) to "OPERATE" and Selector Switch (3M) to position 1.
PPI Scope
Coarse and fine range calibrations must be checked first as above.
1. Throw Markers Switch (4T) "ON" and PPI Pattern Selector Switch (4Q) to position 1--Range Mark. The markers will appear every 1, 5, 10, 20, 50 miles on the PPI sweep for its ranges of 4, 20, 50, 100, and 200 miles respectively. The range mark or strobe will appear at the range indicated by the sum of the Fine and Coarse Range Dials.
2. Set PPI Range Selector Range Switch (4R) to "50." Set strobe to 10 miles and rotate antenna. Marker and strobe should coincide and trace coincident circles. Check 20-, 30-, 40-, and 50-mile markers the same way. (If trace must be adjusted, the technician will have to do this with adjustments located behind the panel).
OPERATIONAL TECHNIQUE
Tuning the Receiver.--Controls
The operator has two controls to perfect his picture on the scope after proper brilliance, focus and centering have been set. These are Main Gain Control (6C) and L. O. Tuning (4A). If echoes will not appear on adjustment of these controls, the technician will have to make adjustment at the transmitter itself. The AFC Switch (4M) must be set to "MANUAL" (down) when using 4A.
Tuning
Using the Land Echo.--Turn to bearing of land and set Main Gain (6C) so grass is at least one-eighth inch high but not more than one-fourth inch. Then tune L. 0. Tuning (4A) for a compromise between maximum echo height and maximum width of echo on the time base.
Using the Ship Echo.--Tune as normally on any moving target. Attempt to get a maximum echo return watching the pip over a period of a minute or so.*
Using Sea Return.--Tune on the "R" Scope with Coarse Range Dial at zero range. Tune L. O. Tuning (4A) for maximum width of sea return as well as maximum height.*
No Echo or Sea Return.--Have technician tune the built-in echo box at.the transmitter for proper setting leaving the echo probe in the "IN" position. Elevate antenna so that no sea return appears at zero range. Tune L. O. Tuning (4A) for maximum width of no grass at the zero range. See figure 4SP-2. The Echo Box, tuned to the transmitter, gives a negative echo of transmitter frequency to the receiver. Thus, the receiver can be tuned to the transmitter by using this echo which is generated each time the transmitter pulse excites the Echo Box.* Set probe in "out" position.**
* Note on operating with Automatic Frequency Control: If radar has modification for automatic frequency control circuit always return AFC switch to "Automatic." If not, leave on "Manual" position. Sets installed after Jan. 1, 1945, have this modification.
** The Echo Box probe should be left in the "Out" position to insure the best minimum range the set is capable of getting. (See Performance.)
4-SP-7
Operating the Set.--General
Two operators are required at the console. The PPI and the "A" operators.
The principal duties of the PPI operator are to observe the PPI pattern, to control the antenna in elevation and bearing by means of the Elevation and Bearing Handwheel, and to observe the Precision or Target Alignment Scope when aligning the antenna on a target.
The principal duties of the "A" operator are to control the position of the ranging notch or ditch on the "R" scope, and consequently the strobe on the "A" scope by means of the Coarse and Fine Range Handwheels, to read the height meter, and to operate the IFF units.
SP will detect a target through two general types of operation: (a) detection by continuous search of aircraft at low angles from the horizon, and ships, depending upon antenna height above the water, weather conditions, size of target and the limiting factor-power of the set; and (b) detection of aircraft at high angles from the horizon depending upon adequate "coaching" by information from other detectors designed for such search and, again, weather conditions, size of target, and power of the set.
Detecting the target is the first part of the process. Obtaining a "fix" is the second step, which in the case of the SP is complicated by the attempt to fix in three dimensions: bearing, range, and elevation.
The ultimate performance depends upon the operators' sensible analysis and use of the controls at their disposal for presenting the target information for correct interpretation. The necessity for team work will be at once apparent when the operators attempt to do this together.
The third step is a matter of policy depending upon the situation: The tracking of the target to the exclusion of other radar duties; or the periodic fix of the target between searches for new information at low angles and on the surface. The first choice is an extremely dangerous practice and the operators should never take it upon themselves to make this choice. The second choice should be taken automatically unless given specific instructions otherwise.
Special tasks will arise. Operation for the more important of these are discussed below.
Figure 4 SP-2.
Detecting the Target--Continuous Low Angle and Surface Search
Adjustment of the Radar.
Antenna Elevation.--Zero to -30 minutes. The beam should clear the horizon at the surface of the sea and thus beam its energy out into space providing coverage of low angle and surface at a maximum possible distance. Experience with the radar aboard your own ship will find the best antenna position.
Antenna Sweep.--360 degrees to provide complete coverage of the area about the ship. The low angle attack by plane or approach by fast force may be launched from any azimuth depending upon such factors as enemy speed, strength, location of base, sun, weather, cloud coverage, etc.
Antenna Speed.--About two to three revolutions per minute. The sweep must be fast enough not to allow the approach of high speed targets over a large distance between sweeps of the approach area. It must be fast enough to keep a pattern on all azimuths of the PPI and, yet, slow enough to get readability from the "A" and "R" scopes. Too much speed combined with the narrow beam will cause the targets to "flash" on and off the "A" and "R" scopes so rapidly as to be missed.
Gain Used.--Optimum gain level is obtained with between one-eighth inch to one-fourth inch grass on the "A" and "R" scopes. (Main Gain Control
4-SP-8
6C.) Adjustment of the PPI Intensity (4K) and Video Gain (4L) is made to obtain a clearly defined sweep that seems "jeweled" as it rotates. Focus, brightness, and position of the time traces on the "A" and "R" scopes should be adjusted with controls 3H, J, K, L, and N, P, Q, and R.
Range Scale.--The 100 mile range is used in general search. The SP is provided with a 200 mile sweep on the PPI (the "A" scope has only one sweep length, 100 miles) but cannot be used unless the "B" type modulator is provided and cut into operation. The repetition rate of the "A" modulator allows only a little over 100 miles between transmitter pulses. Refer RADTHREE-Continuous and Discontinuous sweeps, page 1-36.
Watching the Scope.--The "A" and PPI operators must assume a conscious alertness to searching the time trace with their eyes. Don't get into the habit of starting at one spot on the scope. The strobe mark should be carried on the "A" scope at zero range if there is any tendency for the operator to find himself staring at the strobe.
High Angle Search
The narrow beam of the SP precludes the use of any general air search technique. Covering the entire vertical area on all azimuths about the ship will take too long and never give adequate protection. In addition, the power of the SP radar is not sufficient to guarantee protection at the great distances demanded in the combat task force. The long range air search sets must take care of this function.
High Angle Search with Coaching
Information of range and bearing and a rough altitude guess will come from the air search gear. To detect the target, rotate antenna to bearing and move the range notch to range. (The height meter used to estimate the altitude of your beam at a given range is useless unless the range notch is set at that range.) Elevate antenna using meter to indicate the altitude of your beam, at the range of the notch, and make at 15° to 20° bearing spread.
If you fail to pick up the target, a search in elevation must be made as well as in bearing. The design of the antenna allows this to be done quickly and systematically. The antenna throws a small cone of energy the vertical width of which is enough to cause the energy to be spread over a substantial altitude at any distance from the set. Remember this rule: At ranges greater than 25 miles the antenna can search in elevation in jumps or levels of 5,000 feet; at ranges less than 25 miles the antenna can search in elevation in jumps of 2,500 feet. --With the one requirement, that the range strobe on the "A" scope is set at the expected range of the target. If the set is operating normally, this procedure will provide plenty of overlap in vertical search. (See fig. 4SP-3.)
An experienced operator can make a bearing search at a given altitude and range in 5 seconds. Thus, a target at 040-35, say, and with no altitude information would be detected at any altitude up to 30,000 feet in 6 sweeps or 30 seconds.
Changes of the average bearing and range must be made constantly as new air search data comes in. The constant adjustment plus the coordination of bearing and elevation change to accomplish a through search require practice and teamwork.
Having detected a target the second step, obtaining the fix, is begun.
Obtaining the Fix
Several additional controls come into use at this time. The function and adjustment of these controls is described here.
The Scanner.--The energy of the set is piped to the parabolic reflector on the mast and much like the light in a car headlight focused and projected into space as a cone. The nozzle which projects this energy to the parabola is mounted on an eccentric rotating device which will cause the nozzle to make a very small looping motion about the center line, the perpendicular to the antenna face. The energy is thus slightly" cocked" off the center line. Where before the maximum energy of the cone was straight down the center line, it is now making a tiny loop about this line.
It will occur to the operator that this cone of energy might detect a target more quickly, since it is larger, than the straight shooting cone. Practically this is not so as the increase is too small to have that effect. The scanner operates at high speed and should be used only when the precision fix is desired. This is a common sense rule designed to save undue wear of the mechanical parts of the scanner system.
4-SP-9
Figure 4 SP-3. "Overlap of radar cone searching in elevation in 5,000 feet jumps at 25 miles.
Precision Scope.--When the scanner is turned on, the precision scope and the circuit feeding it are also energized. This circuit compares the echo strength received from a target when the cone of energy is in four positions in relation to the center line: "UP," "RIGHT," "DOWN," "LEFT." See figure 4. Realize that no signal goes to the precision scope at any other time although the cone does make a complete loop.
The "UP" and "DOWN" echo strengths are compared and a net signal applied to the vertical deflection plates of the precision scope. The "RIGHT" and "LEFT" signals are compared and the net signal applied to the horizontal deflection plates. If the "UP" is equal to the "DOWN" and the "RIGHT" is equal to the "LEFT," the dot will stay in the exact center. If one signal is bigger than its mate, the dot will be deflected. Refer RADTHREE--Structure of the Electrostatic Cathode Ray Tube, page 1-30. It is important to realize that the circuit is connected so that if the dot moves to the right and up, you turn the antenna to the left and down--the same way the dot must move to return to Center. The antenna center line is pointed precisely at the target whenever the dot returns to the exact center of the scope.
The Wings.--In order that the operator will know that he has a target on his precision scope a further restriction is placed on the circuit which feeds the precision scope. The "A" operator must place the detected target in his notch, or ditch, on the "R" scope. As long as the target remains in the notch the precision circuit has a
Figure 4 SP-4. 1. Precision circuit receives target only in four positions of cone. 2. Precision scope gets "net" signal from "up-down" and "right-left."
4-SP-10
target to work on. Further the operators will know which target is being aligned. In order to provide an instant and constant warning to the PPI operator that he does or does not have a target on the precision scope, "wings" are caused to appear on the dot when a target is in the notch. Before using the precision circuit the main gain of the receiver (6C) must be set at the proper level and the Wings Level Control (6B) adjusted so that the grass or noise will not cause the wings to appear on the dot when the "R" scope notch is empty. See figure 5.
Figure 4 SP-5 Wings level and main gain adjusted properly.
The Height Computing Meter.--See figure 6. The Height Meter is a computer which solves for the leg of the triangle, altitude, knowing the one leg, range and the angle between the radar beam and zero elevation. In addition most SP radars have a circuit which adds a figure corresponding to the error due to the curvature of the earth at the range of computation. If your meter does not have this feature a table or graph will be necessary to add this correction. See figure 7. Figures 8 and 9 are tables which can be used to check your meter. Use the appropriate table. These tables check the meter for various angles at a given range and at various ranges for a given angle. If the meter checks both ways, you may assume the meter will compute all range and elevation combinations. The meter is built to withstand a current greater than any combination you can achieve on the set so off-scale readings will not harm it. Always, however, secure at zero elevation so that sudden power application will not surge the current through the meter when starting the set.
Figure 4 SP-6. Height meter reading.
4-SP-11
For height meter with earth curvature correction built in.
For height meter without earth curvature correction.
A final precaution must be observed. The Height Meter is used in other ways by the technician to make certain necessary checks on the set. The Height Meter will give height solutions only if Switch 5C is in the "Height" position.
Obtaining the Precision Fix.--When either the "A" or PPI operator detects an echo, the PPI operator stops the antenna and rotates it by the Bearing Handwheel to the bearing of the target while the "A" operator advances the strobe with the Coarse Range Handwheel until the target appears on the "R" scope and then places the target in the notch with the Fine Range Handwheel. Usually the PPI operator will spot the target first and should call out an approximate range to the "A" operator while returning to the target's bearing.
As the target drops into the notch, "A" operator calls out "in the ditch" and the PPI operator starts the scanner and focuses his attention to the precision scope. The "A" operator continues to keep the target just next to the leading edge of the ditch and in the ditch. The PPI operator will see his winged dot moving rapidly about the face of his precision scope. Sometimes the dot will be off the scope but its general position can be noticed by the green glow off to one side or the other. He then moves his bearing and altitude handwheels
in the direction the dot should move to approach center. Once the winged dot is on the scope do not attempt to respond to every small movement it makes. Get the knack of determining which way the dot tends to drift and how fast, and smoothly compensating for the movement. If the dot persists, say, in moving into the first quadrant, think "down and left." Sudden surges of power or variation in echo amplitude will kick the dot off or across the scope but it will return quickly to its general movement. (If the dot is extremely erratic and the slightest movement of elevation and bearing handwheel throws it about the scope, the scope is not properly balanced and the technician should be called to make adjustments with 8A, B, C, D, and 6E.) Call out "ditch" if the wings disappear to warn the "A" operator to get the target back into the ditch. The "A" operator should say "off target" if the echo disappears.
The instant the target is brought smoothly to coincide with the cross hairs etched on the scope, the PPI operator calls "mark." Do not move the Elevation and Bearing Handwheels until the following is completed. If an evaluator or talker is not present, the PPI operator calls out the bearing immediately and the "A" operator, warned by "mark," is ready to call out the range and elevation. If there is a talker, the talker calls out the bearing, range, and elevation warned by the "mark" that the information is ready.
The "A" operator will continue to keep the target in the ditch if further fixes will be called as his change of range will not materially affect the elevation reading. The PPI operator must not move the elevation dial, as this will greatly affect the Height Meter. As he becomes more experienced, the Bearing Handwheel can be used during the readings to help stay on.
If the search is to be resumed, the PPI operator resets the elevation to zero as soon as he hears the elevation called out, starts the antenna rotating and turns off the scanner.
Special Tasks
Fighter Direction.--In combination with high-power air-search gear such as the SK, the SP lends itself to the Fighter Director's work through supplying the third dimension, elevation, of his target. In a combat task force the SP will be engaged routinely as the preferred long-distance surface search set, but upon the contact of enemy aircraft by the air-search gear, will be called upon for fixes
4-SP-12
Figure 4 SP-7. Curvature of the earth correction.
by the FDO. Unless specifically ordered, do not assume the responsibility for tracking an aircraft after a fix. The FDO may request a track for, say, three minutes. Do so, but get the habit of dropping back immediately to general search.
If called upon to track a target, the plot will usually use the "Stand-by-Mark" method of obtaining fixes for greater accuracy of speed solutions. The evaluator or talker is necessary for this at the set. The operators will keep aligned on the target and attempt to have a "mark" set when the evaluator follows his "stand-by" with "mark." This takes a great deal of practice, and during exercises and maneuvers a large portion of the time should be spent on this type of operation.
Night Fighter Direction is greatly dependent upon this type of tracking because of the necessity of directing the fighter to an exact preferred position with respect to the target. Here it is important for the operators to understand the value of relative altitude fixes. You will recall, as the Fighter Director watches the friendly and enemy echoes on his PPI scope, he becomes more and more interested in their relative motion as they draw closer together. On initial contacts and vectors he was demanding course, speed, and altitude but now things are happening too fast for plot solutions and he relies upon the fast-moving relative picture. At night the relative elevation is vital, but the FDO has no way of sensing that part of the problem on the PPI.
The SP Radar comes into valuable use here. It may be that the altitude readings you are getting might be 500, 1,000, or even 2,000 feet off the true altitude due to the set's imperfections. You will, if a good operator, get the altitude between two close targets, making rapid alternate fixes. For example, X may be at 17,500 and O at 18,000, and your reading for X, 16,500 and for O, 17,000. The difference or relative altitude is the same and the FDO can use the information to solve his problem.
The Delayed Sweep.--A special feature is incorporated in the PPI as an aid to increased accuracy in interpreting relative movement and composition of the PPI picture which is suitable for use in fighter direction--the Delayed Sweep. PPI Pattern Selector (4Q) when turned to "DELAYED" activates the circuit. When using delayed sweep, a "hole" is left in the center of the screen to indicate delayed sweep is on.
Delayed PPI sweep produces an expanded view of an annular area so that it cannot be used to appreciate true course but only relative movement and composition. For example, if the range ditch is set at 37 miles and the PPI range switch to "50," the PPI picture will be a ring whose inside diameter
4-SP-13
Figure 4 S-8. Delayed SP Sweep for PPI.
is 37 miles and outside diameter 87 miles, See figure 10.
It must be borne in mind that the start of the sweep on the PPI will always be the range at which the ditch is set when using delayed, so ranging to a target will spoil the current picture and bring the target to the center of the PPI.
Operators will find this feature useful in general search for examining the formation and composition of an approaching task force or group of planes. Remember, ranging cannot be done when using Delayed Sweep.
Navigation.--The SP, like the SG, is extremely useful to the navigator, particularly when operating in close waters. The navigator who is always cognizant of the ship's position will be able to give the operator the approximate bearing, distance, and expected time of contact with land. From his chart he cases
Figure 4 SP-9.
4-SP-14 fixtures.
Auxiliary Fire Control.--Special destroyers have the SG, SC, Mark 12 and 22, and SP radar systems. The SP may be called upon for torpedo fire control as is the SG, especially for targets beyond the SG's range. The SP will also be used as a substitute for the Mark 12 and 22 for accurate tracking for antiaircraft fire as well as surface bombardment. It will also be used for fixing distant aircraft approaching your area but still out of range of the fire control gear. Experience has shown that the operators on the Mark 12 and 22 radars can pick up targets much further than usual when coached to exact target position.
Large carrier classes have the SG, SC, SK, Mark IV and 22, and SP (or SM) and smaller carrier classes have the SG, SK, and SP radar systems. Large carriers will find the same useful advantages for the SP as the destroyer class except of course for torpedo control. The smaller carriers usually have only small caliber antiaircraft weapons and no fire control radar, but the Fire Control Officer can use the advance warning of the SP's low altitude search to good advantage.
Station Keeping.--The SG radar should always have the station keeping duties. The SP is a capable set for this duty in an emergency, particularly because of a good minimum range. For details of procedure refer RADTHREE--Station Keeping, page 4-SG-8.
Composition of the Target (in addition to identification).--Surface or airborne? Speed and altitude, of course, are the quickest means of classifying the target as surface or airborne. The expanded "R" sweep allows the operator to see clearly the approximate speed of his target; the elevation control and precision circuit give the fact of whether or not the target is off the surface. Certain targets such as the carrier with several planes in the landing circle, or a 30-knot cloud at a substantial altitude are exceptions. However, the operator will quickly learn these.
The operator, usually, then must concentrate mostly upon guessing the strength of the target, both as to numbers and size. The "R" scope with a range resolution of 0.1 mile is the scope used to study the details of the echo's behavior. The PPI scope on delayed sweep is used to good advantage to study the number of individual targets making up the group and their disposition.
The basic fundamentals of pipology are well outlined in RADTHREE--Pipology, page 3-10, and must be mastered as a part of good operation. The very narrow beam of the set, the unusual range resolution of the "R" scope and the clear definition of the PPI pattern should make the SP the best set for composition data of any current radar.
A word about false echo characteristics on the SP radar.
Double or Triple Trip Echoes.--The radar beam can return to the source and be reflected from the source to return to the target and back again. The picture resulting from this is an echo at the range of the target and one at twice the range. The high power of the SP makes even triple trip echoes possible. The operator can expect these however, at close true ranges of the order of 1 to 3 miles.
Second Sweep Echoes.--The ranging distance between two transmitter pulses with modulator A" is about 131 miles. This means that large mass targets, which will return enough energy for the set to detect them from more than 131 miles, will return energy the second sweep from the time the energy left the set. A target 145 miles away might appear at 14 miles. Barring a visual check, a set with a different repetition rate
4-SP-15
would be necessary to check this distance. Modulator "B" has such a low repetition rate as to make second sweep echoes impossible on the set and the 200-mile sweep can be used as well.
Cloud Echoes.--Of all the false echoes received on the SP radar the cloud echo is seen the most. This includes cloud banks, small rain squalls, and ionized layers invisible to the eye. The great advantage of this is the ability to keep the air operations informed of suddenly appearing bad weather spots thus enabling the carrier to maneuver to a favorable section for launching and retrieving aircraft. For a description of these and other false contacts refer RADTHREE--False Contacts, page 3-18.
A special Cloud Suppressor Switch (6A) has been provided on the receiver which attenuates targets having a large range width as clouds almost invariably will. The usual ship or plane echo will not be affected by the circuit this switch controls. These echoes can be seen "going thru" the cloud echo. Do not expect too much of this feature.
Jamming and Deception.--The operator must know the practical aspects of jamming and deception and the logical means for preventing the success of its mission--to spoil the SP's ability to get the information it is capable of getting.
RADTHREE--Defense Against Jamming and Deception, page 3-25, gives the information clearly and completely. Pay particular attention to the section "What the Operator Should Do," page 3-28.
In addition, make sure you have been informed when in the combat force of known and expected measures the enemy might take, what his latest wrinkle is for fooling you, from where or what points you can expect the trouble and what reports the CIC will want made. We would know more about jamming if all the fleet's operators had taken this precaution in previous operations.
THE DUAL IFF SYSTEM
The SP radar is fitted to operate two separate IFF systems. One system, is the Mark III "A" band system which is standard throughout the fleet. Refer to RADTHREE, part 2, General IFF Principals. This system the operator will recall is based on a combination of pulses returned from the target at regular intervals, a total of six combinations or codes appearing as a downward echo at the range of the target responding to the challenge. The SP uses the BM or BN interrogator.
There are two differences about the SP radar's MarkIII "A" band IFF as compared to the SC, SK Mark III systems: (1) The challenger or interrogator uses a nondirectional antenna and (2) the IFF time trace is separate from the regular range trace on the scope and directly below it. You will recall that the SG uses Mark III with a nondirectional antenna and a new series of air search radars, the SR's, are using a separate time trace for IFF.
Selector Switch (1Q) places Mark III either on the "A" or the PPI scope. Selector Switch (3M) will place on the "R" scope whichever IFF is on the "A" scope. The usual controls are all explained in the section describing the IFF Coordination Unit.
Refer to RADTHREE pages 2-9, -10, -11, for a complete description of the appearance of Mark III IFF, remembering that the SP will present the IFF on a separate trace.
The second system, for which the SP uses a BO interrogator or equivalent is a special recognition system used by carriers to recognize their own fighter planes. This system is not coded but sends a rapidly repeated challenge pulse and receives a rapidly repeated response pulse on a private frequency. A certain carrier can then ask a plane to turn his special transpondor on and can tell quickly whether or not the plane is one of its own fighters, The Mark III IFF of course can determine originally whether or not the plane is friend of foe.
The second system is known as the Mark III G/R system ("G" band or George IFF for short), and uses a directional antenna and separate IFF time trace. You will notice the antenna for this system mounted as a vertical array of dipoles on the face of the SP parabolic antenna reflector.
Switch 1Q and 3M perform the necessary control for presentation on the scopes for this as well as the Mark III system. Note that both IFFs cannot be presented at the same time on the same scope.
The plane fitted for using both systems has a special dual transpondor. Normally, only "A" band is being answered by the plane's transpondor. Whenever a carrier wishes to determine which of the many friendly targets is its own group, the carrier informs his group to flash "George," and starts challenging with his "G" band IFF. The pilot turns the "G" band section of his transpondor "on." A special time-sharing device alternates
4-SP-16
the "A" and "G" band transpondors in operation, the "A" "on" for three-twentieths and the "G" "on" for one-twentieth of a second--5 times a second. This means that the "A" response continues as usual (the short "off" time 5 times a second does not spoil the transpondor's response or your IFF picture). The "G" band response comes 5 times a second, just rapid enough to appear as a steady but flickering response much like an old time movie with the frames flashing on the screen too slowly.
The pilot cuts the G" band "off" as soon as the carrier has completed the special challenge and the operators cut "off" the "G" band interrogator. The carrier's interrogator, remember, is on a private frequency and should get response only from its own fighter planes.
Comparatively, the "G" response is about the same strength as the "A" response and will show about the same width as the wide pulse of the "A" band codes. Remember that the two bands are set in different ranges of frequencies, thus do not interfere on each other's time traces.
TROUBLES
Major troubles are handled by the technicians, but experience has shown that a great percentage of the troubles are caused by the operators failing to recognize minor break-downs which can be corrected by anyone. In addition much of the misinformation given by the radar is due to the operators failing to know when something is amiss and getting the technician to correct it immediately.
Calibration.--Misadjustment of Coarse Range Calibration will cause the "R" scope trace to disappear at certain settings of the Coarse Range Handwheel. Have technician adjust at once controls 5J and 5K on the range unit.
Tune.--Ultrahigh frequency transmitters drift constantly. Check amount of sea return and known target amplitudes to be sure the receiver is tuned to the transmitter whenever you relieve the set. Don't continue the preceding operator's bad job. Remember to return AFC Switch (4M) to "AUTOMATIC."
Azimuth Elevation or Cross Level Errors.--If antenna fails to respond to console signals the telltale lights 2R, S, T, on the Power Control Unit will flash. Get in the habit of watching for this warning. If these lights persist in flashing for nominal rates of rotation or manual rotation, the servo-mechanisms controlling the antenna need adjustment. Usually the lights will go out if you stop movement for a few seconds, but if any telltale stays on secure the antenna and investigate.
There is an important exception to the telltale system. If a target appears on 360° azimuth, the antenna is not rotating with the sweep. Usually the telltale azimuth light would indicate this. However, if the stable element is not operating the telltale lights will not give warning. You should be able to check this by noticing if the Stable Element Green Indicator (2K) is "on." Secure antenna if this light is out.
Harmful Overloads in Motors and Generators.--A yellow Overload Light (2H) will come on if harmful overloads are present in any of the various motors and generators used to control the antenna. This system will work only if the Selector Switch (2Y) is left in "NORMAL" position. When the light goes on, stop antenna movement and turn Selector off the "NORMAL" position and the light will go out. Then turn Selector until light comes "on" again. The overload exists in the unit indicated by the selector at this point.
Precision Scope Unbalance or Erratic Dot.--The Precision Scope dot will rest at the cross hairs with the scanner motor off. If not, it is out of DC balance. Adjustments 8A and 8B must be used as described in the section on Precision Alignment Unit. The dot should also drift or orbit very closely to the center of the scope with the scanner "on" and no targets present in the "R" scope ditch. If not, it is out of AC balance. Refer to section on Precision Alignment Unit. A technician should do this adjustment. Extremely erratic movement of the dot is adjusted by the AGC Level Control (6E) which controls sensitivity of the precision circuit.
Meters.--There are 6 meters on the console-Learn the. correct position of each pointer on the meter dials (a red line on the meter face will help). They are:
1 Adjust so Oscillator Current Meter reads correctly.
4-SP-17
Constant Altitude Regardless of Range and Elevation.--The Crystal Check Switch (5C) is provided for the technician to make certain checks on the radars. Always make certain this switch has been returned to "Height" position so that the meter will compute height and not stay at a constant level.
Fuse Failures.--If any fuse on the auxiliary power unit fails, a neon telltale should light above it. Always suspect a fuse failure if scopes or units suddenly cease to function or refuse to turn on. All fuses on the console have spares located adjacently.
Refusal of Scopes To Focus.--If focus controls on the scopes will not give a clean, clear trace, the power tubes are usually failing even though they have not burnt out. Have technicians check and try a replacement. Don't waste time with poor focus as these controls will respond readily if properly powered.
Interference on Carrier.--Some sets on carriers experience "hashing" of the time traces when large numbers of planes are warming up on deck (ignition hash). Homing devices occasionally cause similar trouble, though these more likely will interfere with the IFF time trace.
Veracity of the Stable Element.--Even though the height meter is giving correct solutions, errors in altitude will arise if the Stable Element is faulty. Checking the SP altitude against friendly aircraft at known altitudes must be a regular check because of the possibility of this error. In addition to the foregoing check, the use of the SC or the SK estimates of altitude will help. Carriers in the combat zone have found again and again that the air-search gear, properly calibrated, will give excellent height results.
General.--Learn the function of all the telltale and overload indicators and become used to noticing any warning signs of danger to the set. Your set will give consistent service if not allowed to operate in a danger condition.
PERFORMANCE
Maximum Reliable Range
Ranges on surface craft are dependent upon the antenna height. Ranges on low flying aircraft are dependent on both antenna height and aircraft height. Expected ranges with a typical antenna height are listed below as a guide to performance The results listed are considered maximum reliable ranges for an antenna 90 feet above the surface of the water.
Accuracy
Range accuracy is ±0.1 mile.
Bearing accuracy is ±¼° with scanner unit on. ±1° with scanner unit off.
Elevation accuracy is ±700 feet. This accuracy is dependent not only upon the precision circuit but also upon the ability of the Height Meter to compute the information it receives.
Resolution
Range Resolution-of two targets on the same bearing.
Bearing Resolution of two targets at the same range is 6° on the PPI scope and 4° on the "A" scope.
Minimum Range
Minimum range with the Echo Box tuned and probe "IN," 2 miles.
Minimum range with probe "OUT," 0.1 mile.
Planes in the landing circle of the carrier can be seen easily on the PPI scope using the 4-mile range. Escort destroyers close aboard or ships in the task force can be accurately spotted.
4-SP-18
VD, VD-1-2 CONSOLE
Units of the Repeater (figure 1)
1. Remote PPI Scope and Control Circuit Assembly.
2. Power Supply and Servo Assembly.
3. Selector Switch.
Identification and description of the Controls and Indicators on the Console.
1. PPI Scope and Control Circuit Unit
1A. Relative Bearing Indicator (red).--When lit, indicates the master radar is presenting a relative bearing picture rather than a true bearing picture.
1B. Range Selector Switch.--Provides successive ranges of 4, 20, 80, 200 miles on the VD and 4, 10, 20, 80, 200 miles on later models, VD-1-2.
1C. On-Off Indicator (red).--When lit, indicates the PPI and its controlling circuits are energized except for the Servo circuits which are supplied from the ship's synchro bus.
1D. On-Off Switch.--When "on," provides power to the PPI scope and control circuits.
1E. Range Marks Control.--Controls the intensity of the range marks which are provided every 1, 2%, 5,20,50milesfor the 4-, 10-, 20-, 80-, 200-mile sweep.
1F. Intensity Control.--Controls the intensity of the PPI trace.
1G. Focus Control.--Controls the sharpness of the PPI trace.
1H. Dial Light Control.--Controls the brilliance of the lamp illuminating the bearing dial around the PPI scope.
1J. Centering Control (Center Expand Control).-- Centers the start of the PPI sweep.
IK. Sweep Length.--Controls the length of the PPI sweep without changing the total range of the sweep.
1L. Mechanical Cursor Control.--Rotates the Cursor line about the face of the PPI scope.
2. Power Supply and Servo Assembly
No operator controls.
3. Selector Switch
3A. On-Off Selector Switch.--When set to indicated master radar, switches that radar's sweep-start synchronizing pulse, video signal (echoes), bearing information from a synchro generator (so VD PPI repeats rotation of master PPI), the signal indicating whether PPI rotation is in relative or true, and the necessary power from ship's synchro bus. Five (5) different master radars may be wired to be cut in to the VD by this switch.
Figure 4 VD-1. VD-2 console.
4-VD-1
TURNING ON AND OFF
Turning On
1. Turn the Range Marks Control (IE) and Intensity Control (IF) completely counterclockwise.
2. Throw Off-On Switch (ID) to "ON." Pilot Lamp (1C) comes "on."
3. Wait one (1) minute, turn Intensity Control (IF) until trace appears and adjust brightness.
4. Using Focus Control (1G) focus and put Range Selector (ID) to desired range.
5. Turn Range Mark Control (IE) until range marks appear and using Centering Control (1J) and Sweep Length Control (IK) place the first marker at the center of the PPI and the fifth marker at the outer edge.
6. Turn Selector Switch (3A) to desired master radar.
7. Check Sweep by having master radar rotate its PPI sweep and noting that the first marker scribes a dot or very small circle and the fifth marker travels the outside edge of the VD PPI scope.
Turning Off
1. Throw Selector Switch (3A) to "OFF."
2. Turn Range Marks Control (IE) and Intensity Control (IF) completely counterclockwise.
3. Throw On-Off Switch (ID) to "OFF."
CALIBRATION
It should be obvious that placing the range marks on the PPI trace as described in the Turn On procedure does not necessarily mean that the ranges will be correct. The Range Marks are developed by a circuit which sends a mark to the trace at steadily repeated constant intervals. If, say, for the 20-mile sweep they are separated by a time equivalent to 4.5 miles, the fifth marker, placed at the end of the sweep, will be at 18 not 20 miles.
The adjustment of the marker circuit for each range is done from screw driver controls inside the Control Assembly Unit and should be done by a technician. This calibration will take several minutes and a master radar must be available to send calibrated range marks or a target of known distance to the VD PPL
The operator can, however, check the calibration and should always do so for the range he will be using.
Checking the Calibration
1. Set the Range Selector Switch (1B) to the desired range, say, 80 miles and adjust the sweep length, sweep center and markers as described in the Turn On procedure.
2. If the master radar has a range marker for its PPI, set the marker at, say, 20 miles and rotate the PPI sweep. Your VD 20-mile marker should trace a coincident circle with the marker piped from the master set. Check the 60-mile range. If a set of range markers is available from the master compare the master range circles with the VD's range circles as the sweep rotates.
3. If the master radar has a target of known range, check VD range against that given by the master. If possible check with fire control radar ranges.
OPERATIONAL TECHNIQUE General
The remote PPI is used chiefly in the CIC, pilot house, and gunnery Control. The CIC has it available for the Radar Watch Officer, the Evaluator, Gunnery and Torpedo Liaison, and Fighter Director. The pilot house has it available for the Officer of the Deck and the Navigator, and Control on larger ships for the Gunnery Officer himself.
The VD series, then, is used primarily by the officer rather than the enlisted operator. The officer must take it upon himself not to "hog" the radar from which he is getting information unless circumstances demand his exclusive use. The most important single item to remember is that you cannot range a target, get tangents to islands, sweep sectors, and still have the master radar perform a genuine search job. New series remotes (VF) are coming into the fleet to correct this fault.
"Operating" the VD is first the adjustment of the controls and a check on the calibration as described above. The Radar Officer should insist upon a daily calibration and adjustment of gain by the technician. The gain is also a screwdriver inside adjustment and needs daily attention even as the gain on the master radar does. The gain must be set so that it gives a good picture when the master radar is doing the job you will be asking it to perform for your VD. Naturally, if the operator at the master set changes gain to study target composition or "ranges" on an island your picture will be unsatisfactory for the moment. The VD operator will find usually that his picture is much clearer than the master radar itself due to the improved video circuits.
4-VD-2
The only control that the operator will use then, with a properly adjusted VD, is the Mechanical Cursor Dial which rotates the Cursor line. The bearing is obtained quickly by bisecting the target arc with the Cursor line. The Range Marks allow an estimation by eye of the range, but since they are part of the picture, parallax is eliminated (such as was present on older types of remotes--VC series).
Specific Tasks
The main uses of the remote are listed here with references to RADTHREE which explain in detail the handling of the master radar which, in effect, is the way in which the problem must be met with the VD.
1. Station Keeping (Summary Plot). RADTHREE, page 4-SG-8; 4-SL-4.
2. Navigation. RADTHREE, page 4-SG-9.
3. Auxiliary Fire Control. RADTHREE, page 4-SG-8; 4-Mk3/Mk4-9; 4-SC/SK-7; 4-SA-8.
4. Fighter Direction. RADTHREE, page 4-SC/SK-7.
5- Tracking Air Targets. RADTHREE, page 4-SC/SK-7; 4-SA-7.
Communications
The officer using the VD must be in direct contact with the master set and know how to direct the radar operator for best results. He may either use a sound power phone himself or a talker circuit which will leave him free to move about. The MC circuits are not satisfactory during GQ because of the need to minimize the noise level in CIC.
TROUBLES
Aside from miscalibration and improper gain adjustment the VD should not give more than occasional operating trouble. Often after severe gun fire shock, the trace will refuse to start from the physical center of the PPL This is due to the focusing coil being "out of line." The adjustment is inside near the base of the PPI tube.
PERFORMANCE
Maximum and Minimum Range
Performance is dependent upon the master set. Refer RADTHREE, section 4, for individual set performance.
Accuracy
Resolution
Range resolution of two targets on the same bearing is about 2 miles on the 200-mile sweep with increased discrimination to ¼ mile on the 4-mile sweep.
Bearing resolution of two targets at the same range is about 10° with the SC/SK series and 4° with the SG series.
4-VD-3
VF--PRECISION PPI REPEATER
GENERAL DESCRIPTION
ADVANTAGES
CONTROLS
TURNING ON AND OFF
OPERATION
REMARKS
LIMITATIONS
MODEL VF--PRECISION PPI REPEATER
Navy Model VF is designed for use with various types of search radar equipment. Experience has shown that it is most valuable when used with surface search radars. Its function is to repeat and retransmit the target bearing provided by any selected search radar, and to measure and transmit the accurate range of a target.
General Description
Usually located in CIC, the VF set is equipped with two 5-inch scopes for both PPI and B-scope presentation. As with Model VD gear, the PPI has four range scales of 4, 20, 80, and 200 miles. Similarly range marks consistent with the scale chosen appear at 1, 5, 20, and 50 miles. The bearing accuracy of the PPI tube is within 1° of the master radar, limited only by the ability of the operator to center the cursor on the target. The range accuracy is slightly less than that of the master radar.
The B-scope repeats a selected sector of the PPI screen in a greatly enlarged rectangular coordinate view. That is, the portion of the PPI sector representing close ranges is enlarged more in azimuth than the portion representing more distant ranges. Altered presentation is clarified, however, by suitably intensifying the sweeps to produce azimuth lines at 10° intervals and range lines at 1,000-yard intervals, thus forming a geometric reference grid on the B-scope screen. The vertical sweep represents range; the horizontal sweep represents bearing. The B-scope horizontal sweep occurs once each revolution of the PPI sweep, but the duration of this horizontal sweep is only approximately one-eighth of that of one PPI revolution.
When viewed from the operating position, the bottom of the B-scope screen always represents closer range and the top represents more distant range. The center of the screen corresponds to the range counter reading and to azimuth cursor position on the PPI tube. Positions at the left-hand
Figure 4 VF-1. PPI screen, showing target presentation, range marks, and segment selected for enlargement.
Figure 4 VF-2. B-scope, showing enlarged presentation of targets seen in selected segment on PPI screen.
4-VF-1
side of the B-scope are smaller azimuth angles than the cursor position; and positions at the right-hand side are larger azimuth angles. When the PPI sweep is rotating clockwise, the B-scope is scanned from left to right; when the sweep is rotating counterclockwise, the B-scope is scanned from right to left.
The bearing accuracy of the B-scope is essentially the same as that of the PPI, but the ability of the operator to read information on the B-scope is far greater. Ranges, however, can be read with an accuracy approaching the basic accuracy of B-scope (±100 yards between 600 and 4,000 yards, and ±25 yards between 4,000 and 40,000 yards).
Advantages
(1) An accurate track on one or more targets may be obtained without interrupting the normal search procedure of the master radar.
(2) A range and bearing on the guide or on any ship in the formation is readily available without stopping the sweep on the surface search radar. This is a considerable advantage for ships with only one surface search radar.
(3) The feature of having the VF connected to the target bearing and range designation system affords a quick and accurate method of sending the target bearings and ranges to important stations in the ship.
(4) The ability to spot the fall of shot within about one hundred yards.
(5) Target discrimination with the B-scope of the VF is better than with the SG or Mark 12 radars.
(6) With the operator behind the VF, CIC officers have a clear view of the general and detailed picture without interfering with radar operation.
Controls
Before using the equipment for the first time, the operator should learn the locations and functions of the operating controls. Controls actually used in determining range and bearing are located on the Top Control Panels on the top surface of the unit. Controls for preliminary adjustments (such as Focus and Intensity) are mounted on the exposed front panel of the Control Chassis. Controls for calibration, etc., which are used only occasionally are mounted on the recessed front panel of the Control Chassis, and are normally concealed by a hinged cover.
Dial Lights
A. Dial Lights.--Dial lights for PPI scope.
B. Power.--Standby-On Switch.
Figure 4 VF-3. Controls on top control panel.
4-VF-2
C. PPI Video Gain.--To make signals appear at the desired strength on PPI scope.
D. B Video Gain.--To make signals appear at the desired strength on B-scope.
E. Range.--Range selector switch for 4-, 20-, 80-, 200-mile scales.
F. Dimmer.--Dial light control on range counter and relative bearing vernier dial.
G. Remote Bearing Switch.--To indicate to remote stations that bearings are being transmitted.
H. Bearing Crank.--To rotate the mechanical cursor on the PPI scope.
I. Range Crank.--Coupled to the range counter to read B-scope ranges.
J. Remote Range Switch.--To indicate to remote stations that ranges are being transmitted.
K. Range Counter.--Indicates B-scope ranges in yards.
L. PPI Scope.--Five-inch scope with both true and relative bearing dials.
M. B-Scope.--Five-inch scope with electronic range and bearing marks.
N. Bearing Vernier Dial.--Vernier scale for relative bearings only.
1. Focus.--PPI focus adjustment.
2. Range Marks.--Controls intensity of PPI range marks.
3. Range Ring.--Controls brilliance of illuminated range ring on PPI screen.
4. Intensity.--Adjustment for desired intensity of PPI trace.
5. Center Expand.--Adjustment to correctly center first mark on PPI screen.
6. Intensity.--Adjustment for desired intensity of B-scope trace.
7. Spot.--Controls intensity of B-scope tracking spot.
8. Range Marks.--Controls intensity of B-scope range marks.
9. Focus.--B-scope focus adjustment.
Figure 4 VF-4. Front panel controls on control chassis.
Turning ON end OFF
1. Starting the Equipment.
(a) Check to see if Main Line Switch is on.
(b) Turn POWER switch B to "on."
(c) Set externally mounted Selector Switch to desired master radar.
2. Adjusting the PPI Scope.
(a) Turn up INTENSITY Control 4 until a light trace appears on the PPI screen.
(b) Adjust FOCUS Control 1 for optimum sharpness of PPI trace.
(c) Adjust RANGE MARKS Control 2 for desired intensity.
(d) Adjust RANGE RING Control 3 for desired brilliance of the illuminated range ring.
(e) Set RANGE SWITCH E to the desired range.
(f) Advance PPI VIDEO GAIN Control C until signals of the desired contrast are obtained.
(g) Adjust CENTER EXPAND Control 5 until first mark makes a small circle or dot at the center of the PPI screen.
(h) Adjust DIAL LIGHTS Control A for desired illumination of the PPI Bearing Dial.
3. Adjusting the B-Scope.
(a) Turn up INTENSITY Control 6 until a faint trace appears on the B-scope.
(b) Adjust FOCUS Control 9 for optimum sharpness of center bearing mark.
(c) Adjust RANGE MARKS Control 8 for desired brilliance of marks.
(d) Adjust SPOT Control 7 for desired brilliance of the tracking spot.
(e) Advance B VIDEO GAIN Control D until signals of the desired contrast are obtained.
(f) Adjust DIMMER Control F for desired illumination of Range Counter and Relative Bearing Vernier Dial.
4. Securing the Set.
(a) Turn all intensity, range marks, range ring, and spot controls fully counter clockwise.
(b) Turn down dial light controls and PPI and B-scope gain controls.
(c) Set POWER Switch B to "STANDBY" position.
(d) Set the externally mounted Selector Switch to "OFF" position.
4-VF-3
Operation
1. Interpreting PPI Targets.
Targets appearing on the VF PPI will be similar to those on the master PPI. However, the VF picture will be clearer than the master PPI picture due to the sharper focus obtainable on the former.
2. Determining Range and Bearing on the PPI Scope.
(a) Determining Range.--Estimate the range of the target by reference to the range marks, bearing in mind the value of these marks as determined by the setting of RANGE Switch E.
(b) Determining Bearing.--Rotate Bearing Crank H until the rotating cursor bisects the signal trace on the screen, then read the bearing (true or relative) on the Bearing Dials surrounding the screen.
3. Reading Accurate Range and Bearing on the B-Scope.
(a) Accurate range is read from the RANGE COUNTER K. Accurate bearing (azimuth) is read from the two PPI Bearing Dials in conjunction with the Relative Bearing Vernier Dial at the front of the top panel.
(b) Procedure.
(1) Observe PPI scope and select a target on which accurate range and bearing are desired.
(2) Rotate the Bearing Crank until the white end of the cursor bisects the chosen target.
(3) Rotate the Range Crank until the illuminated range ring on the PPI appears at the range of the target. The desired target will now lie in the approximate center of an intensified sector on the PPI which is 4,000 yards long and 50°-60° wide. The target will also appear near the center of the B-scope the next time the horizontal sweep occurs on that tube.
(4) As soon as the horizontal sweep ends on the B-scope, adjust the vertical line that crosses the tracking spot until it exactly bisects the target.
(5) Simultaneously adjust the Range Crank until the tracking spot rests on the edge of the target trace nearest the front of the set. The next time the sweep occurs the target will appear in the exact center of the screen in the horizontal plane, and the front edge of the target will be on the middle range mark.
(6) Read the bearing from the PPI Bearing Dials and the range directly from the Range Counter.
(7) If range and bearing to remote stations are desired, press the Remote Range and Bearing Switches indicating that information on the selected target is being transmitted.
Remarks
1. A great deal of practice is required before an operator can get a good track from the VF. Poor operating produces a very poor track, much poorer than proportionately substandard operation of the SG would produce. Try to anticipate the movement of the target by placing the spot where the pip will appear on the next sweep. Never read a range and bearing unless the lower edge of the target is just touching the middle range mark and is perfectly bisected by the vertical line.
2. When not tracking it is advisable to keep the VF trained on the guide, allowing information for station keeping to be quickly obtained.
3. When possible VF ranges should be checked against fire-control radar ranges to insure the accuracy of calibration.
4. Operation of the target designation system is very simple and effective. First, set the selector switches on the desired remote indicators. Second, place spot on leading edge of the target. Third, press the Remote Alarm Switch; one blast indicates action to starboard, two blasts action to port.
5. Precision in spotting depends on the bearing and range discrimination of the radar used. The gain must be set sufficiently high to observe the splashes. An ordinary radar sled target at 5,000 yards produces a pip on the VF oval in shape, 400 yards long and 8° wide when % inch of grass on the SG "A" scope is used. The width of the pip depends on the beam width while the length depends on the pulse width. Spots within 100 yards of the target will be very difficult to make since the splash-pip will merge with the target. Also it must be remembered that when the antenna is rotating, the master radar is not continuously looking at the target. Splashes may possibly rise and fall between sweeps. The best solution probably is to rotate the antenna at its fastest automatic speed. VF spotting is practicable and with a little practice should be a very valuable aid.
6. The possibilities of operation with air search radar are very limited by the relatively short range (40,000-45,000 yards) of the B-scope. Long-range air tracking with the VF is not practical. Tracking within the range of the B-scope is made difficult by
4-VF-4
the slow rotation of the air search antenna combined with the swift movement of the target. Getting on in range requires a very good guess at where the pip will be on the next sweep. The wide beam width of air search radars causes most echoes to extend all the way across the screen. Bearings must then be read from the PPI scope.
Limitations
1. When measuring ranges below 2,375 yards on the B-scope, the spot will not return to the center after the tube has been scanned. The bearing and range may be read from their associated dials, however, when the spot is centered on the desired target. Azimuth centering will still occur but range centering is locked out on low range. The LOW RANGE Pilot Lamp on the top panel is lighted when measuring ranges below 2,375 yards. Do not attempt to read ranges under 500 yards on the B-scope.
2. Bearing accuracy is no better than the bearing accuracy of the master radar, being limited only by the ability of the operator to center the cursor on the vertical bearing mark on the target.
3. The user should remember that the shape of the targets as viewed on the B-scope is not the true enlarged plan view of a section of the PPI screen, but rather a portion of the selected PPI section 4,000 yards long and 40° wide, having the sides of the angle opened out to form parallel lines. This picture is then enlarged to the limits of the 5-inch B-scope. In effect, it is really a Mercator Chart conversion.
4. The VF is a precision instrument both electrically and mechanically and hence should be operated only by competent personnel. All adjustments on controls located inside the recessed front panel of the Control Chassis should be made by technicians. The Battle Switch, which shorts out the interlocks, should be used only in the event of an emergency and then only by a qualified technician.
4-VF-5
VG, VG-1 PROJECTION PPI
CONTROLS
Main Control Panel
Main Power Switch.--In the "on" position, this switch supplies power to the unit, and in "off" position it supplies power to the heaters. With all other switches "off" it will put into operation only the projection lamp and the blower motor.
Operate Switch.--This switch admits power to all electronic components of the unit with the exception of the high voltage circuit.
High Voltage Switch.--This switch energizes the high voltage circuit.
Dial Light Switch.--The True and Relative Bearing Dials are projected on the viewing screen when the O. S. C. projector lamp is turned on by this switch.
C.R.T. Bias.--This control is analogous to the intensity control on the usual Cathode Ray Tube. In the maximum counter-clockwise position only the strongest signals under the maximum video gain will show on the viewing screen. As the control is rotated in a clockwise direction, less and less gain is required to permit signals to pass through to the viewing screen.
Video Gain.--This control varies the strength of the signals received from the radar. It has the effect of changing the intensity of the pattern appearing on the viewing screen. Together with the C.R.T. Bias it should be adjusted to the point of maximum contrast.
Focus.--This control is used to focus the electron beam until the clearest pattern appears on the viewing screen.
Range Selector Switch.--This control is used to select the range scale desired. Five ranges: 4, 10, 20, 80, and 200 miles are available.
Range Mark Intensity.--This control is used to vary the intensity of the four (4) range mark circles. These range marks always appear at quarter range intervals of whatever range scale is selected. Thus for the 4-mile range, the four (4) concentric rings represent 1, 2, 3, and 4 miles; for the 10-mile range, they represent 2½, 5, 7½ and 10 miles; for the 20-mile range, they represent 5, 10, 15, and 20 miles; for the 80-mile range, they represent 20, 40, 60, and 80 miles; and for the 200-mile range, they represent 50, 100, 150, and 200 miles.
Center Expand Switch.--This switch can be used to move the start of the sweep out from the center of the screen. Its purpose is to give better bearing resolution. The screen will no longer be a true map but the marker circles will still give accurate ranges. If used at all, this switch must be turned "on" only momentarily to avoid harming an extremely persistent circle into the face of the scope.
Centering North-South Control.--This is a screwdriver adjustment used to center the projected pattern on the viewing screen in a north-south direction.
Centering East-West Control.--This is a screwdriver adjustment used to center the projected pattern on the viewing screen in an east-west direction.
Miscellaneous Controls
Dial Light Dimmer.--This control is used to vary the intensity of illumination of the bearing dials on the viewing screen.
Selector Switch.--Located on the selector box, this switch selects the master radar from which signals will be taken for the VG.
Picture Erase Control.--This control is used to vary the persistence of the pattern appearing on the screen. In "operate" position a heat absorbing "aklo" glass is inserted in the path of the projection lamp beam which decreases the heating of the tube face. This results in greater persistence. In the "erase" position, the heat filter is removed, allowing more heating of the tube face and less persistence of the pattern.
4-VG-1
Figure 4 VG-1.
Picture Fade-Out Control.--This control also varies the persistence of the pattern appearing on the screen. It actuates a butterfly valve controlling the flow of air from the blower to the optical unit housing. In "fast" position it cuts off the circulation of air allowing the tube face to heat up and decreasing persistence of the pattern. In "slow" position full flow of air is permitted giving maximum persistence to the pattern. Intermediate settings of the control will frequently be found desirable.
Battle Short Switch.--Normally this switch is "off." When directed it can be used to short out all interlocks in the unit. When the switch is
4-VG-2
"on," the red warning light at the right top forward corner of the unit, and the warning lights on either side of the base of the optical unit housing, will light.
Caution:This Battle Short Switch should be used only during such times that the danger to which the operator and service personnel are exposed, thereby, is warranted and justified. It is intended to be used during time of battle only.
TURNING ON, ERASING, AND TURNING OFF
Turning on--Check Controls for Normal Positions:
1. Video Gain.--Counterclockwise.
2. C.R.T. Bias.--Counterclockwise.
3. Range Mark Intensity.--Counterclockwise.
4. High Voltage.--Off.
5. Center Expand- Off'.
6. Operate.--Off.
7. Picture Erase.--" Operate." 8. Battle Short.--Off.
To Place in Operation
1. Turn Main Power Switch "on". The blower motor will start and the viewing screen will be illuminated.
2. Turn the Operate Switch "on."
3. Turn the High Voltage Switch "on."
4. Set the Selector Switch to the desired master radar.
5. Place the antenna of the selected radar in rotation.
6. Set the Range Selector Switch to the desired range.
7. Turn C.R.T. Bias clockwise until the trace appears.
8. Adjust Focus to optimum.
9. Turn C.R.T. Bias counterclockwise until the trace just disappears.
10. Turn Video Gain clockwise until maximum contrast is obtained on the viewing screen--NOT BEYOND.
11. Readjust Focus to optimum.
Further Adjustments Will be Made as Necessary
1. Range Mark Intensity should not be advanced beyond the point where the range circles are faintly visible. Frequently the range circles will not be used at all.
2. The Dial Light Switch will be turned on and the Dial Light Dimmer advanced whenever desired.
3. Picture Erase Control will normally be placed in "Operate" position though it may be placed in "Erase" position for brief periods if minimum persistence is desired.
4. Fade Out Control will be positioned according to the degree of persistence required.
To Erase Pattern
1. Turn Video Gain fully counterclockwise.
2. Turn Range Selector Switch to 200-mile range.
3- Turn Range Mark Intensity fully counterclockwise.
4. Adjust Focus for most diffuse beam.
5. Turn C.R.T. Bias fully clockwise.
6. Set Picture Erase at "Erase."
7. Set Picture Fade Out at "Fast."
8. Keep antenna of selected radar rotating until pattern is fully erased. A surface search radar is most satisfactory for this purpose since the antenna rotates at a higher speed than does the air search radar.
To Turn Off
1. Erase pattern until viewing screen is clear except for black spot in center.
2. Turn Video Gain fully counterclockwise.
3- Turn C.R.T. Bias fully counterclockwise.
4. Turn Range Mark Intensity fully counterclockwise.
5. Turn High Voltage "off."
6. Delay five (5) seconds.
7. Turn Operate "off."
8. Turn Main Power "off."
9. Turn Picture Erase to "Operate."
10. Turn Selector Switch "off."
OPERATING TECHNIQUE
General Precautions
Care must be taken at all times to avoid burning the pattern too deeply into the scope face. Land echoes are a problem particularly on the higher ranges. Ships in formation also burn targets into the scope. In some cases a compromise must be made between the point of maximum contrast and extreme burning in of targets. Where land is concerned it is good to use a shorter scale not covering the land whenever feasible. Burning in is most serious when using SP-SM radar and least serious on poor definition radars such as SC-SK. When ships in formation change disposition, their burned in image will remain. With practice it is
4-VG-3
possible to differentiate a new and an old target by the shade of the image. Still, confusion may result from several images of ships in the formation, if the old one is not erased or marked in a distinguishing manner.
The Center Expand Switch can cause most serious burning in. When it is turned "on," the transmitted pulse will describe a circle about the center of the screen. This device must be used with great care. Its purpose is to obtain better bearing resolution at the inner portion of the sweep. Unless necessary, it should not be used. When used, it should be turned on for the briefest possible period.
Care must also be taken to guard against momentary flare-ups of the sweep. Such flare-ups are likely to occur when the antenna is suddenly stopped, when ranges are changed, and when the gear is switched to a different radar. The intensity is automatically decreased when the antenna stops rotating but the action is not instantaneous. If the antenna is slowly brought to a stop, no flare-up will result. However, it is desirable for the radar operator to give the VG operator the word whenever the antenna is stopped. The VG operator can then reduce Video Gain until the antenna is again put in operation. The VG operator should also turn down the gain when he switches to a different radar or to a higher range.
When a different range is selected not merely the Video Gain should be readjusted but also the C.R.T. Bias. Again the point of maximum contrast should be attained.
Techniques of Use
Provided with the VG are three different types of viewing screens. One is a clear glass screen covered by plotting paper, two are ground-glass screens, one of which is plain while the other is calibrated with bearing lines and range circles. The plotting paper will not be used unless a record of the plot is desired. The calibrated screen will be used in instances where it may be desired to plot information from sources other than radar. Plotting on all three surfaces is most successful with a soft lead pencil. A damp cloth can be used to erase the ground-glass screens.
Accurately calibrated distance scales should be prepared for each of the five (5) ranges. For use with air plot speed triangles may also be prepared. Some ships have found it helpful to mount a Vard or Craig computer on the VG. In any case, a paralleled motion plotting arm will be found useful for maneuvering board problems as well as for plotting.
Plotting technique depends somewhat on the radar in use. Used with SP-SM or SC-SK the correct plot calls for splitting the target arc and placing a small dot on the inner edge of the indication. Used with SG, the dot is placed in the center of the indication rather than on its leading edge. Plots will be made as the antenna rotates past the bearing of the target, completely eliminating dead time. Time is recorded to the closest quarter minute at appropriate intervals.
The long persistence of the scope is a limitation that must be considered at all times. It is not good practice to change ranges frequently or to switch in different radars very often. The scope should be erased each time before such a change, and thus a time delay is inevitable. Long persistence also contributes to a poor target definition already noticeably worse than the master radar.
Use of VG as a Summary Plot
Summary Plot is a relative plot on which is displayed the present position of all surface contacts. It is used to keep track of all friendly forces and thus is invaluable for purposes of identification. By picturing the fleet disposition it is also useful in station keeping.
The 20-mile range will usually be found to be the most satisfactory. Only when used primarily for station keeping will a lower range scale be preferable. Notation of more distant contacts can be kept on the periphery of the plot. Use of the polar coordinate plotting surface will simplify this process of plotting other information.
With respect to the fleet disposition, all assigned positions should be plotted on the screen with our ship at the center. The guide should be designated as such. Names of ships in the formation can be printed in with their voice call also indicated. When the disposition has been plotted in this manner it will become instantly apparent when any of the ships get out of position. It will be equally apparent when we are out of position. Furthermore, new contacts in or near the formation will be easy to discover.
When a change in the fleet disposition is made there is danger of confusing the old burned in image. The best practice is to erase the old disposition, but if time will not allow this procedure,
4-VG-4
the old images should be marked in a distinguishing manner.
When any contacts have relative motion, the use of maximum persistence will result in the target plotting itself. It leaves behind it a "tail" which gradually fades out with time. This process provides a rough indication of the relative course of the target for the "tail" will extend toward the reciprocal bearing of the target's relative course. A rough indication of relative speed is also provided by the length of this "tail," When plots are made with every rotation, an even more accurate indication of relative course and relative speed is given by the direction and intervals between dots.
Accurate courses and speeds can be readily computed from a plot on which quarter minute times are noted. The viewing screen can then be used as a maneuvering board.
Use of VG for Air Plot
Used with SK, air plotting can be carried out on the VG screen in the same manner as it is usually performed on an air plot board. Again, great advantages will result from the elimination of dead time and the constant plotting of all targets. If it is not possible to plot all contacts appearing on the screen, the "tail" will indicate the general course and speed of all aircraft. Quarter minute time should be used but plotting done with each rotation of the antenna. Tracks will turn out to be clearer and straighter than those made with the usual operator-plotter team. Moreover, plots will not be missed and fades will be at once apparent.
Several disadvantages must be understood and the gear operated accordingly. Identification will ordinarily be impossible on VG. Information as to identity of the contact will have to be obtained from the master radar. However, once a target is designated friendly, an accurate plot will serve to keep its identity certain.
Difficulty is also encountered in use of the electronic range marks when SC-SK radar is being used. With Range Mark Intensity turned fully clockwise, the range marks may not appear at all. It is necessary then to reduce the Video Gain until the marks appear. It may not be possible to get signals and marks at the same time.
Interceptions can be made from VG with some advantages over an air plot board interception. However, poor target definition and long persistence has limited the possibilities where particularly close interception is required as in night fighter direction. Evasive maneuvers of the bogey are sometimes hard to follow. The VC with a 12-inch scope is much more satisfactory.
Use of VG for Navigation
When within range of land, the VG can be used to obtain navigational fixes. The SP-SM is the best master radar to use for this purpose with the SG being almost as effective.
Contour charts on tracing paper must be prepared in advance for land to be encountered. With a pantograph these charts can be drawn quickly and easily to correspond with the VG range scale on which they will be used. The range scale to be used will depend entirely upon the operations to be undertaken. The 80-mile scale will be most useful range for general navigation but for shore bombardment, or inshore piloting, lower scale will be better.
Accuracy of VG fixes will not be as high as with the VPR or when otherwise making use of the master radar. However, fixes can be obtained very quickly and can be of considerable use in C.I.C.
PERFORMANCE
Performance of the VG is in all cases inferior to the master radar with which it is being operated. Target definition is poorer resulting in worse bearing and range resolution. Also faint targets visible on the master radar will often be lost on the VG though it is frequently possible to coach the VG operator onto this target from the master set. Range and bearing accuracy is also inferior to that of the master radar.
TROUBLES
Burning in Permanent Patterns.--This hazard has frequently been mentioned and it must always be borne in mind. Targets with no relative motion, land, range marks, and the center expand circle create images which can burn in permanent black patterns. These images must be avoided or reduced whenever possible. The screen must always be erased before securing it.
4-VG-5
Changing Cathode Kay Tube.--This is a process requiring considerable practice since it involves realignment of the optical system. Technicians should be given an opportunity to practice this and no one else should attempt it.
Cracking of Lenses.--Several cases of cracking of the parabolic condenser lens have been reported. The operator should report any failure of the blower motor immediately as continuous air delivery might prevent such casualties.
4-VG-6
ECHO BOX
INTRODUCTION
HOW IT WORKS
HOW TO TEST OVER-ALL RADAR EFFICIENCY
RINGTIME MEASUREMENT POINTERS
OTHER USES
Figure 4 OBU-1. The typical echo box (OBU-3).
Introduction
Before the development of the echo box, radar operators had no way of testing the efficiency of their sets. The echo strength of a so-called "standard target" such as the pineapple tower in Honolulu--as seen from Pearl Harbor, was once thought to be significant. In the early days of radar few appreciated the role of weather as a factor influencing the performance of radar. Now, however, we know that a radar may be in poor materiel condition and give fair ranges under conditions of "anomalous" (nonstandard) wave propagation. Furthermore, it is quite possible
Figure 4 OBU-2. Atmospheric variations cause variations in radar performance.
4-1
that a set may be in 40 condition and still fall far below the typical standard of performance. Nonstandard propagation and other variables that influence the performance of radars have been dealt with at length in RAD 1A and to some extent in this manual: suffice it to say, it is not possible for you to judge the efficiency of your radar except by testing it with an echo box.
How It Works
The echo box, as the name implies, is a device that returns an echo whenever a pulse from the transmitter is fed into it. This echo incidentally is a standard echo in the truest sense of the word--if it changes, a change in over-all radar system efficiency is indicated.
Figure 4 OBU-3. Simplified cross-section of echo box.
Essentially the echo box consists of simply a cylinder, the size of which is varied by a piston. The piston moves in and out as the echo box is tuned by its tuning knob. Energy from the radar transmitter is fed into this "tuned cavity" in one of two ways: (1) A small pick-up antenna can be placed in the vicinity of the radar antenna--the pick-up antenna being connected to the echo box by a coaxial cable.
(2) A so-called "directional coupler" can be installed in the wave guide--it picks up energy which is then fed through a coaxial cable to the echo box.
Basically this is all there is to an echo box, but most have an output meter built in as an additional refinement--this is, of course, for use in making periodic comparisons of average pulse power.
The echoes of the box are detected by the radar receiver and displayed on the various indicators as a characteristic pip extending from zero range out to several thousand yards. If the pick-up dipole has been placed in a fixed position with respect to the radar antenna, the echo box echo will be seen best in one direction only (when the radar antenna is pointed at the pick-up antenna). If the pickup antenna is attached to the radar antenna and rotates with it, or if a directional coupler is used; the echo will be seen extending in all directions from zero range to several thousand yards.
How To Test Over-all Radar System Efficiency
Testing the over-all system efficiency requires only a moment and should be done by the radar operator at the time a new watch is set or whenever he has reason to believe his set is "below par." The procedure is as follows:
1. Turn on radar and allow sufficient time for it to warm up thoroughly.
2. Turn off AJ controls and STC.
Figure 4 OBU-4. Echo box echo on "A" scope. Its duration is measured in yards and called "ringtime."
4-2
Figure 4 OBU-5. Ringtime as it appears on the PPI scope
3. Rotate the radar antenna until it is pointed in a direction relatively free of targets out to several thousand yards.
4. With echo box connected to the directional coupler, adjust its tuning knob until the output meter reads a maximum.
5. Check calibration of radar range circuit.
6. Set receiver gain as you would for short range search.
7. Look at the echo box echo on the radar indicator (A scope preferred) and adjust the receiver tune control until the echo box echo is saturated to the greatest possible range.
8. Measure the "ringtime" (the greatest range at which the echo box echo can be seen) several times and average the readings.
9. Record the date and time, the output meter reading, the ringtime, the difference between the actual ringtime and the expected ringtime (the latter is determined by the technician or the materiel officer).
10. If the ringtime is low, the technician should be called to investigate the trouble. A loss of more than about 150 to 250 yards of ringtime begins to be quite significant (this depends on the model of echo box used)--especially with regard to small targets such as periscopes and aircraft. The radar materiel officer will inform the operators of the expected ringtime and he may request that he be called if the loss of ringtime is larger than some specified figure--like 150 yards.
11. Having completed the check, the radar operator may now secure the echo box by detuning it.
CONFIDENTIAL
Figure 4 OBU-6.
4-3
Figure 4 OBU-7. Measuring ringtime on "A" scope--receiver gain not a critical factor within reasonable limits.
Ringtime Measurement Pointers
In measuring ringtime on the A scope, the range should be read at the point where the echo just disappears in the grass--the antenna should be stopped. Be sure you don't confuse the echo box ring with sea return or other nearby echoes. The characteristic behavior of the ring as the receiver gain is varied will distinguish it from other echoes.
When the PPI scope is used, the ringtime should be measured to the point where it is barely distinguishable from noise--not where it ceases to be solid white. Receiver gain should be set so that flecks of "snow" cover about half the scope area. Ringtime can be measured on the PPI with the
Figure 4 OBU-8. Setting the step.
Figure 4 OBU-9. Measuring ringtime on PPI. A. When directional coupler is used. B. When pick-up dipole is used and is not mounted on antenna so as to rotate with it. Note that measurement is made at outermost fringe of echo.
4-4
Figure 4 OBU-10. Ringtime seen on B' and * J" scope.
antenna rotating or stopped but it is generally easier when the antenna is in motion.
In most cases, a number of operators will be making ringtime measurements. These men should practice together until they can make readings that agree closely with one another.
The expected ringtime will depend upon the pulse length in the case of some radars--so be sure you take this into account and use the one which corresponds to the ringtime you have been told to expect. Furthermore, the expected ringtime will depend upon whether it is the pick-up antenna or the directional coupler that is "connected to the echo box" (there is more loss in the long coax necessary when the pick-up antenna is used). It is quite possible to use the pick-up dipole in
4-5
over-all system check. This technique has two advantages and one big disadvantage when compared to the test previously described.
Advantages--(1) You test not only the transmitter and receiver, but the antenna and transmission line too. (2) You can see a rough outline of your antenna pattern (and therefore spot your minor lobes) on the PPI, if pick-up is fixed with respect to antenna.
Disadvantage--Variations in weather affect the loss in the longer coax rather unpredictably, making precision comparisons impossible.
Other Uses
The echo box is a valuable piece of test gear. In addition to its most important function (ringtime measurement), it can be used to make a "spectrum analysis" (to determine if frequency modulation or double moding is occurring and to measure pulse duration) to make periodic power comparisons, and discover and isolate to some extent obscure troubles that might go unnoticed. Naturally these test functions are out of the realm of radar operation but they are mentioned for information anyway.
You now have a quick, scientific means of checking the over-all system efficiency. There is a natural tendency question to question testing equipment of this type--especially when good radar conditions (nonstandard atmosphere) offset and conceal reduced efficiency. The equipment is fundamentally simple and ruggedly and reliably made. It is intended to serve you and is worthy of your confidence. Use it.
4-6
Table of Contents
Previous Part (3) Next Part (5)
|
http://www.ibiblio.org/hyperwar/USN/ref/RADTHREE/RADTHREE-4.html
|
CC-MAIN-2013-48
|
refinedweb
| 55,203
| 64.91
|
I should have spelled this out before: these are all permutations, so in general permuting the result space of `x * mult + y` (or any other permutation involving x and y) is exactly the same as not permuting it but applying a different permutation to y instead.
Specifically, the sequence:
x = x * mult + y (mod 2**N)
x = P(x) # P is any permutation of N-bit integers
is the same as (and this isn't "deep" - it's trivial):
x = x * mult + Q(y, x) (mod 2**N)
where Q(y, x) = P(x * mult + y) - x * mult (mod 2**N)
Q is a "richer" class of permutation though, because it's a different permutation for each fixed value of `x`, and uses multiplication to help disperse bits.
While it would take a lot of work to quantify this, in my experiments the tuple hash is significantly less touchy when permuting x after than when permuting y before, presumably because Q is richer.
The two tuple hash tests have many inputs whose tuple component hashes have very similar (even identical) bit patterns. There's only so much dirt-simple permutations (like "y ^= y << 1") can do to break the patterns. So, e.g., change a shift count, change the multiplier, ..., and at least one of those two tests fails depressingly often. Not spectacularly, but over the limit they allow. Q(y, x) does a far better job of magnifying small differences.
Something I haven't tried: use a richer permutation of y that _doesn't_ depend on x. For example, the frozenset hash has much the same underlying challenge, and uses this permutation to "blow up" small input differences:
static Py_uhash_t
_shuffle_bits(Py_uhash_t h)
{
return ((h ^ 89869747UL) ^ (h << 16)) * 3644798167UL;
}
But that's a lot more expensive than a single shift-xor, and the speed of tuple hashing is more important than of frozenset hashing.
|
https://bugs.python.org/msg326583
|
CC-MAIN-2020-34
|
refinedweb
| 315
| 52.73
|
1 Dec 04:11 2005
(no subject)
Chris Jensen <cjensen <at> gmail.com>
2005-12-01 03:11:46 GMT
2005-12-01 03:11:46 GMT
Hi, I'm trying to implement an exim filter to perform quarantining and notification for malware and dangerous attachments. However, I wish to make the notification conditional based on if the sender was an internal or external IP. eg If a virus is received from an internal IP, notify the administrator, notify the sender if they're internal and have sent a banned attachment file type. Am I going about this the right way? I can't figure out how to successfully identify internal sender IP's from within a filter, I was hoping for something along the lines of # Set n1 to 1 if this is a local message if ${match_address{$sender_host_address}{$relay_from_hosts}} is 1 then add 1 to n1 endif But that doesn't work. I've googled and searched the archive and seen questions about this, but no answers that have helped me. Thanks for any help Chris -- -- ## List details at ## Exim details at ## Please use the Wiki with this list -
|
http://blog.gmane.org/gmane.mail.exim.user/month=20051201
|
CC-MAIN-2014-35
|
refinedweb
| 191
| 66.47
|
Log message:
sysutils/acpica-utils: remove nonexistent files from REPLACE_BASH:
Adjust CC_VERSION check from gcc-8* to gcc-[89]*
Log message:
Avoid some sprintf buffer overflows reported by gcc 8. Bump PKGREVISION
Log message:
acpica-utils: build fix for netbsd<7
from Edgar Fuß in PR pkg/52654
Log message:
acpica-utils: patch in Solaris support
taken from illumos-gate
should get the build further
Log message:
acpica-utils: clean up patch lost in the update and left behind with
no checksum for it
fixes clang build by removing GCC-specific build flags
Log message:
acpica-utils: update to 20160930
----------------------------------------
30 September 2016. Summary of changes for version 20160930:
1) ACPICA kernel-resident subsystem:
Fixed a regression in the internal AcpiTbFindTable function where a non
AE_OK exception could inadvertently be returned even if the function did
not fail. This problem affects the following operators:
DataTableRegion
LoadTable
Fixed a regression in the LoadTable operator where a load to any
namespace location other than the root no longer worked properly.
Increased the maximum loop count value that will result in the
AE_AML_INFINITE_LOOP exception. This is a mechanism that is intended to
prevent infinite loops within the AML interpreter and thus the host OS
kernel. The value is increased from 0xFFFF to 0xFFFFF loops (65,535 to
1,048,575).
Moved the AcpiGbl_MaxLoopIterations configuration variable to the public
acpixf.h file. This allows hosts to easily configure the maximum loop
count at runtime.
Removed an illegal character in the strtoul64.c file. This character
caused errors with some C compilers..4K Code, 58.1K Data, 198.5K Total
Debug Version: 200.7K Code, 82.1K Data, 282.8K Total
Previous Release:
Non-Debug Version: 140.0K Code, 58.1K Data, 198.1K Total
Debug Version: 200.3K Code, 82.1K Data, 282.4K Total
2) iASL Compiler/Disassembler and Tools:
Disassembler: Fixed a problem with the conversion of Else{If{ blocks into
the simpler ASL ElseIf keyword. During the conversion, a trailing If
block could be lost and missing from the disassembled output.
iASL: Fixed a missing parser rule for the ObjectType operator. For ASL+,
the missing rule caused a parse error when using the Index operator as an
operand to ObjectType. This construct now compiles properly. Example:
ObjectType(PKG1[4]).
iASL: Correctly handle unresolved symbols in the hardware map file (-lm
option). Previously, unresolved symbols could cause a protection fault.
Such symbols are now marked as unresolved in the map file.
iASL: Implemented support to allow control method invocations as an
operand to the ASL DeRefOf operator. Example:
DeRefOf(MTH1(Local0))
Disassembler: Improved support for the ToPLD ASL macro. Detection of a
possible _PLD buffer now includes examination of both the normal buffer
length (16 or 20) as well as the surrounding AML package length.
Disassembler: Fixed a problem with the decoding of complex expressions
within the Divide operator for ASL+. For the case where both the quotient
and remainder targets are specified, the entire statement cannot be
disassembled. Previously, the output incorrectly contained a mix of ASL-
and ASL+ operators. This mixed statement causes a syntax error when
compiled. Example:
Divide (Add (INT1, 6), 128, RSLT, QUOT) // was incorrectly
disassembled to:
Divide (INT1 + 6, 128, RSLT, QUOT)
iASL/Tools: Added support to process AML and non-AML ACPI tables
consistently. For the disassembler and AcpiExec, allow all types of ACPI
tables (AML and data tables). For the iASL -e option, allow only AML
tables (DSDT/SSDT).
----------------------------------------
31 August 2016. Summary of changes for version 20160831:
1) ACPICA kernel-resident subsystem:
Improve support for the so-called "module-level code", which is defined
to be math, logical and control AML opcodes that appear outside of any
control method. This change improves the support by adding more opcodes
that can be executed in the manner. Some other issues have been solved,
and the ASL grammar changes to support such code under all scope
operators (Device, etc.) are complete. Lv Zheng.
UEFI support: these OSL functions have been implemented. This is an
additional step toward supporting the AcpiExec utility natively (with
full hardware access) under UEFI. Marcelo Ferreira.
AcpiOsReadPciConfiguration
AcpiOsWritePciConfiguration
Fixed a possible mutex error during control method auto-serialization. Lv
Zheng.
Updated support for the Generic Address Structure by fully implementing
all GAS fields when a 32-bit address is expanded to a 64-bit GAS. Lv
Zheng.
Updated the return value for the internal _OSI method. Instead of
0xFFFFFFFF, the "Ones" value is now returned, which is 0xFFFFFFFFFFFFFFFF
for 64-bit ACPI tables. This fixes an incompatibility with other ACPI
implementations, and will be reflected and clarified in the next version
of the ACPI specification.
Implemented two new table events that can be passed to an ACPICA table
handler. These events are used to indicate a table installation or
uninstallation. These events are used in addition to existed table load
and unload events. Lv Zheng.
Implemented a cleanup for all internal string-to-integer conversions.
Consolidate multiple versions of this functionality and limit possible
bases to either 10 or 16 to simplify the code. Adds a new file,
utstrtoul64.
Cleanup the inclusion order of the various compiler-specific headers.
This simplifies build configuration management. The compiler-specific
headers are now split out from the host-specific headers..1K Code, 58.1K Data, 198.1K Total
Debug Version: 200.3K Code, 82.1K Data, 282.4K Total
2) iASL Compiler/Disassembler and Tools:
iASL/AcpiExec: Added a command line option to display the build date/time
of the tool (-vd). This can be useful to verify that the correct version
of the tools are being used.
AML Debugger: Implemented a new subcommand ("execute predef") to execute
all predefined control methods and names within the current namespace.
This can be useful for debugging problems with ACPI tables and the ACPI
namespace.
----------------------------------------
29 July 2016. Summary of changes for version 20160729:
1) ACPICA kernel-resident subsystem:
Implemented basic UEFI support for the various ACPICA tools. This
includes:
1) An OSL to implement the various AcpiOs* interfaces on UEFI.
2) Support to obtain the ACPI tables on UEFI.
3) Local implementation of required C library functions not available on
UEFI.
4) A front-end (main) function for the tools for UEFI-related
initialization.
The initial deployment of this support is the AcpiDump utility executing
as an UEFI application via EDK2 (EDKII, "UEFI Firmware Development Kit").
Current environments supported are Linux/Unix. MSVC generation is not
supported at this time. See the generate/efi/README file for build
instructions. Lv Zheng.
Future plans include porting the AcpiExec utility to execute natively on
the platform with I/O and memory access. This will allow viewing/dump of
the platform namespace and native execution of ACPI control methods that
access the actual hardware. To fully implement this support, the OSL
functions below must be implemented with UEFI interfaces. Any community
help in the implementation of these functions would be appreciated:
AcpiOsReadPort
AcpiOsWritePort
AcpiOsReadMemory
AcpiOsWriteMemory
AcpiOsReadPciConfiguration
AcpiOsWritePciConfiguration
Restructured and standardized the C library configuration for ACPICA,
resulting in the various configuration options below. This includes a
global restructuring of the compiler-dependent and platform-dependent
include files. These changes may affect the existing platform-dependent
configuration files on some hosts. Lv Zheng.
The current C library configuration options appear below. For any issues,
it may be helpful to examine the existing compiler-dependent and
platform-dependent files as examples. Lv Zheng.
1) Linux kernel:
ACPI_USE_STANDARD_HEADERS=n in order not to use system-provided C
library.
ACPI_USE_SYSTEM_CLIBRARY=y in order not to use ACPICA mini C library.
2) Unix/Windows/BSD applications:
ACPI_USE_STANDARD_HEADERS=y in order to use system-provided C
library.
ACPI_USE_SYSTEM_CLIBRARY=y in order not to use ACPICA mini C library.
3) UEFI applications:
ACPI_USE_STANDARD_HEADERS=n in order not to use system-provided C
library.
ACPI_USE_SYSTEM_CLIBRARY=n in order to use ACPICA mini C library.
4) UEFI applications (EDK2/StdLib):
ACPI_USE_STANDARD_HEADERS=y in order to use EDK2 StdLib C library.
ACPI_USE_SYSTEM_CLIBRARY=y in order to use EDK2 StdLib C library.
AML interpreter: "module-level code" support. Allows for execution of so-
called "executable" AML code (math/logical operations, etc.) outside of
control methods not just at the module level (top level) but also within
any scope declared outside of a control method - Scope{}, Device{},
Processor{}, PowerResource{}, and ThermalZone{}. Lv Zheng.
Simplified the configuration of the "maximum AML loops" global option by
adding a global public variable, "AcpiGbl_MaxLoopIterations" which can be
modified at runtime.: 139.1K Code, 22.9K Data, 162.0K Total
Debug Version: 199.0K Code, 81.8K Data, 280.8K Total
2) iASL Compiler/Disassembler and Tools:
iASL: Add full support for the RASF ACPI table (RAS Features Table).
Includes disassembler, data table compiler, and header support.
iASL Expand "module-level code" support. Allows for
compilation/disassembly of so-called "executable" AML code (math/logical
operations, etc.) outside of control methods not just at the module level
(top level) but also within any scope declared outside of a control
method - Scope{}, Device{}, Processor{}, PowerResource{}, and
ThermalZone{}.
AcpiDump: Added support for dumping all SSDTs on newer versions of
Windows. These tables are now easily available -- SSDTs are not available
through the registry on older versions.
----------------------------------------
27 May 2016. Summary of changes for version 20160527:
1) ACPICA kernel-resident subsystem:
Temporarily reverted the new arbitrary bit length/alignment support in
AcpiHwRead/AcpiHwWrite for the Generic Address Structure. There have been
a number of regressions with the new code that need to be fully resolved
and tested before this support can be finally integrated into ACPICA.
Apologies for any inconveniences these issues may have caused.
The ACPI message macros are not configurable (ACPI_MSG_ERROR,
ACPI_MSG_EXCEPTION, ACPI_MSG_WARNING, ACPI_MSG_INFO, ACPI_MSG_BIOS_ERROR,
and ACPI_MSG_BIOS_WARNING). Lv Zheng.
Fixed a couple of GCC warnings associated with the use of the -Wcast-qual
option. Adds a new return macro, return_STR. Junk-uk K: 136.8K Code, 51.6K Data, 188.4K Total
Debug Version: 201.5K Code, 82.2K Data, 283.7K Total
Previous Release:
Non-Debug Version: 137.4K Code, 52.6K Data, 190.0K Total
Debug Version: 200.9K Code, 82.2K Data, 283.1K Total
----------------------------------------
22 April 2016. Summary of changes for version 20160422:
1) ACPICA kernel-resident subsystem:
Fixed a regression in the GAS (generic address structure) arbitrary bit
support in AcpiHwRead/AcpiHwWrite. Problem could cause incorrect behavior
and incorrect return values. Lv Zheng. ACPICA BZ 1270.
ACPI 6.0: Added support for new/renamed resource macros. One new argument
was added to each of these macros, and the original name has been
deprecated. The AML disassembler will always disassemble to the new
names. Support for the new macros was added to iASL, disassembler,
resource manager, and the acpihelp utility. ACPICA BZ 1274.
I2cSerialBus -> I2cSerialBusV2
SpiSerialBus -> SpiSerialBusV2
UartSerialBus -> UartSerialBusV2
ACPI 6.0: Added support for a new integer field that was appended to the
package object returned by the _BIX method. This adds iASL compile-time
and AML runtime error checking. ACPICA BZ 1273.
ACPI 6.1: Added support for a new PCCT subtable, "HW-Reduced Comm
Subspace Type2" (Headers, Disassembler, and data table compiler)..4K Code, 52.6K Data, 190.0K Total
Debug Version: 201.5K Code, 82.2K Data, 283.7K Total
Previous Release:
Non-Debug Version: 137.1K Code, 51.5K Data, 188.6K Total
Debug Version: 201.0K Code, 82.0K Data, 283.0K Total
2) iASL Compiler/Disassembler and Tools:
iASL: Implemented an ASL grammar extension to allow/enable executable
"module-level code" to be created and executed under the various
operators that create new scopes. This type of AML code is already
supported in all known AML interpreters, and the grammar change will
appear in the next version of the ACPI specification. Simplifies the
conditional runtime creation of named objects under these object types:
Device
PowerResource
Processor
Scope
ThermalZone
iASL: Implemented a new ASL extension, a "For" loop macro to add greater
ease-of-use to the ASL language. The syntax is similar to the
corresponding C operator, and is implemented with the existing AML While
opcode -- thus requiring no changes to existing AML interpreters.
For (Initialize, Predicate, Update) {TermList}
Grammar:
ForTerm :=
For (
Initializer // Nothing | TermArg => ComputationalData
Predicate // Nothing | TermArg => ComputationalData
Update // Nothing | TermArg => ComputationalData
) {TermList}
iASL: The _HID/_ADR detection and validation has been enhanced to search
under conditionals in order to allow these objects to be conditionally
created at runtime.
iASL: Fixed several issues with the constant folding feature. The
improvement allows better detection and resolution of statements that can
be folded at compile time. ACPICA BZ 1266.
iASL/Disassembler: Fixed a couple issues with the Else{If{}...}
conversion to the ASL ElseIf operator where incorrect ASL code could be
generated.
iASL/Disassembler: Fixed a problem with the ASL+ code disassembly where
sometimes an extra (and extraneous) set of parentheses were emitted for
some combinations of operators. Although this did not cause any problems
with recompilation of the disassembled code, it made the code more
difficult to read. David Box. ACPICA BZ 1231.
iASL: Changed to ignore the unreferenced detection for predefined names
of resource descriptor elements, when the resource descriptor is
created/defined within a control method.
iASL: Disassembler: Fix a possible fault with externally declared Buffer
objects.
----------------------------------------
18 March 2016. Summary of changes for version 20160318:
1) ACPICA kernel-resident subsystem:
Added support for arbitrary bit lengths and bit offsets for registers
defined by the Generic Address Structure. Previously, only aligned bit
lengths of 8/16/32/64 were supported. This was sufficient for many years,
but recently some machines have been seen that require arbitrary bit-
level support. ACPICA BZ 1240. Lv Zheng.
Fixed an issue where the \_SB._INI method sometimes must be evaluated
before any _REG methods are evaluated. Lv Zheng.
Implemented several changes related to ACPI table support
(Headers/Disassembler/TableCompiler):
NFIT: For ACPI 6.1, updated to add some additional new fields and
constants.
FADT: Updated a warning message and set compliance to ACPI 6.1 (Version
6).
DMAR: Added new constants per the 10/2014 DMAR spec.
IORT: Added new subtable per the 10/2015 IORT spec.
HEST: For ACPI 6.1, added new constants and new subtable.
DBG2: Added new constants per the 12/2015 DBG2 spec.
FPDT: Fixed several incorrect fields, add the FPDT boot record structure.
ACPICA BZ 1249.
ERST/EINJ: Updated disassembler with new "Execute Timings" actions.
Updated header support for the DMAR table to match the current version of
the related spec.
Added extensions to the ASL Concatenate operator to allow any ACPI object
to be passed as an operand. Any object other than Integer/String/Buffer
simply returns a string containing the object type. This extends the
usefulness of the Printf macros. Previously, Concatenate would abort the
control method if a non-data object was encountered.
ACPICA source code: Deployed the C "const" keyword across the source code
where appropriate. ACPICA BZ 732. Joerg Sonnenberger (NetBS.1K Code, 51.5K Data, 188.6K Total
Debug Version: 201.0K Code, 82.0K Data, 283.0K Total
Previous Release:
Non-Debug Version: 136.2K Code, 51.5K Data, 187.7K Total
Debug Version: 200.4K Code, 82.0K Data, 282.4K Total
2) iASL Compiler/Disassembler and Tools:
iASL/Disassembler: Improved the heuristic used to determine the number of
arguments for an externally defined control method (a method in another
table). Although this is an improvement, there is no deterministic way to
"guess" the number of method arguments. Only the ACPI 6.0 External opcode
will completely solve this problem as it is deployed (automatically) in
newer BIOS code.
iASL/Disassembler: Fixed an ordering issue for emitted External() ASL
statements that could cause errors when the disassembled file is
compiled. ACPICA BZ 1243. David Box.
iASL: Fixed a regression caused by the merger of the two versions of the
local strtoul64. Because of a dependency on a global variable, strtoul64
could return an error for integers greater than a 32-bit value. ACPICA BZ
1260.
iASL: Fixed a regression where a fault could occur for an ASL Return
statement if it invokes a control method that is not resolved. ACPICA BZ
1264.
AcpiXtract: Improved input file validation: detection of binary files and
non-acpidump text files.
----------------------------------------
12 February 2016. Summary of changes for version 20160212:
1) ACPICA kernel-resident subsystem:
Implemented full support for the ACPI 6.1 specification (released in
January). This version of the specification is available at:
Only a relatively small number of changes were required in ACPICA to
support ACPI 6.1, in these areas:
- New predefined names
- New _HID values
- A new subtable for HEST
- A few other header changes for new values
Ensure \_SB_._INI is executed before any _REG methods are executed. There
appears to be existing BIOS code that relies on this behavior. Lv Zheng.
Reverted a change made in version 20151218 which enabled method
invocations to be targets of various ASL operators (SuperName and Target
grammar elements). While the new behavior is supported by the ACPI
specification, other AML interpreters do not support this behavior and
never will. The ACPI specification will be updated for ACPI 6.2 to remove
this support. Therefore, the change was reverted to the original ACPICA
behavior.
ACPICA now supports the GCC 6 compiler.
Current Release: (Note: build changes increased sizes)
Non-Debug Version: 136.2K Code, 51.5K Data, 187.7K Total
Debug Version: 200.4K Code, 82.0K Data, 282.4K Total
Previous Release:
Non-Debug Version: 102.7K Code, 28.4K Data, 131.1K Total
Debug Version: 200.4K Code, 81.9K Data, 282.3K Total
2) iASL Compiler/Disassembler and Tools:
Completed full support for the ACPI 6.0 External() AML opcode. The
compiler emits an external AML opcode for each ASL External statement.
This opcode is used by the disassembler to assist with the disassembly of
external control methods by specifying the required number of arguments
for the method. AML interpreters do not use this opcode. To ensure that
interpreters do not even see the opcode, a block of one or more external
opcodes is surrounded by an "If(0)" construct. As this feature becomes
commonly deployed in BIOS code, the ability of disassemblers to correctly
disassemble AML code will be greatly improved. David Box.
iASL: Implemented support for an optional cross-reference output file.
The -lx option will create a the cross-reference file with the suffix
"xrf". Three different types of cross-reference are created in this file:
- List of object references made from within each control method
- Invocation (caller) list for each user-defined control method
- List of references to each non-method object in the namespace
iASL: Method invocations as ASL Target operands are now disallowed and
flagged as errors in preparation for ACPI 6.2 (see the description of the
problem above).
----------------------------------------
8 January 2016. Summary of changes for version 20160108:
1) ACPICA kernel-resident subsystem:
Updated all ACPICA copyrights and signons to 2016: Added the 2016
This includes the standard Linux dual-license header. This affects
virtually every file in the ACPICA core subsystem, iASL compiler, all
ACPICA utilities, and the ACPICA test suite.
Fixed a regression introduced in version 20151218 concerning the
execution of so-called module-level ASL/AML code. Namespace objects
created under a module-level If() construct were not properly/fully
entered into the namespace and could cause an interpreter fault when
accessed..7K Code, 28.4K Data, 131.1K Total
Debug Version: 200.4K Code, 81.9K Data, 282.4K Total
Previous Release:
Non-Debug Version: 102.6K Code, 28.4K Data, 131.0K Total
Debug Version: 200.3K Code, 81.9K Data, 282.3K Total
2) iASL Compiler/Disassembler and Tools:
Fixed a problem with the compilation of the GpioIo and GpioInt resource
descriptors. The _PIN field name was incorrectly defined to be an array
of 32-bit values, but the _PIN values are in fact 16 bits each. This
would cause incorrect bit width warnings when using Word (16-bit) fields
to access the descriptors.
----------------------------------------
18 December 2015. Summary of changes for version 20151218:
1) ACPICA kernel-resident subsystem:
Implemented per-AML-table execution of "module-level code" as individual
ACPI tables are loaded into the namespace during ACPICA initialization.
In other words, any module-level code within an AML table is executed
immediately after the table is loaded, instead of batched and executed
after all of the tables have been loaded. This provides compatibility
with other ACPI implementations. ACPICA BZ 1219. Bob Moore, Lv Zheng,
David Box.
To fully support the feature above, the default operation region handlers
for the SystemMemory, SystemIO, and PCI_Config address spaces are now
installed before any ACPI tables are loaded. This enables module-level
code to access these address spaces during the table load and module-
level code execution phase. ACPICA BZ 1220. Bob Moore, Lv Zheng, David
Box.
Implemented several changes to the internal _REG support in conjunction
with the changes above. Also, changes to the AcpiExec/AcpiNames/Examples
utilities for the changes above. Although these tools were changed, host
operating systems that simply use the default handlers for SystemMemory,
SystemIO, and PCI_Config spaces should not require any update. Lv Zheng.
For example, in the code below, DEV1 is conditionally added to the
namespace by the DSDT via module-level code that accesses an operation
region. The SSDT references DEV1 via the Scope operator. DEV1 must be
created immediately after the DSDT is loaded in order for the SSDT to
successfully reference DEV1. Previously, this code would cause an
AE_NOT_EXIST exception during the load of the SSDT. Now, this code is
fully supported by ACPICA.
DefinitionBlock ("", "DSDT", 2, "Intel", \
"DSDT1", 1)
{
OperationRegion (OPR1, SystemMemory, 0x400, 32)
Field (OPR1, AnyAcc, NoLock, Preserve)
{
FLD1, 1
}
If (FLD1)
{
Device (\DEV1)
{
}
}
}
DefinitionBlock ("", "SSDT", 2, "Intel", \
"SSDT1", 1)
{
External (\DEV1, DeviceObj)
Scope (\DEV1)
{
}
}
Fixed an AML interpreter problem where control method invocations were
not handled correctly when the invocation was itself a SuperName argument
to another ASL operator. In these cases, the method was not invoked.
ACPICA BZ 1002. Affects the following ASL operators that have a SuperName
argument:
Store
Acquire, Wait
CondRefOf, RefOf
Decrement, Increment
Load, Unload
Notify
Signal, Release, Reset
SizeOf
Implemented automatic String-to-ObjectReference conversion support for
packages returned by predefined names (such as _DEP). A common BIOS error
is to add double quotes around an ObjectReference namepath, which turns
the reference into an unexpected string object. This support detects the
problem and corrects it before the package is returned to the caller that
invoked the method. Lv Zheng.
Implemented extensions to the Concatenate operator. Concatenate now
accepts any type of object, it is not restricted to simply
Integer/String/Buffer. For objects other than these 3 basic data types,
the argument is treated as a string containing the name of the object
type. This expands the utility of Concatenate and the Printf/Fprintf
macros. ACPICA BZ 1222.
Cleaned up the output of the ASL Debug object. The timer() value is now
optional and no longer emitted by default. Also, the basic data types of
Integer/String/Buffer are simply emitted as their values, without a data
type string -- since the data type is obvious from the output. ACPICA BZ
1221..6K Code, 28.4K Data, 131.0K Total
Debug Version: 200.3K Code, 81.9K Data, 282.3K Total
Previous Release:
Non-Debug Version: 102.0K Code, 28.3K Data, 130.3K Total
Debug Version: 199.6K Code, 81.8K Data, 281.4K Total
2) iASL Compiler/Disassembler and Tools:
iASL: Fixed some issues with the ASL Include() operator. This operator
was incorrectly defined in the iASL parser rules, causing a new scope to
be opened for the code within the include file. This could lead to
several issues, including allowing ASL code that is technically illegal
and not supported by AML interpreters. Note, this does not affect the
related #include preprocessor operator. ACPICA BZ 1212.
iASL/Disassembler: Implemented support for the ASL ElseIf operator. This
operator is essentially an ASL macro since there is no AML opcode
associated with it. The code emitted by the iASL compiler for ElseIf is
an Else opcode followed immediately by an If opcode. The disassembler
will now emit an ElseIf if it finds an Else immediately followed by an
If. This simplifies the decoded ASL, especially for deeply nested
If..Else and large Switch constructs. Thus, the disassembled code more
closely follows the original source ASL. ACPICA BZ 1211. Example:
Old disassembly:
Else
{
If (Arg0 == 0x02)
{
Local0 = 0x05
}
}
New disassembly:
ElseIf (Arg0 == 0x02)
{
Local0 = 0x05
}
AcpiExec: Added support for the new module level code behavior and the
early region installation. This required a small change to the
initialization, since AcpiExec must install its own operation region
handlers.
AcpiExec: Added support to make the debug object timer optional. Default
is timer disabled. This cleans up the debug object output -- the timer
data is rarely used.
AcpiExec: Multiple ACPI tables are now loaded in the order that they
appear on the command line. This can be important when there are
interdependencies/references between the tables.
iASL/Templates. Add support to generate template files with multiple
SSDTs within a single output file. Also added ommand line support to
specify the number of SSDTs (in addition to a single DSDT). ACPICA BZ
1223, 1225.
----------------------------------------
24 November 2015. Summary of changes for version 20151124:
1) ACPICA kernel-resident subsystem:
Fixed a possible regression for a previous update to FADT handling. The
FADT no longer has a fixed table ID, causing some issues with code that
was hardwired to a specific ID. Lv Zheng.
Fixed a problem where the method auto-serialization could interfere with
the current SyncLevel. This change makes the auto-serialization support
transparent to the SyncLevel support and management.
Removed support for the _SUB predefined name in AcpiGetObjectInfo. This
interface is intended for early access to the namespace during the
initial namespace device discovery walk. The _SUB method has been seen to
access operation regions in some cases, causing errors because the
operation regions are not fully initialized.
AML Debugger: Fixed some issues with the terminate/quit/exit commands
that can cause faults. Lv Zheng.
AML Debugger: Add thread ID support so that single-step mode only applies
to the AML Debugger thread. This prevents runtime errors within some
kernels. Lv Zheng.
Eliminated extraneous warnings from AcpiGetSleepTypeData. Since the _Sx
methods that are invoked by this interface are optional, removed warnings
emitted for the case where one or more of these methods do not exist.
ACPICA BZ 1208, original change by Prarit Bhargava.
Made a major pass through the entire ACPICA source code base to
standardize formatting that has diverged a bit over time. There are no
functional changes, but this will of course cause quite a few code
differences from the previous ACPICA release..0K Code, 28.3K Data, 130.3K Total
Debug Version: 199.6K Code, 81.8K Data, 281.4K Total
Previous Release:
Non-Debug Version: 101.7K Code, 27.9K Data, 129.6K Total
Debug Version: 199.3K Code, 81.4K Data, 280.7K Total
2) iASL Compiler/Disassembler and Tools:
iASL/acpiexec/acpixtract/disassembler: Added support to allow multiple
definition blocks within a single ASL file and the resulting AML file.
Support for this type of file was also added to the various tools that
use binary AML files: acpiexec, acpixtract, and the AML disassembler. The
example code below shows two definition blocks within the same file:
DefinitionBlock ("dsdt.aml", "DSDT", 2, \
"Intel", "Template",
0x12345678)
{
}
DefinitionBlock ("", "SSDT", 2, "Intel", \
"Template", 0xABCDEF01)
{
}
iASL: Enhanced typechecking for the Name() operator. All expressions for
the value of the named object must be reduced/folded to a single constant
at compile time, as per the ACPI specification (the AML definition of
Name()).
iASL: Fixed some code indentation issues for the -ic and -ia options (C
and assembly headers). Now all emitted code correctly begins in column 1.
iASL: Added an error message for an attempt to open a Scope() on an
object defined in an SSDT. The DSDT is always loaded into the namespace
first, so any attempt to open a Scope on an SSDT object will fail at
runtime.
----------------------------------------
30 September 2015. Summary of changes for version 20150930:
1) ACPICA kernel-resident subsystem:
Debugger: Implemented several changes and bug fixes to assist support for
the in-kernel version of the AML debugger. Lv Zheng.
- Fix the "predefined" command for in-kernel debugger.
- Do not enter debug command loop for the help and version commands.
- Disallow "execute" command during execution/single-step of a method.
Interpreter: Updated runtime typechecking for all operators that have
target operands. The operand is resolved and validated that it is legal.
For example, the target cannot be a non-data object such as a Device,
Mutex, ThermalZone, etc., as per the ACPI specification.
Debugger: Fixed the double-mutex user I/O handshake to work when local
deadlock detection is enabled.
Debugger: limited display of method locals and arguments (LocalX and
ArgX) to only those that have actually been initialized. This prevents
lines of extraneous output.
Updated the definition of the NFIT table to correct the bit polarity of
one flag: ACPI_NFIT_MEM_ARMED --> ACPI_NFIT_MEM_NOT_ARMED.7K Code, 27.9K Data, 129.6K Total
Debug Version: 199.3K Code, 81.4K Data, 280.7K Total
Previous Release:
Non-Debug Version: 101.3K Code, 27.7K Data, 129.0K Total
Debug Version: 198.6K Code, 80.9K Data, 279.5K Total
2) iASL Compiler/Disassembler and Tools:
iASL: Improved the compile-time typechecking for operands of many of the
ASL operators:
-- Added an option to disable compiler operand/operator typechecking (-
ot).
-- For the following operators, the TermArg operands are now validated
when possible to be Integer data objects: BankField, OperationRegion,
DataTableRegion, Buffer, and Package.
-- Store (Source, Target): Both the source and target operands are
resolved and checked that the operands are both legal. For example,
neither operand can be a non-data object such as a Device, Mutex,
ThermalZone, etc. Note, as per the ACPI specification, the CopyObject
operator can be used to store an object to any type of target object.
-- Store (Source, Target): If the source is a Package object, the target
must be a Package object, LocalX, ArgX, or Debug. Likewise, if the target
is a Package, the source must also be a Package.
-- Store (Source, Target): A warning is issued if the source and target
resolve to the identical named object.
-- Store (Source, <method invocation>): An error is generated for the
target method invocation, as this construct is not supported by the AML
interpreter.
-- For all ASL math and logic operators, the target operand must be a
data object (Integer, String, Buffer, LocalX, ArgX, or Debug). This
includes the function return value also.
-- External declarations are also included in the typechecking where
possible. External objects defined using the UnknownObj keyword cannot be
typechecked, however.
iASL and Disassembler: Added symbolic (ASL+) support for the ASL Index
operator:
- Legacy code: Index(PKG1, 3)
- New ASL+ code: PKG1[3]
This completes the ACPI 6.0 ASL+ support as it was the only operator not
supported.
iASL: Fixed the file suffix for the preprocessor output file (.i). Two
spaces were inadvertently appended to the filename, causing file access
and deletion problems on some systems.
ASL Test Suite (ASLTS): Updated the master makefile to generate all
possible compiler output files when building the test suite -- thus
exercising these features of the compiler. These files are automatically
deleted when the test suite exits.
----------------------------------------
18 August 2015. Summary of changes for version 20150818:
1) ACPICA kernel-resident subsystem:
Fix a regression for AcpiGetTableByIndex interface causing it to fail. Lv
Zheng. ACPICA BZ 1186.
Completed development to ensure that the ACPICA Disassembler and Debugger
are fully standalone components of ACPICA. Removed cross-component
dependences. Lv Zheng.
The max-number-of-AML-loops is now runtime configurable (previously was
compile-time only). This is essentially a loop timeout to force-abort
infinite AML loops. ACPCIA BZ 1192.
Debugger: Cleanup output to dump ACPI names and namepaths without any
trailing underscores. Lv Zheng. ACPICA BZ 1135.
Removed unnecessary conditional compilations across the Debugger and
Disassembler components where entire modules could be left uncompiled.
The aapits test is deprecated and has been removed from the ACPICA git
tree. The test has never been completed and has not been maintained, thus
becoming rather useless. ACPICA BZ 1015, 794.
A batch of small changes to close bugzilla and other reports:
- Remove duplicate code for _PLD processing. ACPICA BZ 1176.
- Correctly cleanup after a ACPI table load failure. ACPICA BZ 1185.
- iASL: Support POSIX yacc again in makefile. Jung-uk Kim.
- ACPI table support: general cleanup and simplification. Lv Zheng, Bob
Moore.
- ACPI table support: fix for a buffer read overrun in AcpiTbFindTable.
ACPICA BZ 1184.
- Enhance parameter validation for DataTableRegion and LoadTable ASL/AML
operators.
- Debugger: Split debugger initialization/termination interfaces. Lv
Zheng.
- AcpiExec: Emit OemTableId for SSDTs during the load phase for table
identification.
- AcpiExec: Add debug message during _REG method phase during table
load/init.
- AcpiNames: Fix a regression where some output was missing and no longer
emitted.
- Debugger: General cleanup and simplification. Lv Zheng.
- Disassembler: Cleanup use of several global option variables..3K Code, 27.7K Data, 129.0K Total
Debug Version: 198.6K Code, 80.9K Data, 279.5K Total
Previous Release:
Non-Debug Version: 100.9K Code, 24.5K Data, 125.4K Total
Debug Version: 197.8K Code, 81.5K Data, 279.3K Total
2) iASL Compiler/Disassembler and Tools:
AcpiExec: Fixed a problem where any more than 32 ACPI tables in the XSDT
were not handled properly and caused load errors. Now, properly invoke
and use the ACPICA auto-reallocate mechanism for ACPI table data
structures. ACPICA BZ 1188
AcpiNames: Add command-line wildcard support for ACPI table files. ACPICA
BZ 1190.
AcpiExec and AcpiNames: Add -l option to load ACPI tables only. For
AcpiExec, this means that no control methods (like _REG/_INI/_STA) are
executed during initialization. ACPICA BZ 1187, 1189.
iASL/Disassembler: Implemented a prototype "listing" mode that emits AML
that corresponds to each disassembled ASL statement, to simplify
debugging. ACPICA BZ 1191.
Debugger: Add option to the "objects" command to display a summary of the
current namespace objects (Object type and count). This is displayed if
the command is entered with no arguments.
AcpiNames: Add -x option to specify debug level, similar to AcpiExec.
----------------------------------------
17 July 2015. Summary of changes for version 20150717:
1) ACPICA kernel-resident subsystem:
Improved the partitioning between the Debugger and Disassembler
components. This allows the Debugger to be used standalone within kernel
code without the Disassembler (which is used for single stepping also).
This renames and moves one file, dmobject.c to dbobject.c. Lv Zheng.
Debugger: Implemented a new command to trace the execution of control
methods (Trace). This is especially useful for the in-kernel version of
the debugger when file I/O may not be available for method trace output.
See the ACPICA reference for more information. Lv Zheng.
Moved all C library prototypes (used for the local versions of these
functions when requested) to a new header, acclib.h
Cleaned up the use of non-ANSI C library functions. These functions are
implemented locally in ACPICA. Moved all such functions to a common
source file, utnonansi.c
Debugger: Fixed a problem with the "!!" command (get last command
executed) where the debugger could enter an infinite loop and eventually
crash.
Removed the use of local macros that were used for some of the standard C
library functions to automatically cast input parameters. This mostly
affected the is* functions where the input parameter is defined to be an
int. This required a few modifications to the main ACPICA source code to
provide casting for these functions and eliminate possible compiler
warnings for these parameters.
Across the source code, added additional status/error checking to resolve
issues discovered by static source code analysis tools such as Cover.9K Code, 24.5K Data, 125.4K Total
Debug Version: 197.8K Code, 81.5K Data, 279.3K Total
Previous Release:
Non-Debug Version: 100.6K Code, 27.6K Data, 128.2K Total
Debug Version: 196.2K Code, 81.0K Data, 277.2K Total
2) iASL Compiler/Disassembler and Tools:
iASL: Fixed a regression where the device map file feature no longer
worked properly when used in conjunction with the disassembler. It only
worked properly with the compiler itself.
iASL: Implemented a new warning for method LocalX variables that are set
but never used (similar to a C compiler such as gcc). This also applies
to ArgX variables that are not defined by the parent method, and are
instead (legally) used as local variables.
iASL/Preprocessor: Finished the pass-through of line numbers from the
preprocessor to the compiler. This ensures that compiler errors/warnings
have the correct original line numbers and filenames, regardless of any
#include files.
iASL/Preprocessor: Fixed a couple of issues with comment handling and the
pass-through of comments to the preprocessor output file (which becomes
the compiler input file). Also fixed a problem with // comments that
appear after a math expression.
iASL: Added support for the TCPA server table to the table compiler and
template generator. (The client table was already previously supported)
iASL/Preprocessor: Added a permanent #define of the symbol "__IASL__" to
identify the iASL compiler.
Cleaned up the use of the macros NEGATIVE and POSITIVE which were defined
multiple times. The new names are ACPI_SIGN_NEGATIVE and
ACPI_SIGN_POSITIVE.
AcpiHelp: Update to expand help messages for the iASL preprocessor
directives.
----------------------------------------
19 June 2015. Summary of changes for version 20150619:
Two regressions in version 20150616 have been addressed:
Fixes some problems/issues with the C library macro removal (ACPI_STRLEN,
etc.) This update changes ACPICA to only use the standard headers for
functions, or the prototypes for the local versions of the C library
functions. Across the source code, this required some additional casts
for some Clib invocations for portability. Moved all local prototypes to
a new file, acclib.h
Fixes several problems with recent changes to the handling of the FACS
table that could cause some systems not to boot.
----------------------------------------
16 June 2015. Summary of changes for version 20150616:
1) ACPICA kernel-resident subsystem:
Across the entire ACPICA source code base, the various macros for the C
library functions (such as ACPI_STRLEN, etc.) have been removed and
replaced by the standard C library names (strlen, etc.) The original
purpose for these macros is no longer applicable. This simplification
reduces the number of macros used in the ACPICA source code
significantly, improving readability and maintainability.
Implemented support for a new ACPI table, the OSDT. This table, the
"override" SDT, can be loaded directly by the host OS at boot time. It
enables the replacement of existing namespace objects that were installed
via the DSDT and/or SSDTs. The primary purpose for this is to replace
buggy or incorrect ASL/AML code obtained via the BIOS. The OSDT is slated
for inclusion in a future version of the ACPI Specification. Lv Zheng/Bob
Moore.
Added support for systems with (improperly) two FACS tables -- a "32-bit"
table (via FADT 32-bit legacy field) and a "64-bit" table (via the 64-bit
X field). This change will support both automatically. There continues to
be systems found with this issue. This support requires a change to the
AcpiSetFirmwareWakingVector interface. Also, a public global variable has
been added to allow the host to select which FACS is desired
(AcpiGbl_Use32BitFacsAddresses). See the ACPICA reference for more
details Lv Zheng.
Added a new feature to allow for systems that do not contain an FACS.
Although this is already supported on hardware-reduced platforms, the
feature has been extended for all platforms. The reasoning is that we do
not want to abort the entire ACPICA initialization just because the
system is seriously buggy and has no FACS.
Fixed a problem where the GUID strings for NFIT tables (in acuuid.h) were
not correctly transcribed from the ACPI specification in ACPICA version
20150515.
Implemented support for the _CLS object in the AcpiGetObjectInfo external
interface.
Updated the definitions of the TCPA and TPM2 ACPI tables to the more
recent TCG ACPI Specification, December 14, 2014. Table disassembler and
compiler also updated. Note: The TCPA "server" table is not supported by
the disassembler/table-compiler at this time.
ACPI 6.0: Added definitions for the new GIC version field in the MAD.6K Code, 27.6K Data, 128.2K Total
Debug Version: 196.2K Code, 81.0K Data, 277.2K Total
Previous Release:
Non-Debug Version: 99.9K Code, 27.5K Data, 127.4K Total
Debug Version: 195.2K Code, 80.8K Data, 276.0K Total
2) iASL Compiler/Disassembler and Tools:
Disassembler: Fixed a problem with the new symbolic operator disassembler
where incorrect ASL code could be emitted in some cases for the "non-
commutative" operators -- Subtract, Divide, Modulo, ShiftLeft, and
ShiftRight. The actual problem cases seem to be rather unusual in common
ASL code, however. David Box.
Modified the linux version of acpidump to obtain ACPI tables from not
just /dev/mem (which may not exist) and /sys/firmware/acpi/tables. Lv
Zheng.
iASL: Fixed a problem where the user preprocessor output file (.i)
contained extra data that was not expected. The compiler was using this
file as a temporary file and passed through #line directives in order to
keep compiler error messages in sync with the input file and line number
across multiple include files. The (.i) is no longer a temporary file as
the compiler uses a new, different file for the original purpose.
iASL: Fixed a problem where comments within the original ASL source code
file were not passed through to the preprocessor output file, nor any
listing files.
iASL: Fixed some issues for the handling of the "#include" preprocessor
directive and the similar (but not the same) "Include" ASL operator.
iASL: Add support for the new OSDT in both the disassembler and compiler.
iASL: Fixed a problem with the constant folding support where a Buffer
object could be incorrectly generated (incorrectly formed) during a
conversion to a Store() operator.
AcpiHelp: Updated for new NFIT GUIDs, "External" AML opcode, and new
description text for the _REV predefined name. _REV now permanently
returns 2, as per the ACPI 6.0 specification.
Debugger: Enhanced the output of the Debug ASL object for references
produced by the Index operator. For Buffers and strings, only output the
actual byte pointed to by the index. For packages, only print the single
package element decoded by the index. Previously, the entire
buffer/string/package was emitted.
iASL/Table-compiler: Fixed a regression where the "generic" data types
were no longer recognized, causing errors.
----------------------------------------
15 May 2015. Summary of changes for version 20150515:
This release implements most of ACPI 6.0 as described below.
1) ACPICA kernel-resident subsystem:
Implemented runtime argument checking and return value checking for all
new ACPI 6.0 predefined names. This includes: _BTH, _CR3, _DSD, _LPI,
_MTL, _PRR, _RDI, _RST, _TFP, _TSN.: 99.9K Code, 27.5K Data, 127.4K Total
Debug Version: 195.2K Code, 80.8K Data, 276.0K Total
Previous Release:
Non-Debug Version: 99.1K Code, 27.3K Data, 126.4K Total
Debug Version: 192.8K Code, 79.9K Data, 272.7K Total
2) iASL Compiler/Disassembler and Tools:
iASL compiler: Added compile-time support for all new ACPI 6.0 predefined
names (argument count validation and return value typechecking.)
iASL disassembler and table compiler: implemented support for all new
ACPI 6.0 tables. This includes: DRTM, IORT, LPIT, NFIT, STAO, WPBT, XENV.
iASL disassembler and table compiler: Added ACPI 6.0 changes to existing
tables: FADT, MADT.
iASL preprocessor: Added a new directive to enable inclusion of binary
blobs into ASL code. The new directive is #includebuffer. It takes a
binary file as input and emits a named ascii buffer object into the ASL
code.
AcpiHelp: Added support for all new ACPI 6.0 predefined names.
AcpiHelp: Added a new option, -d, to display all iASL preprocessor
directives.
AcpiHelp: Added a new option, -t, to display all known/supported ACPI
tables.
|
https://pkgsrc.se/sysutils/acpica-utils
|
CC-MAIN-2020-34
|
refinedweb
| 7,339
| 51.55
|
We'll need to share your messages (and your email address if you're logged in) with our live chat provider, Drift. Here's their privacy policy.
If you don't want to do this, you can email us instead at contact@anvil.works.
In the Data Grids Getting Started tutorial, we created a simple paginated table that presented employee data.
Then, the Add Button Tutorial showed how to give the user a widget to add new entries with.
This is great, but what if I accidentally add the wrong data? Usually you’ll want to allow editing the data and deleting rows entirely as well. In this tutorial, we’ll modify the Data Grid to allow just that.
We’ll start with the endpoint of the Add Button Tutorial, and try two approaches to making rows user-editable. We’ll also create a delete button on each row.
To follow along, clone the Data Grids example app with the add button - it’s the starting point you’ll build from.
If you’ve not done the Data Grids Getting Started tutorial, you may find it better to go through that before following this.
A simple way to allow records to be edited is to make all rows editable all the time.
Double-click on the Repeating Panel to open its RowTemplate. You can drag-and-drop TextBoxes and DropDowns into the Repeating Panel, in much the same way as you did for the ‘add’ row.
This time, the new components need to have their contents populated from the existing data.
The Employee TextBox needs a Data Binding that binds its
text property to the employee name:
The Grade TextBox needs a Data Binding that binds its
text property to the pay grade:
The Team DropDown’s
selected_value should be
self.item['team'], so you need to set a Data Binding up for that:
The Team DropDown also needs to have a list of all available teams, for the user to choose between. We need to fetch this
list from the
employees table. There is one DropDown per row, and we don’t want to waste time fetching the data from the server once for every single DropDown,
so we’ll need to store the team list in a global variable. Create a Module called
State and add some code to fetch the set of teams, sorted alphabetically:
# Get a set of all teams teams = {employee['team'] for employee in anvil.server.call('get_employees')} # Cast to a list and sort alphabetically teams = sorted(list(teams))
Now you can import this in
RowTemplate1 and initialise the Team DropDown from it:
from State import teams as TEAMS class RowTemplate1(RowTemplate1Template): def __init__(self, **properties): # ... self.drop_down_team_edit.items = TEAMS
By this stage, you have populated your editable components in your table. But once they are changed, how do you get the data back into the database?
You can’t use the ‘write back’ feature of data bindings because 1) you munge the data slightly before you display it, and
2) your employee data is sensitive, so you don’t want to allow the client to write to the database - that’s why you’ve got
the class RowTemplate1(RowTemplate1Template): # ... def text_box_employee_edit_lost_focus(self, **event_args): """This method is called when the text box loses focus.""" self.edit_employee() def drop_down_teams_edit_change(self, **event_args): """This method is called when the drop down is changed.""" self.edit_employee() def text_box_grade_edit_lost_focus(self, **event_args): """This method is called when the text box loses focus.""" self.edit_employee() def edit_employee(self): first_name, last_name = parse_employee_name(self.text_box_employee_edit.text) anvil.server.call( 'edit_employee', self.item, first_name=first_name, last_name=last_name, team=self.drop_down_teams_edit.selected_value, pay_grade=self.text_box_grade_edit.text, )
Bind these event handlers to the appropriate components using the Properties window.
To edit the data, they call a simple server function - you need to add this to the
DatabaseProxy Server Module:
@anvil.server.callable def edit_employee(employee, first_name, last_name, team, pay_grade): employee.update(first_name=first_name, last_name=last_name, team=team, pay_grade=pay_grade)
And that’s all there is to making the rows editable. Now you have a table where each of the rows is made of editable fields:
Being able to edit the data after you’ve added it is a big improvement. But you might prefer to make most of the table read-only until the user explicitly decides to click an ‘edit’ button.
Maybe you prefer to make the user click a button to make a row editable. This puts more clicks in the user workflow, but it stops the user accidentally editing stuff if they’re a bit click-happy.
You’ve got that ‘column for putting buttons into’ on the right of the Data Grid. In your Repeating Panel, this is currently empty - it’s only used by the Add row for the Add button. Let’s put a Save button into the Repeating Panel. You’ll need to drag-and-drop a FlowPanel into the column first, so that you can put the Delete button in later.
Each row has two states: ‘being edited’ and ‘not being edited’. For each state, you want to show a different set of components. So you need two Data Row Panels in the Repeating Panel. One should be the ‘read view’, showing the employee data when it’s not being edited. The other should be the ‘write view’, showing the employee data using editable components.
The ‘write view’ will be how the row was in the ‘Making all rows editable’ section above, and the ‘read view’ will be how the row was before you made it editable, at the very start of this tutorial. The ‘read view’ should have a button with an ‘edit’ icon ‘write view’ should have a button with a ‘save’ icon.
Make sure you add a new Data Row Panel for the write view and drag the existing components into it. You need to add your own Data Row Panel because you need to be able to refer to it by name in the code.
The pre-existing Data Row Panel that is built in to the Repeating Panel will now not be used. It should have no
components in it and its
auto_display_data should be unchecked.
When the Edit button is clicked, the read view should be hidden, and the write view should be visible:
def button_edit_click(self, **event_args): """This method is called when the button is clicked""" self.data_row_panel_write_view.visible = True self.data_row_panel_read_view.visible = False
The Save button does the opposite. It also includes a call to
edit_employee in order to persist the changes to the
database. (The event handlers for the Write View components must be removed, so they don’t write to the database until
the Save button is clicked.)
The Data Bindings must also be refreshed after save, in order to update the Read View with what’s just been written.
def button_save_click(self, **event_args): """This method is called when the button is clicked""" self.data_row_panel_read_view.visible = True self.data_row_panel_write_view.visible = False self.edit_employee() self.refresh_data_bindings()
That’s the Edit button complete. Now an individual row can be switched into Edit mode, edited, and saved to the database:
Add a Delete button next to the edit button. You’ll probably need to make the column that the buttons are in a bit wider.
Making the Delete button work is simple. Following the now-familiar pattern, create a server function to access the database on the server side:
@anvil.server.callable def delete_employee(employee): employee.delete()
and call it from an event handler on the client side (which also removes the row from the Repeating Panel):
def button_delete_click(self, **event_args): """This method is called when the button is clicked""" anvil.server.call('delete_employee', self.item) self.parent.raise_event('x-refresh-employees')
That final line triggers a custom event on the Repeating Panel to make sure its employee list is updated
to reflect the deletion of the row. You need to set up an event handler in the
__init__ of the outer Form:
class Form1(Form1Template): def __init__(self, **properties): # ... self.repeating_panel_employees.set_event_handler('x-refresh-employees', self.refresh_employees)
And define that
refresh_employees method so that it re-loads the employee data into the Repeating Panel:
def refresh_employees(self, **event_args): self.repeating_panel_employees.items = anvil.server.call('get_employees')
And now your delete button is hooked up.
You now have a table that can Create, Read, Update and Delete data!
To explore the final result, clone the finished app:
Feel free to use it and share it - our code examples are open-source under the Apache License.
Here are our other tutorials on Data Grids:
|
https://anvil.works/blog/data-grid-editable-rows
|
CC-MAIN-2019-22
|
refinedweb
| 1,431
| 62.78
|
SiteTree Models¶
SiteTree comes with Tree and Tree item built-in models to store sitetree data.
Models customization¶
Now let’s pretend you are not satisfied with SiteTree built-in models and want to customize them.
1. First thing you should do is to define your own tree and tree item models inherited from TreeBase and TreeItemBase classes respectively:
# Suppose you have `myapp` application. # In its `models.py` you define your customized models. from sitetree.models import TreeItemBase, TreeBase class MyTree(TreeBase): """This is your custom tree model. And here you add `my_tree_field` to all fields existing in `TreeBase`. """ my_tree_field = models.CharField('My tree field', max_length=50, null=True, blank=True) class MyTreeItem(TreeItemBase): """And that's a tree item model with additional `css_class` field.""" css_class = models.CharField('Tree item CSS class', max_length=50)
2. Now when models.py in your myapp application has the definitions of custom sitetree models, you need to instruct Django to use them for your project instead of built-in ones:
# Somewhere in your settings.py do the following. # Here `myapp` is the name of your application, `MyTree` and `MyTreeItem` # are the names of your customized models. SITETREE_MODEL_TREE = 'myapp.MyTree' SITETREE_MODEL_TREE_ITEM = 'myapp.MyTreeItem'
- Run manage.py syncdb to install your customized models into DB.
Note
As you’ve added new fields to your models, you’ll probably need to tune their Django Admin representation. See Overriding SiteTree Admin representation for more information.
Sitetree definition with custom models¶
Given the example model given above, you can now use the extra fields when defining a sitetree programmatically:, css_class='book-detail'), item('Add a book', 'books-add', css_class='book-add'), item('Edit "{{ book.title }}"', 'books-edit', in_menu=False, in_sitetree=False, css_class='book-edit') ]) ]), # ... You can define more than one tree for your app. )
Models referencing¶
You can reference sitetree models (including customized) from other models, with the help of MODEL_TREE, MODEL_TREE_ITEM settings:
from sitetree.settings import MODEL_TREE, MODEL_TREE_ITEM # As taken from the above given examples # MODEL_TREE will contain `myapp.MyTree`, MODEL_TREE_ITEM - `myapp.MyTreeItem`
If you need to get current tree or tree item classes use get_tree_model and get_tree_item_model functions:
from sitetree.utils import get_tree_model, get_tree_item_model current_tree_class = get_tree_model() # MyTree from myapp.models (from the example above) current_tree_item_class = get_tree_item_model() # MyTreeItem from myapp.models (from the example above)
|
http://django-sitetree.readthedocs.io/en/latest/models.html
|
CC-MAIN-2017-30
|
refinedweb
| 377
| 50.94
|
It has been a long time since .NET version 4.5 was released. To refresh our memory, that happened on August 15th, 2012. Yes, six years ago. Feel old yet? Well, it was not my intention to bum you out but to remind you about some of the highlights of .NET release. One of the main features that this version brought was asynchronous programming using async/await methods. Basically, the guys from Microsoft made the compiler do work that developers used to do by keeping the logical structure that resembles synchronous code.
async
await
You see, back then, Windows Phone was still a thing, and making applications for these platforms had certain limitations. The main one was that Windows Phone, unlike desktop applications, introduced hard limit in which no method could block for more than 50ms. This, in turn, meant that there was no more blocking of the UI for the developers, which led to the necessity for some sort of asynchronicity in the code. .NET 4.5 represents the response to this necessity.
So, why am I writing about something that happened more than half a decade ago? Well, I noticed that even though this is an old topic, there are still a lot of engineers that struggle with the concept. To quote Mike James from iProgrammer:
Often, the programmer is fully aware that what they are doing is object oriented but only vaguely aware that they are writing asynchronous code.
Often, the programmer is fully aware that what they are doing is object oriented but only vaguely aware that they are writing asynchronous code.
That is why I will try to sum up the most important parts of this style of programming in a few blogs posts. Also, we will try to identify situations in which we should use this programming style, as well as the situations when we should avoid it. So, let’s dive right into it!
style="width: 640px; height: 427px" alt="Image 2" data-src="/KB/threads/1245057/348dc338-e7b1-478f-9b10-4e0701781142.Png" class="lazyload" data-sizes="auto" data->
Essentially, this style of programming is applicable to anywhere you need the ability to do something while waiting for something else to be complete. Years of usage of this tool have actually given us the ability to realize where we should use it. It is great for user experience, and in general for event-based systems, e.g., CPU-based parallelism or working with files.
Any activity that is potentially blocking, such as access to the web, is a good candidate for this approach. If any of these blocking activities end up in a synchronous process, the entire application is blocked. On the other hand, if this activity is a part of an asynchronous process, the application can continue working with other tasks until the activity is done.
Of course, you don’t need to abuse this ability. For example, we shouldn’t asynchronously update records that are dependent. It is generally a bad idea and our data will get out of sync very quickly. Apart from that, this concept is sometimes overused. For example, if we are working on some simple actions and operations we should consider more orthodox approaches. Using asynchronous concepts in these cases may, in fact, cause more overhead than benefits.
width="640" alt="Image 3" data-src="/KB/threads/1245057/7c263bdc-f854-4b01-b2c4-3e796a39d000.Png" data-sizes="auto" data->
The asynchronous mechanism is implemented in .NET by using async/await keywords in our code. We use the async operator to mark our methods as asynchronous. Only methods with this operator methods can use await operator in them. Await operator, on the other hand, is telling to the compiler that async method in which it has been used can’t continue past that point until the awaited asynchronous task is complete. Basically, it suspends the execution of the method until awaited task is done. Methods that are marked with async operator also can be called with await operator from the other methods.
Await
Another important thing to mention is that async methods must return Task class or Task class. This is because in this method, await operator is applied to the Task that is returned from another async method. To sum it up, the asynchronous mechanism is in .NET implemented like this:
Task
How does that look into the code? Take a look at this example WebAccess.cs class:
public class WebAccess
{
public async Task<int> AccessRubiksCodeAsync()
{
HttpClient client = new HttpClient();
var getContent = client.GetStringAsync("");
LogToConsole("Yay!");
string content = await getContent;
return content.Length;
}
private void LogToConsole(string message)
{
Console.WriteLine("At the moment I am actually listening to the new NIN song...");
Console.WriteLine("It is pretty cool...like something of David Bowie's - Blackstar.");
Console.WriteLine("message");
}
}
AccessRubiksCodeAsync
Async
LogToConsole
Tas<wbr />k
style="width: 640px; height: 127px" alt="Image 4" data-src="/KB/threads/1245057/874569e9-94c8-47c9-94bd-ab924fb03bb6.Png" class="lazyload" data-sizes="auto" data->
Notice how we attained the structure of the synchronous code, which is awesome. Even though we are calling await operator and essentially running asynchronous task, our code looks pretty neat and simple. This is one of the reasons why async/await mechanism gained a lot of popularity.
So, what happens if GetStringAsync method takes too long to answer? Here is how the workflow goes:
GetStringAsync
style="width: 640px; height: 337px" alt="Image 5" data-src="/KB/threads/1245057/092ada02-12c2-4647-b90f-0b26c4fd3dc1.Png" class="lazyload" data-sizes="auto" data->
In the first step (marked with 1), AccessRubiksCodeAsync method creates an instance of the HttpClient and calls GetStringAsync method of this class. The goal is to download the content of the website in a form of a string. If something unexpected happens that blocks GetStringAsync method, e.g., the website is taking too long to download, this method yields control to its caller. That is how it avoids blocking resources. Apart from that, this method returns Task, which AccessRubiksCodeAsync assigns to the variable getContent. Later in the code, this variable is used in combination with await operator.
HttpClient
string
getContent
Now, since we haven’t used await operator on getContent yet, AccessRubik<wbr />sCodeAsync can continue with other operations that are not depending on the result of getContent task. So, the LogToConsole method can be run in a synchronous manner (step 2). This means that this method will take control, do its job and only then give control back to AccessRubiksCodeAsync method.
AccessRubik<wbr />sCodeAsync
After that, this method is calling getContent with await operator (step 3). This means that at this moment, this method requires the result from GetStringAsync method. If this GetStringAsync is still not ready, AccessRubiksCodeAsync is suspending its progress and returns control to its caller. Of course, bit benefit of having this kind flow is that we “gave some time” to GetStringAsync method, and meanwhile, we have run synchronous parts of the code. When content is downloaded, its length is returned as a result (step 4).
style="width: 640px; height: 427px" alt="Image 6" data-src="/KB/threads/1245057/dc9400c0-bcc1-4149-a0ef-e7bbbdd844bf.Png" data-sizes="auto" data->
Unit testing is actually one great example of how async methods are initiated. In this example, I’ve used xUnit, but async/await mechanism is supported in other unit testing frameworks like NUnit and MSTests. If you want to install xUnit to your project, enter these commands in Package Manager Console:
Install-Package xunit
Install-Package xunit.runner.console
Install-Package xunit.runner.visualstudio
Update-Package
Ok, this should get you up to speed with xUnit. Now let’s take a look at our test class for WebAccess class – WebAcces<wbr />sTests.
WebAccess
WebAcces<wbr />sTests
public class WebAccessTests
{
[Fact]
public async Task AccessRubiksCode_NoCondition_ExpectedResult()
{
var webAccess = new WebAccess();
var result = await webAccess.AccessRubiksCodeAsync();
Assert.NotEqual(0, result);
}
}
public async Task
public void
What will happen if we do this – call the async method without await operator? Well, in that case, this async method will be fired separately, and in the meantime, the calling method will continue executing. Since we didn’t await it, you’ll never know whether and when it has completed. This can be used as an advantage in certain situations of course, but it is important to know how this mechanism is working.
Apart from that, there are no crucial changes into test structure. We are first creating an instance of WebAccess class in “arrange” phase. In “act” phase, we are using await operator to initiate AccessRubiksCodeAsync method and retrieve the result. Finally, in “assert” phase, we are checking the validity of the result.
assert
Asynchronous programming is a somewhat standard functionality of .NET for a number of years. Still, sometimes I get the notion that less experienced programmers don’t quite get the point of it. Especially the ones that don’t have experience with some other technologies where this mechanism is directly used in the technology itself, like Node.js. Or they are familiar with it and try to use it in every situation.
In this article, I tried to explain how asynchronous programming is done in the .NET world from the high-level. In next few articles, we will go deeper into the subject and cover some other aspects of this style, as well.
Thank you for reading!
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
It seems to me that the three cardinal rules of unit testing are
Is your statement that, 'This Task is later run by the await operator' correct? It seems to me that the await operator asynchronously waits for the Task's state to change to some sort of completed state, typically, RanToCompletion, Canceled or Faulted. It doesn't actually run a Task, in effect, it simply monitors the Task's state. An asynchronous method that returns a Task does so as soon as the method is called, so any 'running' has already taken place before the Task is instantiated.
Task's
Is your statement that, 'Async methods must return Task class or Task class' correct? It seems to me that it is possible to use await inside event handlers with a void return type.
void
private async void Button_Click(object sender, RoutedEventArgs e)
{
await Task.Delay(300);
}
Is your statement that 'We use the async operator to mark our methods as asynchronous' correct? My understanding is that async is a compiler instruction to allow the method to use the await keyword. It does not mean that the method itself runs asynchronously. It seems to me that the only method that runs asynchronously, in your example, is the call to GetStringAsync.
According to Sephen Toub, one of the chief architects of the Task-based Asynchronous pattern. "Marking a method as async does not affect whether the method runs to completion synchronously or asynchronously. Rather, it enables the method to be split into multiple pieces, some of which may run asynchronously, such that the method may complete asynchronously."
It seems to me that an async method only runs asynchronously if it encounters a method that specifically runs code on something other than the UI thread. And it only does that if the returned Task has not already completed. If you have 3 async methods as shown below and you await MyAsync1. The application thread will run through all the awaits until it gets to TaskDelay(300). That call will run asynchronously. When it completes, the UI thread will run the continuations of MyAsync3, MyAsync2 and MyAsync1 in that order.
await MyAsync1
awaits
TaskDelay(300)
MyAsync3, MyAsync2 and MyAsync1
public async Task MyAsync1()
{
await MyAsync2();
}
public async Task MyAsync2()
{
await MyAsync3();
}
public async Task MyAsync3()
{
await TaskDelay(3000);
}
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
https://www.codeproject.com/Articles/1245057/Asynchronous-Programming-in-NET-Motivation-and-Uni?fid=1936683&df=90&mpp=25&sort=Position&view=Normal&spc=Relaxed&prof=True&select=5522001&fr=1
|
CC-MAIN-2020-34
|
refinedweb
| 1,992
| 64.3
|
#include <QTextOption>
This class was introduced in Qt 4.4.
Each tab definition is represented by this struct.
Creates a default left tab with position 80.
Returns true if tab other is not equal to this tab; otherwise returns false.
Returns true if tab other is equal to this tab; otherwise returns false.
If type is DelimitorTab; tab until this char is found in the text.
Distance from the start of the paragraph. The position of a tab is from the start of the paragraph which implies that when the alignment of the paragraph is set to centered, the tab is interpreted to be moved the same distance as the left ege of the paragraph does. In case the paragraph is set to have a layoutDirection() RightToLeft the position is interpreted to be from the right side of the paragraph with higher numbers moving the tab to the left.
Determine which type is used. In a paragraph that has layoutDirection() RightToLeft the type LeftTab will be interpreted to be a RightTab and vice versa.
|
http://doc.trolltech.com/4.5-snapshot/qtextoption-tab.html#operator-not-eq
|
crawl-003
|
refinedweb
| 174
| 72.46
|
Introduction
In this article we will learn how to set up SQLite in Xamarin.Forms. It doesn’t require too much time and it is not difficult like setting up other databases.
Target Audience
People with basic knowledge of C# and XAML are the targeted audience of this article.
Tools
You can use both Xamarin Studio and Visual Studio for Xamarin development.
Definition
SQLite is light-weight, zero configuration and transaction database which is already available in all three mobile app platforms we are targeting. This includes Android, iOS, and Windows.
Setup
Three steps are needed to completely make things ready for development.
Add sqlite-net-pcl Library
You can find this library in NuGet Packages. Just add it in your solution by following the following simple steps.
Firstly, create a Xamarin.Forms PCL application.
Right click on Solution -> Manage NuGet Package for Solution.
Select "Browse" and search for sqlite-net-pcl and install it in all projects.
Now, move towards the second step, i.e., to make an interface in PCL.
Declare interface in PCL
To declare an interface in PCL, first make a folder named persistence, then add a class in it, so you will not be confused with other classes.
Here, you can see that I made a folder of name persistence and added a new item in it.
After this, select interface and rename it.
Add the following code in interface.
Now, implement this interface in other projects.
Implement interface in all projects
Make a folder of persistence in all projects and implement this interface just like this. Make a new class of SQLiteDb in each project and implement this interface on it.
For Android
Change namespace according to your project name. In my case, the project name is XamarinApp1
For iOS
For Android and iOS, the code is same.
For Windows
For Windows, there is a change in path of db.
Now, the interface is implemented and it will return the path of DB of each project.
And you are ready to use SQLite. In my next article, I will show you CRUD operations and data persistence using SQLite.
View All
|
https://www.c-sharpcorner.com/article/setting-up-sqlite-in-xamarin-forms/
|
CC-MAIN-2018-13
|
refinedweb
| 356
| 67.35
|
Java Web Application Development With Click Framework/Quick Start
This section discusses how to get a Click web application up quickly. This section will not discuss how to configure your build system or IDE, but will focus on all the basic pieces you need to get a Click application running.
The following topics are covered:
Web Application Structure[edit]
First up add a click.xml and web.xml configuration file to your applications WEB-INF directory:
click.xml[edit]
Your click.xml file should contain:
<?xml version="1.0" encoding="UTF-8"?> <click-app> <pages package="com.quickstart.page"/> </click-app>
web.xml[edit]
Your web.xml file should contain:
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>click-servlet</servlet-name> <servlet-class>net.sf.click.ClickServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>click-servlet</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>redirect.html</welcome-file> </welcome-file-list> </web-app>
JAR Files[edit]
Add the following JAR files to your application WEB-INF/lib:
- click-1.x.jar
- click-extras-1.x.jar
You can obtain these files from the Click distribution dist directory.
Welcome File[edit]
To ensure default application requests (e.g.) are sent to your applications home page we will add a redirect.html file to the web root directory. This file should contain:
<html> <head><meta http-</head> </html>
This redirect.html file is configured in our web.xml, and any default requests will be served this file:
When the browser processes the redirect.html it will redirect to the applications home.htm page.
Home Page[edit]
Now we are ready to add our first Click page which will be our applications home page.
First we define a HomePage class, and ensure the class file is published to our web applications WEB-INF/classes directory:
package com.quickstart.page; import net.sf.click.Page; public class HomePage extends Page { }
Next we add a corresponding Home page home.htm in the web root directory:
<html> <head> <title>Home</title> <link rel="stylesheet" type="text/css" href="style.css" title="Style"/> </head> <body> <div id="header"> <span id="title">Home</span> </div> <div id="container"> <b>Welcome</b> to Home page your application starting point. </div> </body> </html>
Next add a style.css file to your web root directory:
body { font-family: Arial; font-size: 11pt; margin: 0; padding: 0; } #header { background: #FDE3B5 url(/click-quickstart/assets/banner.png) top left no-repeat; border-bottom: 1px solid black; height: 51px; position: relative; width: 100%; } #title { color: white; font-size: 24px; font-weight: bolder; position: absolute; left: 15px; top: 10px; } #container { padding-top: 1em; padding-left: 1.5em; position: relative; z-index: 0; } h3.title { margin-top: 0em; margin-bottom: 1em; }
You should now have the following web files:
Now, if your web application is deployed to the context path quickstart you should now be able to make the request:
-
Your browser should be redirected to your HomePage and you should see your page rendered as:
Welcome to Home page your application starting point.
In this example the Click automatically maps the home.htm request to our HomePage class and uses this class to process the request.
Border Template[edit]
Now we want to create a page border template so application pages will have a common look and feel.
First create a border-template.htm file in the web root directory. In this file include the HTML content:
<html> <head> <title>Click Quickstart - $title</title> <link rel="stylesheet" type="text/css" href="$context/assets/style.css" title="Style"/> </head> <body> <div id="header"> <span class="title">Quick Start :: $title</span> </div> <div id="container"> #parse($path) </div> </body> </html>
Now we define a BorderPage class which specifies its template as the new border-template.htm file:
package com.quickstart.page; import net.sf.click.Page; public class BorderPage extends Page { public String getTemplate() { return "border-template.htm"; } }
Note we named the template file border-template.htm so that it is not automatically mapped by Click to our BorderPage class.
Now we are going to modify our HomePage class to extend BorderPage and define a title value.
package com.quickstart.page; public class HomePage extends BorderPage { public String title = "Home"; }
Next we modify our home.htm to remove the page border and only include the specific Home page content.
<b>Welcome</b> to Home page your application starting point.
You should now have the following web files:
Now if you make browser request to your updated home page you should see identical HTML content being rendered.
Welcome to Home page your application starting point.
Logging[edit]
Click has some handy logging features which will show you how your page templates are being automatically mapped to you page classes. To enable debug logging add a mode value of "debug" to your click.xml file:
<?xml version="1.0" encoding="UTF-8"?> <click-app> <pages package="com.quickstart.page"/> <mode value="debug"/> </click-app>
When the Click application starts up it will write out the following logging messages:
[Click] [debug] automapped pages: [Click] [debug] /border-template.htm -> CLASS NOT FOUND [Click] [debug] /home.htm -> com.quickstart.page.HomePage [Click] [info ] initialized in debug mode
Click is telling us here that the border-template.htm template is not mapped to any Page class, while the home.htm template is mapped to our HomePage class. We are also informed that Click is running in debug mode.
When making a request to our home page we may get the following output:
[Click] [debug] GET [Click] [info ] renderTemplate: /home.htm,border-template.htm - 46 ms [Click] [info ] handleRequest: /home.htm - 62 ms
This is telling us the HTTP request that the ClickServlet received. Then we can see that it is rendering the page path home.htm and template border-template.htm files in 46 milliseconds. Finally we can see that the total time to handle this request was 62 milliseconds
If you need more detailed debugging information change the application mode to trace. Now if we make the browser request:
-
We will see the request parameters logged. This can be very handy for debugging form posts.
[Click] [debug] GET [Click] [trace] request param: password=secret [Click] [trace] request param: user=malcolm [Click] [trace] invoked: HomePage.<<init>> [Click] [trace] invoked: HomePage.onSecurityCheck() : true [Click] [trace] invoked: HomePage.onInit() [Click] [trace] invoked: HomePage.onGet() [Click] [trace] invoked: HomePage.onRender() [Click] [info ] renderTemplate: /user/home.htm,border-template.htm - 6 ms [Click] [trace] invoked: HomePage.onDestroy() [Click] [info ] handleRequest: /home.htm - 24 ms
What's Next[edit]
After you have the Quick Start application up and running you might be wondering, where do I go from here? There are lot of good code examples and patterns you can lift into your application:
- Add a Menu control to your border-template.htm to provide application wide navigation.
- Integrate J2EE Security into your application.
Use the Menu $menu.isUserInRoles() method in your menu rendering macro to only display a user's authorized menu options.
|
http://en.wikibooks.org/wiki/Java_Web_Application_Development_With_Click_Framework/Quick_Start
|
CC-MAIN-2014-52
|
refinedweb
| 1,184
| 51.24
|
The QWidget class is the base class of all user interface objects. More...
#include <qwidget.h>
Inherits QObject and QPaintDevice.
Inherited by QDialog, QFrame, QMainWindow, QComboBox, QLineEdit, QButton, ControlWidgetBase, QSlider, QToolBar, DocPropertiesWidget, QTabWidget, QTabBar, QDial, QHeader, QSemiModal, QScrollBar, QSizeGrip, and QStatusBar.
List of all member functions. (though it is also possible to create top level widgets without such decoration by the use of widget flags). In Qt, QMainWindow and the various subclasses of QDialog are the most common top-level windows.
A widget without a parent widget is always a top-level widget.
The opposite of top-level widgets are child widgets. Those are child windows in their parent widgets. You usually cannot distinguish a child widget from its parent visually. Most other widgets in Qt are useful only as child widgets. (You can make a e.g. button into a top-level widget, but most people prefer to put their buttons in e.g. dialogs.)
QWidget has many member functions, but some of them have little direct functionality - for example it has a font but never uses it itself. There are many subclasses which provide real functionality, as diverse as QPushButton, QListBox and QTabDialog.
Groups of functions:
Every widget's constructor accepts two or three standard arguments:
QWidget *parent = 0is the parent of the new widget. If it is 0 (the default), the new widget will be a top-level window. If not, it will be a child of parent, and be constrained by parent's geometry (Unless you specify WType_TopLevel as widget flag).
const char *name = 0is the widget name of the new widget. You can access it using name(). The widget name is little used by programmers but is quite useful with GUI builders such as the Qt Designer (you can name a widget in the builder, and connect() to it by name in your code). The dumpObjectTree() debugging function also uses it.
WFlags f = 0(where available) sets the widget flags; the default is good for almost all widgets, but to get e.g. top-level widgets without a window system frame you must use special flags.
The tictac/tictac.cpp example program is good example of a simple widget. It contains a few event handlers (as all widgets must), a few custom routines that are peculiar to it (as all useful widgets must), and has a few children and connections. Everything it does is done in response to an event: This is by far the most common way to design GUI applications.
You will need to supply the content for your widgets yourself, but here is a brief run-down of the events, starting with the most common ones:
If your widget only contains child widgets, you probably do not need to implement any event handlers.
Widgets that accept keyboard input need to reimplement a few more event handlers:
Some widgets will need to reimplement some more obscure event handlers, too:
There are also some really obscure events. They are listed in qevent.h and you need to reimplement event() to handle them. The default implementation of event() handles Tab and shift-Tab (to move the keyboard focus), and passes on most other events to one of the more specialized handlers above.
When writing a widget, there are a few more things to look out for.
See also QEvent, QPainter, QGridLayout, and QBoxLayout.. There are also three special values, listed at the end:
FixedColor and FixedPixmap sometimes are just the right thing, but if you use them, make sure that your application looks right when the desktop color scheme has been changed. (On X11, a quick way to test is e.g. "./yourapp -bg paleblue". On Windows, you have to use the control panel.)
See also setBackgroundMode(), backgroundMode(), setBackgroundPixmap(), and setBackgroundColor().
This enum defines the origin used to draw a widget's background pixmap.
This enum type defines the various policies a widget can have with respect to acquiring keyboard focus.
The policy can be:
This type is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.
This enum used to determine how fonts and palette changes are propagated to children of a widget.
If parent is 0, the new widget becomes a top-level window. If parent is another widget, this widget becomes a child window inside parent. The new widget is deleted when parent is.
The name is sent to the QObject constructor.
The widget flags argument f is normally 0, but it can be set to customize the window frame of a top-level widget (i.e. parent must be zero). To customize the frame, set the WStyle_Customize flag OR'ed with any of the Qt::WidgetFlags.
Note that the X11 version of Qt may not be able to deliver all combinations of style flags on all systems. This is because on X11, Qt can only ask the window manager, and the window manager can override the application's settings. On Windows, Qt can set whatever flags you want.
Example:
QLabel *spashScreen = new QLabel( 0, "mySplashScreen", WStyle_Customize | WStyle_NoBorder | WStyle_Tool );
All children of this widget are deleted first. The application exits if this widget is (was) the main widget.
See also setAcceptDrops().
Uses sizeHint() if valid (i.e if the size hint's width and height are equal to or greater than 0), otherwise sets the size to the children rectangle (the union of all child widget geometries).
See also sizeHint() and childrenRect().
Reimplemented in QMessageBox.
See also setAutoMask(), updateMask(), setMask(), and clearMask().
Returns the background color of this widget, which is normally set implicitly by setBackgroundMode(), but can also be set explicitly by setBackgroundColor().
If there is a background pixmap (set using setBackgroundPixmap()), then the return value of this function is indeterminate.
See also setBackgroundColor(), foregroundColor(), colorGroup(), and palette().
This virtual function is called from setBackgroundColor(). oldBackgroundColor is the previous background color; you can get the new background color from backgroundColor().
Reimplement this function if your widget needs to know when its background color changes. You will almost certainly need to call this implementation of the function.
See also setBackgroundColor(), backgroundColor(), setPalette(), repaint(), and update().
See also BackgroundMode and setBackgroundMode().
See also setBackgroundOrigin().
See also setBackgroundPixmap() and setBackgroundMode().
This virtual function is called from setBackgroundPixmap(). oldBackgroundPixmap is the previous background pixmap; you can get the new background pixmap from backgroundPixmap().
Reimplement this function if your widget needs to know when its background pixmap changes. You will almost certainly need to call this implementation of the function.
See also setBackgroundPixmap(), backgroundPixmap(), repaint(), and update().
The base size is used to calculate a proper widget size in case the widget defines sizeIncrement().
See also setBaseSize() and setSizeIncrement().
See also setCaption(), icon(), iconText(), and QString::isNull().
Explicitely hidden children are excluded.
See also childrenRegion().
Explicitely hidden children are excluded.
See also childrenRect().
If the widget has active focus, a focus out event is sent to this widget to tell it that it is about to lose the focus.
This widget must enable focus setting in order to get the keyboard input focus, i.e. it must call setFocusPolicy().
See also hasFocus(), setFocus(), focusInEvent(), focusOutEvent(), setFocusPolicy(), and QApplication::focusWidget().
See also setMask().
Clears the widget flags f.
Widget flags are a combination of Qt::WidgetFlags.
See also testWFlags(), getWFlags(), and setWFlags().
First it sends the widget a QCloseEvent. The widget is hidden if it accepts the close event. The default implementation of QWidget::closeEvent() accepts the close event.
The QApplication::lastWindowClosed() signal is emitted when the last visible top level widget is closed.
See also close(bool).
If alsoDelete is TRUE or the widget has the WDestructiveClose widget flag, the widget is also deleted. The widget can prevent itself from being closed by rejecting the QCloseEvent it gets.
The QApplication::lastWindowClosed() signal is emitted when the last visible top level widget is closed.
Note that closing the QApplication::mainWidget() terminates the application.
See also closeEvent(), QCloseEvent, hide(), QApplication::quit(), QApplication::setMainWidget(), and QApplication::lastWindowClosed().
The default implementation calls e->accept(), which hides this widget. See the QCloseEvent documentation for more details.
See also event(), hide(), close(), and QCloseEvent.
The color group is determined by the state of the widget.
A disabled widget returns the QPalette::disabled() color group, a widget in the window with keyboard focus returns the QPalette::active() color group, and all inactive widgets return the QPalette::inactive() color group.
See also palette() and setPalette().
Ensures that the widget is properly initialized by calling polish().
Call constPolish() from functions like sizeHint() that depends on the widget being initialized, and that may be called before show().
Warning: Do not call constPolish() on a widget from inside that widget's constructor.
See also polish().
Initializes the window (sets the geometry etc.) if initializeWindow is TRUE. If initializeWindow is FALSE, no initialization is performed. This parameter makes only sense if window is a valid window.
Destroys the old window if destroyOldWindow is TRUE. If destroyOldWindow is FALSE, you are responsible for destroying the window yourself (using platform native code).
The QWidget constructor calls create(0,TRUE,TRUE) to create a window for this widget.
See also setCursor() and unsetCursor().
See also event() and QCustomEvent.
The widget may leave Whats This mode by calling QWhatsThis::leaveWhatsThisMode(), with or without actually displaying any help text.
You may also reimplement customWhatsThis() if your widget is a so-called "passive interactor" that is supposed to work under all circumstances. Simply don't call QWhatsThis::leaveWhatsThisMode() in that case.
See also QWhatsThis::inWhatsThisMode() and QWhatsThis::leaveWhatsThisMode().
destroy() calls itself recursively for all the child widgets, passing destroySubWindows for the destroyWindow parameter. To have more control over destruction of subwidgets, destroy subwidgets selectively first.
This function is usually called from the QWidget destructor.
See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.
See also QTextDrag, QImageDrag, and QDragEnterEvent.
See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.
See also QTextDrag, QImageDrag, and QDragLeaveEvent.
See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.
See also QTextDrag, QImageDrag, and QDragMoveEvent.
The y position is the base line position of the text. The text is drawn using the default font and the default foreground color.
This function is provided for convenience. You will generally get more flexible results and often higher speed by using a a painter instead.
See also setFont(), foregroundColor(), and QPainter::drawText().
See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.
See also QTextDrag, QImageDrag, and QDropEvent.
This virtual function is called from setEnabled(). oldEnabled is the previous setting; you can get the new setting from isEnabled().
Reimplement this function if your widget needs to know when it becomes enabled or disabled. You will almost certainly need to update the widget using update().
The default implementation repaints the visible part of the widget.
See also setEnabled(), isEnabled(), repaint(), update(), and visibleRect().
An event is sent to the widget when the mouse cursor enters the widget.
See also leaveEvent(), mouseMoveEvent(), and event().
If w is negative, it is replaced with
width() - x.
If h is negative, it is replaced width
height() - y.
Child widgets are not affected.
See also repaint().
This version erases the entire widget.
Child widgets are not affected.
The main event handler first passes an event through all event filters that have been installed. If none of the filters intercept the event, it calls one of the specialized event handlers.
Key press, or FALSE if nobody wanted the event.
See also closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(), keyPressEvent(), keyReleaseEvent(), leaveEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(), mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(), QObject::event(), and QObject::timerEvent().
Reimplemented from QObject.
The window identifier type depends by the underlying window system, see qwindowdefs.h for the actual definition. If there is no widget with this identifier, a null pointer is returned.
See also wmapper() and winId().
Focus data always belongs to the top-level widget. The focus data list contains all the widgets in this top-level widget that can accept focus, in tab order. An iterator points to the current focus widget (focusWidget() returns a pointer to this widget).
This information is useful for implementing advanced versions of focusNextPrevChild().
A widget normally must setFocusPolicy() to something other than NoFocus in order to receive focus events. (Note that the application programmer can call setFocus() on any widget, even those that do not normally accept focus.)
The default implementation updates the widget if it accepts focus (see focusPolicy()). It also calls setMicroFocusHint(), hinting any system-specific input tools about the focus of the user's attention.
See also focusOutEvent(), setFocusPolicy(), keyPressEvent(), keyReleaseEvent(), event(), and QFocusEvent.
Reimplemented in QMultiLineEdit.
If next is true, this function searches "forwards", if next is FALSE, "backwards".
Sometimes, you will want to reimplement this function. For example, a web browser might reimplement it to move its "current active link" forwards or backwards, and call QWidget::focusNextPrevChild() only when it reaches the last/first.
Child widgets call focusNextPrevChild() on their parent widgets, and only the top-level widget will thus make the choice of where to redirect focus. By overriding this method for an object, you thus gain control of focus traversal for all child widgets.
See also focusData().
A widget normally must setFocusPolicy() to something other than NoFocus in order to receive focus events. (Note that the application programmer can call setFocus() on any widget, even those that do not normally accept focus.)
The default implementation calls repaint() since the widget's colorGroup() changes from active to normal, so the widget probably needs repainting. It also calls setMicroFocusHint(), hinting any system-specific input tools about the focus of the user's attention.
See also focusInEvent(), setFocusPolicy(), keyPressEvent(), keyReleaseEvent(), event(), and QFocusEvent.
Returns QWidget::TabFocus if the widget accepts focus by tabbing, QWidget::ClickFocus if the widget accepts focus by clicking, QWidget::StrongFocus if it accepts both and QWidget::NoFocus if it does not accept focus at all.
See also isFocusEnabled(), setFocusPolicy(), focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), and isEnabled().
See also setFocusProxy().
Returns the font currently set for the widget.
fontInfo() tells you what font is actually being used.
As long as no special font has been set, this is either a special font for the widget class, the parent's font or - if this widget is a toplevel widget - the default application font.
See also setFont(), fontInfo(), fontMetrics(), and QApplication::font().
This virtual function is called from setFont(). oldFont is the previous font; you can get the new font from font().
Reimplement this function if your widget needs to know when its font changes. You will almost certainly need to update the widget using update().
The default implementation updates the widget including its geometry.
See also setFont(), font(), update(), and updateGeometry().
Returns the font info for the widget's current font. Equivalent to QFontInto(widget->font()).
See also font(), fontMetrics(), and setFont().
Returns the font metrics for the widget's current font. Equivalent to QFontMetrics(widget->font()).
See also font(), fontInfo(), and setFont().
The return value is meaningless
See also setFontPropagation().
The foreground color is also accessible as colorGroup().foreground().
See also backgroundColor() and colorGroup().
See the Window Geometry documentation for an overview of geometry issues with top-level widgets.
See also geometry(), x(), y(), and pos().
See the Window Geometry documentation for an overview of geometry issues with top-level widgets.
See also frameGeometry(), size(), and rect().
Returns the widget flags for this this widget.
Widget flags are a combination of Qt::WidgetFlags.
See also testWFlags(), setWFlags(), and clearWFlags().
This widget will receive all keyboard events, independent of the active window.
Warning: Grabbing the keyboard might lock the terminal.
See also releaseKeyboard(), grabMouse(), and releaseMouse().
This widget will be the only one to receive mouse events until releaseMouse() is called.
Warning: Grabbing the mouse might lock the terminal.
It is almost never necessary to grab the mouse when using Qt since Qt grabs and releases it sensibly. In particular, Qt grabs the mouse when a button is pressed and keeps it until the last button is released.
Beware that only widgets actually shown on the screen may grab the mouse input.
See also releaseMouse(), grabKeyboard(), and releaseKeyboard().
The cursor will assume shape cursor (for as long as the mouse focus is grabbed) and this widget will be the only one to receive mouse events until releaseMouse() is called().
Warning: Grabbing the mouse might lock the terminal.
See also releaseMouse(), grabKeyboard(), releaseKeyboard(), and setCursor().
Equivalent to
qApp->focusWidget() == this.
See also setFocus(), clearFocus(), setFocusPolicy(), and QApplication::focusWidget().
Returns TRUE if mouse tracking is enabled for this widget, or FALSE if mouse tracking is disabled.
See also setMouseTracking().
See the Window Geometry documentation for an overview of geometry issues with top-level widgets.
See also geometry(), width(), and size().
Warning: Does not look at the widget's layout
Reimplemented in QTextView and QMenuBar.
You almost never have to reimplement this function. If you need to do something after a widget is hidden, use hideEvent() instead.
See also isHhideEvent(), isHidden(), show(), showMinimized(), isVisible(), and close().
Reimplemented in QMenuBar.
Hide events are sent to widgets right after they have been hidden.
See also event() and QHideEvent.
See also setIcon(), iconText(), and caption().
See also setIconText(), icon(), caption(), and QString::isNull().
When popup windows are visible, this function returns TRUE for both the active window and the popup.
See also setActiveWindow() and QApplication::activeWindow().
A desktop widget is also a top-level widget.
See also isTopLevel() and QApplication::desktop().
See also setEnabled().
This is the case if neither the widget itself nor every parent up to but excluding ancestor has been explicitly disabled.
isEnabledTo(0) is equivalent to isEnabled().
See also setEnabled() and isEnabled().
This function is deprecated. It is equivalent to isEnabled()
See also setEnabled() and isEnabled().
Returns TRUE if the widget accepts keyboard focus, or FALSE if it does not.
Keyboard focus is initially disabled (i.e. focusPolicy() == QWidget::NoFocus).
You must enable keyboard focus for a widget if it processes keyboard events. This is normally done from the widget's constructor. For instance, the QLineEdit constructor calls setFocusPolicy(QWidget::StrongFocus).
See also setFocusPolicy(), focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), and isEnabled().
Returns TRUE if the widget is explicitly hidden, or FALSE if it is visible or would become visible if all its ancestors became visible.
See also hide(), show(), isVisible(), and isVisibleTo().
Returns TRUE if this widget is a top-level widget that is maximized, or else FALSE.
Note that due to limitations in some window-systems, this does not always report expected results (eg. if the user on X11 maximizes the window via the window manager, Qt has no way of telling this from any other resize). This will improve as window manager protocols advance.
See also showMaximized().
See also showMinimized(), isVisible(), show(), hide(), and showNormal().
A modal widget is also a top-level widget.
See also isTopLevel() and QDialog.
A popup widget is created by specifying the widget flag WType_Popup to the widget constructor.
A popup widget is also a top-level widget.
See also isTopLevel().
A top-level widget is a widget which usually has a frame and a caption (title bar). Popup and desktop widgets are also top-level widgets.
A top-level widgets can have a parent widget. It will then be grouped with its parent: deleted when the parent is deleted, minimized when the parent is minimized etc. If supported by the window manager, it will also have a common taskbar entry with its parent.
QDialog and QMainWindow widgets are by default top-level, even if a parent widget is specified in the constructor. This behavior is specified by the WType_TopLevel widget flag.
Child widgets are the opposite of top-level widgets.
See also topLevelWidget(), isModal(), isPopup(), isDesktop(), and parentWidget().
See also setUpdatesEnabled().
Returns TRUE if the widget itself is visible, or else FALSE.
Calling show() sets the widget to visible status if all its parent widgets up to the toplevel widget are visible. If an ancestor is not visible, the widget won't become visible until all its ancestors are shown.
Calling hide() hides a widget explicitly. An explicitly hidden widget will never become visible, even if all its ancestors become visible.
Iconified top-level widgets also have hidden status, as well as having isMinimized() return TRUE. Windows that live on another virtual desktop (on platforms that support this concept) also have hidden status.
This function returns TRUE if the widget currently is obscured by other windows on the screen, but would be visible if moved.
A widget receives show- and hide events when its visibility status changes. Between a hide and a show event, there is no need in wasting any CPU on preparing or displaying information to the user. A video application, for example, might simply stop generating new frames.
See also show(), hide(), isHidden(), isVisibleTo(), isMinimized(), showEvent(), and hideEvent().
This is the case if neither the widget itself nor every parent up to but excluding ancestor has been explicitly hidden.
This function returns TRUE if the widget it is obscured by other windows on the screen, but would be visible if moved.
isVisibleTo(0) is very similar to isVisible(), with the exception that it does not cover the iconfied-case or the situation where the window lives on another virtual desktop.
See also show(), hide(), and isVisible().
This function is deprecated. It is equivalent to isVisible()
See also show(), hide(), and isVisible().
A widget must call setFocusPolicy() to accept focus initially and have focus in order to receive a key press event.
If you reimplement this handler, it is very important that you ignore() the event if you do not understand it, so that the widget's parent can interpret it.
The default implementation closes popup widgets if you hit escape. Otherwise the event is ignored.
See also keyReleaseEvent(), QKeyEvent::ignore(), setFocusPolicy(), focusInEvent(), focusOutEvent(), event(), and QKeyEvent.
Reimplemented in QLineEdit, QTextView, and QMultiLineEdit.
A widget must accept focus initially and have focus in order to receive a key release event.
If you reimplement this handler, it is very important that you ignore() the release if you do not understand it, so that the widget's parent can interpret it.
The default implementation ignores the event.
See also keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(), focusInEvent(), focusOutEvent(), event(), and QKeyEvent.
If no widget in this application is currently grabbing the keyboard, 0 is returned.
See also grabMouse() and mouseGrabber().
Returns a pointer to the layout engine that manages the geometry of this widget's children.
If the widget does not have a layout, layout() returns a null pointer.
See also sizePolicy().
A leave event is sent to the widget when the mouse cursor leaves the widget.
See also enterEvent(), mouseMoveEvent(), and event().
If there are siblings of this widget that overlap it on the screen, this widget will be obscured by its siblings afterwards.
See also raise() and stackUnder().
See also mapTo(), mapFromParent(), and mapFromGlobal().
See also mapToGlobal(), mapFrom(), and mapFromParent().
Same as mapFromGlobal() if the widget has no parent.
See also mapToParent(), mapFrom(), and mapFromGlobal().
See also mapFrom(), mapToParent(), and mapToGlobal().
mapToGlobal(QPoint(0,0))would give the global coordinates of the top-left pixel of the widget.
See also mapFromGlobal(), mapTo(), and mapToParent().
Same as mapToGlobal() if the widget has no parent.
See also mapFromParent(), mapTo(), and mapToGlobal().
Returns the widget's maximum height.
See also maximumSize() and maximumWidth().
The widget cannot be resized to a larger size than the maximum widget size.
See also maximumWidth(), maximumHeight(), setMaximumSize(), minimumSize(), and sizeIncrement().
Returns the widget's maximum width.
See also maximumSize() and maximumHeight().
Use the QPaintDeviceMetrics class instead.
Reimplemented from QPaintDevice.
See also setMicroFocusHint().
Returns the widget's minimum height.
See also minimumSize() and minimumWidth().
The widget cannot be resized to a smaller size than the minimum widget size.
If the returned minimum size equals (0,0) then it means that there are no constraints on the minimum size. However, Qt does nevertheless not allow you to shrink widgets to less than 1 pixel width/height.
See also maximumWidth(), maximumHeight(), setMinimumSize(), maximumSize(), and sizeIncrement().
The default implementation returns an invalid size if there is no layout for this widget, the layout's minimum size otherwise.
See also QSize::isValid(), resize(), setMinimumSize(), and sizePolicy().
Reimplemented in QLineEdit, QMultiLineEdit, and QTabWidget.
Returns the widget's minimum width.
See also minimumSize() and minimumHeight().
The default implementation generates a normal mouse press event.
Note that the widgets gets a mousePressEvent() and a mouseReleaseEvent() before the mouseDoubleClickEvent().
See also mousePressEvent(), mouseReleaseEvent(), mouseMoveEvent(), event(), and QMouseEvent.
If no widget in this application is currently grabbing the mouse, 0 is returned.
See also grabMouse() and keyboardGrabber().
If mouse tracking is switched off, mouse move events only occur if a mouse button is down while the mouse is being moved. If mouse tracking is switched on, mouse move events occur even if no mouse button is down.
QMouseEvent::pos() reports the position of the mouse cursor, relative to this widget. For press and release events, the position is usually the same as the position of the last mouse move event, but it might be different if the user moves and clicks the mouse fast. This is a feature of the underlying window system, not Qt.
See also setMouseTracking(), mousePressEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(), event(), and QMouseEvent.
Reimplemented in QSizeGrip.
If you create new widgets in the mousePressEvent() the mouseReleaseEvent() may not end up where you expect, depending on the underlying window system (or X11 window manager), the widgets' location and maybe more.
The default implementation implements the closing of popup widgets when you click outside the window. For other widget types it does nothing.
See also mouseReleaseEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), event(), and QMouseEvent.
Reimplemented in QSizeGrip.
See also mouseDoubleClickEvent(), mouseMoveEvent(), event(), and QMouseEvent.
If the widget is visible, it receives a move event immediately. If the widget is not shown yet, it is guaranteed to receive an event before it actually becomes visible.
This function is virtual, and all other overloaded move() implementations call it.
Warning: If you call move() or setGeometry() from moveEvent(), you may see infinite recursion.
See the Window Geometry documentation for an overview of geometry issues with top-level widgets.
See also pos(), resize(), setGeometry(), and moveEvent().
Reimplemented in QSemiModal.
The old position is accessible through QMoveEvent::oldPos().
See also resizeEvent(), event(), move(), and QMoveEvent.
See also setFont() and unsetFont().
See also setPalette() and unsetPalette().
When the paint event occurs, the update region QPaintEvent::region() normally has been cleared to the background color or pixmap. An exception is when repaint(FALSE) is called or the widget sets the WRepaintNoErase or WResizeNoErase flag. Inside the paint event handler, QPaintEvent::erased() carries this information.
For many widgets it is sufficient to redraw the entire widget each time, but some need to consider the update rectangle or region of the QPaintEvent to avoid slow update.
During paintEvent(), any QPainter you create on the widget will be clipped to at most the area covered by the update region.
update() and repaint() can be used to force a paint event.
See also event(), repaint(), update(), QPainter, QPixmap, and QPaintEvent.
Reimplemented in QFrame, QButton, QToolBar, QTabBar, QSizeGrip, and QStatusBar.
As long as no special palette has been set, this is either a special palette for the widget class, the parent's palette or - if this widget is a toplevel widget - the default application palette.
See also setPalette(), colorGroup(), and QApplication::palette().
This virtual function is called from setPalette(). oldPalette is the previous palette; you can get the new palette from palette().
Reimplement this function if your widget needs to know when its palette changes. You will almost certainly need to call this implementation of the function.
See also setPalette() and palette().
The return value is meaningless
This function will be called after a widget has been fully created and before it is shown the very first time.
Polishing is useful for final initialization depending on an instantiated widget. This is something a constructor cannot guarantee since the initialization of the subclasses might not be finished.
After this function, the widget has a proper font and palette and QApplication::polish() has been called.
Remember to call QWidget's implementation when reimplementing this function.
See also constPolish() and QApplication::polish().
See the Window Geometry documentation for an overview of geometry issues with top-level widgets.
See also move(), frameGeometry(), x(), and y().
If there are any siblings of this widget that overlap it on the screen, this widget will be visually in front of its siblings afterwards.
See also lower() and stackUnder().
This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.
This method is provided to aid porting to Qt 2.0. The function is renamed to reparent() in 2.0, and we hope the FAQs about it will stop.
See the Window Geometry documentation for an overview of geometry issues with top-level widgets.
See also size().
See also grabKeyboard(), grabMouse(), and releaseMouse().
See also grabMouse(), grabKeyboard(), and releaseKeyboard().
Erases the widget area (x,y,w,h) if erase is TRUE.
If w is negative, it is replaced with
width() - x.
If h is negative, it is replaced width
height() - y.().
This version erases and repaints the entire widget.
This version repaints the entire widget.
Erases the widget region reg if erase is TRUE.().
If showIt is TRUE, show() is called once the widget has been reparented.
If the new parent widget is in a different top-level widget, the reparented widget and its children are appended to the end of the TAB chain of the new parent widget, in the same internal order as before. If one of the moved widgets had keyboard focus, reparent() calls clearFocus() for that widget.
If the new parent widget is in the same top-level widget as the old parent, reparent doesn't change the TAB order or keyboard focus.
Warning: Reparenting widgets should be a real exception. In normal applications, you will almost never need it. Dynamic masks can be achieved much easier and cleaner with classes like QWidgetStack or on a higher abstraction level, QWizard.
See also getWFlags().
A convenience version of reparent that does not take widget flags as argument.
Calls reparent(parent, getWFlags()&~WType_Mask, p, showIt )
If the widget is visible, it receives a resize event immediately. If the widget is not shown yet, it is guaranteed to receive an event before it actually becomes visible.
The size is adjusted if it is outside the minimum or maximum widget size.
This function is virtual, and all other overloaded resize() implementations call it.
Warning: If you call resize() or setGeometry() from resizeEvent(), you may see infinite recursion.
See also size(), move(), setGeometry(), resizeEvent(), minimumSize(), and maximumSize().
Reimplemented in QSemiModal.
The widget will be erased and receive a paint event immediately after processing the resize event. No drawing has to (and should) be done inside this handler.
Widgets that have been created with the WResizeNoErase flag will not be erased. Nevertheless, they will receive a paint event for their entire area afterwards. Again, no drawing needs to be done inside this handler.
The default implementation calls updateMask() if the widget has automatic masking enabled.
See also moveEvent(), event(), resize(), QResizeEvent, and paintEvent().
Reimplemented in QFrame and QMainWindow.
If r is empty or invalid, the result is undefined.
After scrolling, scroll() sends a paint event for the the part of r that is read but not written. For example, when scrolling 10 pixels rightwards, the leftmost ten pixels of r need repainting. The paint event may be delivered immediately or later, depending on some heuristics.
This version of scroll() does not move the children of this widget.
See also QScrollView, erase(), and bitBlt().
This version of the function scrolls the entire widget and moves the widget's children along with the scroll.
See also bitBlt() and QScrollView.
If the widgets is the desktop, this may fail if another application is using the desktop - you can call acceptDrops() to test if this occurs.
See also acceptDrops().
An active window is a visible top-level window that has the keyboard input focus.
This function performs the same operation as clicking the mouse on the title bar of a top-level window. On X11, the result depends on the Window Manager. If you want to ensure that the window is stacked on top as well, call raise() in addition. Note that the window has be to visible, otherwise setActiveWindow() has no effect.
On Windows, if you are calling this when the application is not currently the active one then it will not make it the active window. It will flash the task bar entry blue to indicate that the window has done something. This is due to Microsoft not allowing an application to interrupt what the user is currently doing in another application.
See also isActiveWindow(), topLevelWidget(), and show().
Note: When you re-implement resizeEvent(), focusInEvent() or focusOutEvent() in your custom widgets and still want to ensure that the auto mask calculation works, you will have to add
if ( autoMask() ) updateMask();
at the end of your event handlers. Same holds for all member functions that change the appearance of the widget in a way that a recalculation of the mask is necessary.
While being a technically appealing concept, masks have one big drawback: when using complex masks that cannot be expressed easily with relatively simple regions, they tend to be very slow on some window systems. The classic example is a transparent label. The complex shape of its contents makes it necessary to represent its mask by a bitmap, which consumes both memory and time. If all you want is to blend the background of several neighboring widgets together seamlessly, you may probably want to use setBackgroundOrigin() rather than a mask.
See also autoMask(), updateMask(), setMask(), clearMask(), and setBackgroundOrigin().
Note that using this function is very often a mistake. Here are the most common mistakes:
If you want to set the background color of a widget to one of the "usual" colors, setBackgroundMode() is usually the best function. For example, man widgets that usually use white backgrounds (and black text on it) can use this:
thatWidget->setBackgroundMode( QWidget::PaletteBase );
If you want to change the color scheme of a widget, the setPalette() function is better suited. Here is how to set thatWidget to use a light green (RGB value 80, 255, 80) as background color, with shades of green used for all the 3D effects:
thatWidget->setPalette( QPalette( QColor(80, 255, 80) ) );
A fixed background color sometimes is just the right thing, but if you use it, make sure that your application looks right when the desktop color scheme has been changed. (On X11, a quick way to test is e.g. "./yourapp -bg paleblue". On Windows, you have to use the control panel.)
<
|
http://doc.trolltech.com/qtopia2.2/html/qwidget.html
|
crawl-001
|
refinedweb
| 5,813
| 59.4
|
Right now our browser can only draw colored rectangles and text—pretty boring! Real browsers support all kinds of visual effects that change how pixels and colors blend together. Let’s implement these effects using the Skia graphics library, and also see a bit of how Skia is implemented under the hood. That’ll also allow us to use surfaces for browser compositing to accelerate scrolling.
Before we get any further, we’ll need to upgrade our graphics system. While Tkinter is great for basic shapes and handling input, it lacks built-in support for many visual effects.That’s because Tk, the graphics library that Tkinter uses, dates from the early 90s, before high-performance graphics cards and GPUs became widespread. Implementing fast visual effects routines is fun, but it’s outside the scope of this book, so we need a new graphics library. Let’s use Skia, the library that Chromium uses. Unlike Tkinter, Skia doesn’t handle inputs or create graphical windows, so we’ll pair it with the SDL GUI library.
Start by installing Skia and SDL:
pip3 install skia-python pysdl2 pysdl2-dll
As elsewhere in this book, you may need to use
pip,
easy_install, or
python3 -m pip instead of
pip3 as your installer, or use your IDE’s package
installer. If you’re on Linux, you’ll need to install additional
dependencies, like OpenGL and fontconfig. Also, you may not be able to
install
pysdl2-dll; if so, you’ll need to find SDL in your
system package manager instead. Consult the
skia-python
and
pysdl2
web pages for more details.
Once installed, remove the
tkinter imports from browser
and replace them with these:
import ctypes import sdl2 import skia
If any of these imports fail, you probably need to check that Skia
and SDL were installed correctly. Note that the
ctypes
module comes standard in Python; it is used to convert between Python
and C types.
The
<canvas>
HTML element provides a JavaScript API that is similar to Skia and
Tkinter. Combined with WebGL,
it’s possible to implement basically all of SDL and Skia in JavaScript.
Alternatively, one can compile Skia to
WebAssembly
to do the same.
The main loop of the browser first needs some boilerplate to get SDL started:
if __name__ == "__main__": import sys sdl2.SDL_Init(sdl2.SDL_INIT_EVENTS)= Browser() browser 1]) browser.load(sys.argv[# ...
Next, we need to create an SDL window, instead of a Tkinter window, inside the Browser, and set up Skia to draw to it. Here’s the SDL incantation to create a window:
class Browser: def __init__(self): self.sdl_window = sdl2.SDL_CreateWindow(b"Browser", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, sdl2.SDL_WINDOW_SHOWN)
To set up Skia to draw to this window, we also need create a surface for it:In Skia and SDL, a surface is a representation of a graphics buffer into which you can draw pixels (bits representing colors). A surface may or may not be bound to the physical pixels on the screen via a window, and there can be many surfaces. A canvas is an API interface that allows you to draw into a surface with higher-level commands such as for rectangles or text. Our browser uses separate Skia and SDL surfaces for simplicity, but in a highly optimized browser, minimizing the number of surfaces is important for good performance.
class Browser: def __init__(self): self.root_surface = skia.Surface.MakeRaster( skia.ImageInfo.Make( WIDTH, HEIGHT,=skia.kRGBA_8888_ColorType, ct=skia.kUnpremul_AlphaType)) at
Typically, we’ll draw to the Skia surface, and then once we’re done with it we’ll copy it to the SDL surface to display on the screen. This will be a little hairy, because we are moving data between two low-level libraries, but really it’s just copying pixels from one place to another.
First, get the sequence of bytes representing the Skia surface:
class Browser: def draw(self): # ... # This makes an image interface to the Skia surface, but # doesn't actually copy anything yet. = self.root_surface.makeImageSnapshot() skia_image = skia_image.tobytes() skia_bytes
Next, we need to copy the data to an SDL surface. This requires
telling SDL what order the pixels are stored in (which we specified to
be
RGBA_8888 when constructing the surface) and on your
computer’s endianness:
class Browser: def __init__(self): if sdl2.SDL_BYTEORDER == sdl2.SDL_BIG_ENDIAN: self.RED_MASK = 0xff000000 self.GREEN_MASK = 0x00ff0000 self.BLUE_MASK = 0x0000ff00 self.ALPHA_MASK = 0x000000ff else: self.RED_MASK = 0x000000ff self.GREEN_MASK = 0x0000ff00 self.BLUE_MASK = 0x00ff0000 self.ALPHA_MASK = 0xff000000
The
CreateRGBSurfaceFrom method then wraps the data in
an SDL surface (this SDL surface does not copy the bytes): Note that since Skia and SDL
are C++ libraries, they are not always consistent with Python’s garbage
collection system. So the link between the output of
tobytes and
sdl_window is not guaranteed to be
kept consistent when
skia_bytes is garbage collected.
Instead, the SDL surface will be pointing at a bogus piece of memory,
which will lead to memory corruption or a crash. The code here is
correct because all of these are local variables that are
garbage-collected together, but if not you need to be careful to keep
all of them alive at the same time.
class Browser: def draw(self): # ... = 32 # Bits per pixel depth = 4 * WIDTH # Bytes per row pitch = sdl2.SDL_CreateRGBSurfaceFrom( sdl_surface skia_bytes, WIDTH, HEIGHT, depth, pitch,self.RED_MASK, self.GREEN_MASK, self.BLUE_MASK, self.ALPHA_MASK)
Finally, we draw all this pixel data on the window itself by blitting
(copying) it from
sdl_surface to
sdl_window’s
surface:
class Browser: def draw(self): # ... = sdl2.SDL_Rect(0, 0, WIDTH, HEIGHT) rect = sdl2.SDL_GetWindowSurface(self.sdl_window) window_surface # SDL_BlitSurface is what actually does the copy. sdl2.SDL_BlitSurface(sdl_surface, rect, window_surface, rect)self.sdl_window) sdl2.SDL_UpdateWindowSurface(
Next, SDL doesn’t have a
mainloop or
bind
method; we have to implement it ourselves:
if __name__ == "__main__": # ... = sdl2.SDL_Event() event while True: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: browser.handle_quit() sdl2.SDL_Quit() sys.exit()# ...
The details of
ctypes and
PollEvent aren’t
too important here, but note that
SDL_QUIT is an event,
sent when the user closes the last open window. The
handle_quit method it calls just cleans up the window
object:
class Browser: def handle_quit(self): self.sdl_window) sdl2.SDL_DestroyWindow(
We’ll also need to handle all of the other events in this loop—clicks, typing, and so on. The SDL syntax looks like this:
if __name__ == "__main__": while True: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: # ... elif event.type == sdl2.SDL_MOUSEBUTTONUP: browser.handle_click(event.button)elif event.type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_RETURN: browser.handle_enter()elif event.key.keysym.sym == sdl2.SDLK_DOWN: browser.handle_down()elif event.type == sdl2.SDL_TEXTINPUT: 'utf8')) browser.handle_key(event.text.text.decode(
I’ve changed the signatures of the various event handler methods;
you’ll need to make analogous changes in
Browser where they
are defined. This loop replaces all of the
bind calls in
the
Browser constructor, which you can now remove.
SDL is most popular for making games. Their site lists a selection of books about game programming in SDL.
Now our browser is creating an SDL window and can draw to it via Skia. But most of the browser codebase is still using Tkinter drawing commands, which we now need to replace. Skia is a bit more verbose than Tkinter, so let’s abstract over some details with helper functions.Consult the Skia and skia-python documentation for more on the Skia API. First, a helper function to convert colors to Skia colors:
def parse_color(color): if color == "white": return skia.ColorWHITE elif color == "lightblue": return skia.ColorSetARGB(0xFF, 0xAD, 0xD8, 0xE6) # ... else: return skia.ColorBLACK
You can add more “elif” blocks to support any other color names you use; modern browsers support quite a lot.
To draw a line, you use Skia’s
Path object:
def draw_line(canvas, x1, y1, x2, y2): = skia.Path().moveTo(x1, y1).lineTo(x2, y2) path = skia.Paint(Color=skia.ColorBLACK) paint paint.setStyle(skia.Paint.kStroke_Style)1) paint.setStrokeWidth( canvas.drawPath(path, paint)
To draw text, you use
drawString:
def draw_text(canvas, x, y, text, font, color=None): = parse_color(color) sk_color = skia.Paint(AntiAlias=True, Color=sk_color) paint canvas.drawString(float(x), y - font.getMetrics().fAscent, text, font, paint)
Finally, for drawing rectangles you use
drawRect:
def draw_rect(canvas, l, t, r, b, fill=None, width=1): = skia.Paint() paint if fill: paint.setStrokeWidth(width) paint.setColor(parse_color(fill))else: paint.setStyle(skia.Paint.kStroke_Style)1) paint.setStrokeWidth( paint.setColor(skia.ColorBLACK)= skia.Rect.MakeLTRB(l, t, r, b) rect canvas.drawRect(rect, paint)
If you look at the details of these helper methods, you’ll see that
they all use a Skia
Paint object to describe a shape’s
borders and colors. We’ll be seeing a lot more features of
Paint in this chapter.
With these helper methods we can now upgrade our browser’s drawing commands to use Skia:
class DrawText: def execute(self, scroll, canvas): self.left, self.top - scroll, draw_text(canvas, self.text, self.font, self.color) class DrawRect: def execute(self, scroll, canvas): draw_rect(canvas,self.left, self.top - scroll, self.right, self.bottom - scroll, =self.color, width=0) fill
Let’s also add a
rect field to each drawing command,
replacing its
top,
left,
bottom,
and
right fields with a Skia
Rect object:
class DrawText: def __init__(self, x1, y1, text, font, color): # ... self.rect = \ self.right, self.bottom) skia.Rect.MakeLTRB(x1, y1, class DrawRect: def __init__(self, x1, y1, x2, y2, color): # ... self.rect = skia.Rect.MakeLTRB(x1, y1, x2, y2)
Finally, the
Browser class also uses Tkinter commands in
its
draw method to draw the browser UI. We’ll need to
change them all to use Skia. It’s a long method, so we’ll need to go
step by step.
First, clear the canvas and and draw the current
Tab
into it:
class Browser: def draw(self): = self.root_surface.getCanvas() canvas canvas.clear(skia.ColorWHITE) self.tabs[self.active_tab].draw(canvas)
Then draw the browser UI elements. First, the tabs:
class Browser: def draw(self): # ... = skia.Font(skia.Typeface('Arial'), 20) tabfont for i, tab in enumerate(self.tabs): = "Tab {}".format(i) name = 40 + 80 * i, 120 + 80 * i x1, x2 0, x1, 40) draw_line(canvas, x1, 0, x2, 40) draw_line(canvas, x2, + 10, 10, name, tabfont) draw_text(canvas, x1 if i == self.active_tab: 0, 40, x1, 40) draw_line(canvas, 40, WIDTH, 40) draw_line(canvas, x2,
Next, the plus button for adding a new tab:I also changed the y position of the plus sign. Skia draws fonts a bit differently from Tkinter, and the new y position keeps the plus centered in the box. Feel free to adjust the positions of the UI elements to make everything look good on your system.
class Browser: def draw(self): # ... = skia.Font(skia.Typeface('Arial'), 30) buttonfont 10, 10, 30, 30) draw_rect(canvas, 11, 4, "+", buttonfont) draw_text(canvas,
Then the address bar, including text and cursor:
class Browser: def draw(self): # ... 40, 50, WIDTH - 10, 90) draw_rect(canvas, if self.focus == "address bar": 55, 55, self.address_bar, buttonfont) draw_text(canvas, = buttonfont.measureText(self.address_bar) w 55 + w, 55, 55 + w, 85) draw_line(canvas, else: = self.tabs[self.active_tab].url url 55, 55, url, buttonfont) draw_text(canvas,
And finally the “back” button:
class Browser: def draw(self): # ... 10, 50, 35, 90) draw_rect(canvas, = \ path 15, 70).lineTo(30, 55).lineTo(30, 85) skia.Path().moveTo(= skia.Paint( paint =skia.ColorBLACK, Style=skia.Paint.kFill_Style) Color canvas.drawPath(path, paint)
Tab also has a
draw method, which draws a
cursor; it needs to use
draw_line for that. Also wrap it in
a display list command called
DrawLine.
class DrawLine: def __init__(self, x1, y1, x2, y2): self.rect = skia.Rect.MakeLTRB(x1, y1, x2, y2) self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def execute(self, canvas): self.x1, self.y1, self.x2, self.y2) draw_line(canvas, class Tab: def render(self): # ... if self.focus: = [obj for obj in tree_to_list(self.document, []) obj if obj.node == self.focus and \ isinstance(obj, InputLayout)][0] = self.focus.attributes.get("value", "") text = obj.x + obj.font.measureText(text) x = obj.y y self.display_list.append( + obj.height)) DrawLine(x, y, x, y
That’s most of it. The last few changes we need to upgrade from Tkinter to SDL and Skia relate to fonts and text.
Implementing high-quality raster libraries is very interesting in its own right—check out Real-Time Rendering for more.There is also Computer Graphics: Principles and Practice, which incidentally I remember buying—this is Chris speaking—back in the days of my youth (1992 or so). At the time I didn’t get much further than rastering lines and polygons (in assembly language!). These days you can do the same and more with Skia and a few lines of Python. These days, it’s especially important to leverage GPUs when they’re available, and browsers often push the envelope. Browser teams typically include or work closely with raster library experts: Skia for Chromium and Core Graphics for WebKit, for example. Both of these libraries are used outside of the browser, too: Core Graphics in iOS and macOS, and Skia in Android.
Since we’re replacing Tkinter with Skia, we are also replacing
tkinter.font. In Skia, a font object has two pieces: a
Typeface, which is a type family with a certain weight,
style, and width; and a
Font, which is a
Typeface at a particular size. It’s the
Typeface that contains data and caches, so that’s what we
need to cache:
def get_font(size, weight, style): = (weight, style) key if key not in FONTS: if weight == "bold": = skia.FontStyle.kBold_Weight skia_weight else: = skia.FontStyle.kNormal_Weight skia_weight if style == "italic": = skia.FontStyle.kItalic_Slant skia_style else: = skia.FontStyle.kUpright_Slant skia_style = skia.FontStyle.kNormal_Width skia_width = \ style_info skia.FontStyle(skia_weight, skia_width, skia_style)= skia.Typeface('Arial', style_info) font = font FONTS[key] return skia.Font(FONTS[key], size)
Our browser also needs font metrics and measurements. In Skia, these
are provided by the
measureText and
getMetrics
methods. Let’s start with
measureText—it needs to replace
all calls to
measure. For example, in the
draw
method for a
Tab, we must do:
class Tab: def draw(self, canvas): if self.focus: # ... = obj.x + obj.font.measureText(text) x # ...
There are also
measure calls in
DrawText,
in the
draw method on
Browser, in the
text method in
InlineLayout, and in the
layout method in
TextLayout. Update all of
them to use
measureText.
Also, in the
layout method of
LineLayout
and in
DrawText we make calls to the
metrics
method on fonts. In Skia, this method is called
getMetrics,
and to get the ascent and descent we use
-font.getMetrics().fAscent
and
font.getMetrics().fDescent
Note the negative sign when accessing the ascent. In Skia, ascent and
descent are positive if they go downward and negative if they go upward,
so ascents will normally be negative, the opposite of Tkinter. There’s
no analog for the
lineheight field that Tkinter provides,
but you can use descent minus ascent instead.
You should now be able to run the browser again. It should look and behave just as it did in previous chapters, and it’ll probably feel faster, because Skia and SDL are faster than Tkinter. This is one advantage of Skia: since it is also used by the Chromium browser, we know it has fast, built-in support for all of the shapes we might need.
Let’s reward ourselves for the big refactor with a simple feature
that Skia enables: rounded corners of a rectangle via the
border-radius CSS property, like this:
<div style="border-radius: 10px; background: lightblue"> This is some example text. </div>
Which looks like this:If you’re very observant, you may notice that the text here
protrudes past the background by just a handful of pixels. This is the
correct default behavior, and can be modified by the
overflow CSS property, which we’ll see later this
chapter.
This is some example text.
Implementing
border-radius requires drawing a rounded
rectangle, so let’s add a new
DrawRRect command:
class DrawRRect: def __init__(self, rect, radius, color): self.rect = rect self.rrect = skia.RRect.MakeRectXY(rect, radius, radius) self.color = color def execute(self, scroll, canvas): = parse_color(self.color) sk_color self.rrect, canvas.drawRRect(=skia.Paint(Color=sk_color)) paint
Note that Skia supports
RRects, or rounded rectangles,
natively, so we can just draw one right to a canvas. Now we can draw
these rounded rectangles for the background:
class BlockLayout: def paint(self, display_list): if bgcolor != "transparent": = float( radius self.node.style.get("border-radius", "0px")[:-2]) cmds.append(DrawRRect(rect, radius, bgcolor))
Similar changes should be made to
InputLayout and
InlineLayout.
Font rasterization is surprisingly deep, with techniques such as subpixel rendering and hinting used to make fonts look better on lower-resolution screens. These techniques are much less necessary on high-pixel-density screens, though. It’s likely that eventually, all screens will be high-density enough to retire these techniques.
Skia, like the Tkinter canvas we’ve been using until now, is a rasterization library: it converts shapes like rectangles and text into pixels. Before we move on to Skia’s advanced features, let’s talk about how rasterization works at a deeper level. This will help to understand how exactly those features work.
You probably already know that computer screens are a 2D array of pixels. Each pixel contains red, green and blue lights,Actually, some screens contain pixels besides red, green, and blue, including white, cyan, or yellow. Moreover, different screens can use slightly different reds, greens, or blues; professional color designers typically have to calibrate their screen to display colors accurately. For the rest of us, the software still communicates with the display in terms of standard red, green, and blue colors, and the display hardware converts to whatever pixels it uses. or color channels, that can shine with an intensity between 0 (off) and 1 (fully on). By mixing red, green, and blue, which is formally known as the sRGB color space, any color in that space’s gamut can be made.The sRGB color space dates back to CRT displays. New technologies like LCD, LED, and OLED can display more colors, so CSS now includes syntax for expressing these new colors. All color spaces have a limited gamut of expressible colors. In a rasterization library, a 2D array of pixels like this is called a surface.Sometimes they are called bitmaps or textures as well, but these words connote specific CPU or GPU technologies for implementing surfaces. Since modern devices have lots of pixels, surfaces require a lot of memory, and we’ll typically want to create as few as possible.
The job of a rasterization library is to determine the red, green, and blue intensity of each pixel on the screen, based on the shapes—lines, rectangles, text—that the application wants to display. The interface for drawing shapes onto a surface is called a canvas; both Tkinter and Skia had canvas APIs. In Skia, each surface has an associated canvas that draws to that surface.
Screens use red, green, and blue color channels to match the three types of cone cells in a human eye. We take it for granted, but color standards like CIELAB derive from attempts to reverse-engineer human vision. These cone cells vary between people: some have more or fewer (typically an inherited condition carried on the X chromosome). Moreover, different people have different ratios of cone types and those cone types use different protein structures that vary in the exact frequency of green, red, and blue that they respond to. The study of color thus combines software, hardware, chemistry, biology, and psychology.
Drawing shapes quickly is already a challenge, but with multiple shapes there’s an additional question: what color should the pixel be when two shapes overlap? So far, our browser has only handled opaque shapes,It also hasn’t considered subpixel geometry or anti-aliasing, which also rely on color mixing. and the answer has been simple: take the color of the top shape. But now we need more nuance.
Many objects in nature are partially transparent: frosted glass, clouds, or colored paper, for example. Looking through one, you see multiple colors blended together. That’s also why computer screens work: the red, green, and blue lights blend together and appear to our eyes as another color. Designers use this effectMostly. Some more advanced blending modes on the web are difficult, or perhaps impossible, in real-world physics. in overlays, shadows, and tooltips, so our browser needs to support color mixing.
Color mixing means we need to think carefully about the order of operations. For example, consider black text on an orange background, placed semi-transparently over a white background. The text is gray while the background is yellow-orange. That’s due to blending: the text and the background are both partially transparent and let through some of the underlying white:
But importantly, the text isn’t orange-gray: even though the text is partially transparent, none of the orange shines through. That’s because the order matters: the text is first blended with the background; since the text is opaque, its blended pixels are black and overwrite the orange background. Only then is this black-and-orange image blended with the white background. Doing the operations in a different order would lead to dark-orange or black text.
To handle this properly, browsers apply blending not to individual shapes but to a tree of stacking contexts. Conceptually, each stacking context is drawn onto its own surface, and then blended into its parent stacking context. Rastering a web page requires a bottom-up traversal of the tree of stacking contexts: to raster a stacking context you first need to raster its contents, including its child stacking contexts, and then the whole contents need to be blended together into the parent.
To match this use pattern, in Skia, surfaces form a stack. You can push a new surface on the stack, raster things to it, and then pop it off by blending it with surface below. When traversing the tree of stacking contexts, you push a new surface onto the stack every time you recurse into a new stacking context, and pop-and-blend every time you return from a child stacking context to its parent.
In real browsers, stacking contexts are formed by HTML elements with certain styles, up to any descendants that themselves have such styles. The full definition is actually quite complicated, so in this chapter we’ll simplify by treating every layout object as a stacking context.
Mostly, elements form
a stacking context because of CSS properties that have something to
do with layering (like
z-index) or visual effects (like
mix-blend-mode). On the other hand, the
overflow property, which can make an element scrollable,
does not induce a stacking context, which I think was a mistake.While we’re at it, perhaps
scrollable elements should also be a containing
block for descendants. Otherwise, a scrollable element can have
non-scrolling children via properties like
position. This
situation is very complicated to handle in real browsers.
The reason is that inside a modern browser, scrolling is done on the GPU
by offsetting two surfaces. Without a stacking context the browser might
(depending on the web page structure) have to move around multiple
independent surfaces with complex paint orders, in lockstep, to achieve
scrolling. Fixed- and sticky-positioned elements also form stacking
contexts because of their interaction with scrolling.
Color mixing happens when multiple page elements overlap. The easiest
way that happens in our browser is child elements overlapping their
parents, like this:There
are many more ways elements can overlap in a real browser: the
transform property,
positioned elements,
negative margins, and so many more. But color mixing works the same way
each time.
<div style="background-color:orange"> Parent <div style="background-color:white;border-radius:5px">Child</div> Parent </div>
It looks like this:
Parent
Right now, the white rectangle completely obscures part of the orange
one; the two colors don’t really need to “mix”, and in fact it kind of
looks like two orange rectangles instead of an orange rectangle with a
white one on top. Now let’s make the white child element
semi-transparent, so the colors have to mix. In CSS, that requires
adding an
opacity property with a value somewhere between 0
(completely transparent) and 1 (totally opaque). With 50% opacity on the
white child element, it looks like this:
Parent
Notice that instead of being pure white, the child element now has a light-orange background color, resulting from orange and white mixing. Let’s implement this in our browser.
The way to mix colors in Skia is to first create two surfaces, and
then draw one into the other. The most convenient way to do that is with
saveLayerIt’s called
saveLayer instead of
createSurface because Skia doesn’t actually promise to
create a new surface, if it can optimize that away. So what you’re
really doing with
saveLayer is telling Skia that there is a
new conceptual layer (“piece of paper”) on the stack. Skia’s terminology
distinguishes between a layer and a surface for this reason as well, but
for our purposes it makes sense to assume that each new layer comes with
a surface. and
restore:
# draw parent =skia.Paint(Alphaf=0.5)) canvas.saveLayer(paint# draw child canvas.restore()
We first draw the parent, then create a new surface with
saveLayer to draw the child into, and then when the
restore call is made the
paint parameters
passed into
saveLayer are used to mix the colors in the two
surfaces together. Here we’re using the
Alphaf parameter,
which describes the opacity as a floating-point number from 0 to 1.
Note that
saveLayer and
restore are like a
pair of parentheses enclosing the child drawing operations. This means
our display list is no longer just a linear sequence of drawing
operations, but a tree. So in our display list, let’s represent
saveLayer with a
SaveLayer command that takes
a sequence of other drawing commands as an argument:
class SaveLayer: def __init__(self, sk_paint, children): self.sk_paint = sk_paint self.children = children self.rect = skia.Rect.MakeEmpty() for cmd in self.children: self.rect.join(cmd.rect) def execute(self, scroll, canvas): =self.sk_paint) canvas.saveLayer(paintfor cmd in self.children: cmd.execute(scroll, canvas) canvas.restore()
Now let’s look at how we can add this to our existing
paint method for
BlockLayouts. Right now, this
method draws a background and then recurses into its children, adding
each drawing command straight to the global display list. Let’s instead
add those drawing commands to a temporary list first:
class BlockLayout: def paint(self, display_list): = [] cmds # ... if bgcolor != "transparent": # ... cmds.append(DrawRRect(rect, radius, bgcolor)) for child in self.children: child.paint(cmds)# ... display_list.extend(cmds)
Now, before we add our temporary command list to the overall
display list, we can use
SaveLayer to add transparency to
the whole element. I’m going to do this in a new
paint_visual_effects method, because we’ll want to make the
same changes to all of our other layout objects:
class BlockLayout: def paint(self, display_list): # ... = paint_visual_effects(self.node, cmds, rect) cmds display_list.extend(cmds)
Inside
paint_visual_effects, we’ll parse the opacity
value and construct the appropriate
SaveLayer:
def paint_visual_effects(node, cmds, rect): = float(node.style.get("opacity", "1.0")) opacity return [ =opacity), cmds) SaveLayer(skia.Paint(Alphaf ]
Note that
paint_visual_effects receives a list of
commands and returns another list of commands. It’s just that the output
list is always a single
SaveLayer command that wraps the
original content—which makes sense, because first we need to draw the
commands to a surface, and then apply transparency to it when
blending into the parent.
This blog post gives a really nice visual overview of many of the same concepts explored in this chapter, plus way more content about how a library such as Skia might implement features like raster sampling of vector graphics for lines and text, and interpolation of surfaces when their pixel arrays don’t match resolution or orientation. I highly recommend it.
Now let’s pause and explore how opacity actually works under the hood. Skia, SDL, and many other color libraries account for opacity with a fourth alpha value for each pixel.The difference between opacity and alpha can be confusing. Think of opacity as a visual effect applied to content, but alpha as a part of content. Think of alpha as implementation technique for representing opacity. An alpha of 0 means the pixel is fully transparent (meaning, no matter what the colors are, you can’t see them anyway), and an alpha of 1 means a fully opaque.
When a pixel with alpha overlaps another pixel, the final color is a
mix of their two colors. How exactly the colors are mixed is defined by
Skia’s
Paint objects. Of course, Skia is pretty complex,
but we can sketch these paint operations in Python as methods on an
imaginary
Pixel class.
class Pixel: def __init__(self, r, g, b, a): self.r = r self.g = g self.b = b self.a = a
When we apply a
Paint with an
Alphaf
parameter, the first thing Skia does is add the requested opacity to
each pixel:
class Pixel: def alphaf(self, opacity): self.a = self.a * opacity
I want to emphasize that this code is not a part of our browser—I’m simply using Python code to illustrate what Skia is doing internally.
That
Alphaf operation applies to pixels in one surface.
But with
SaveLayer we will end up with two surfaces, with
all of their pixels aligned, and therefore we will need to combine, or
blend, corresponding pairs of pixels.
Here the terminology can get confusing: we imagine that the pixels “on top” are blending into the pixels “below”, so we call the top surface the source surface, with source pixels, and the bottom surface the destination surface, with destination pixels. When we combine them, there are lots of ways we could do it, but the default on the web is called “simple alpha compositing” or source-over compositing. In Python, the code to implement it looks like this:The formula for this code can be found here. Note that that page refers to premultiplied alpha colors, but Skia’s API does not use premultiplied representations, and the code below doesn’t either.
class Pixel: def source_over(self, source): self.a = 1 - (1 - source.a) * (1 - self.a) if self.a == 0: return self self.r = \ self.r * (1 - source.a) * self.a + \ (* source.a) / self.a source.r self.g = \ self.g * (1 - source.a) * self.a + \ (* source.a) / self.a source.g self.b = \ self.b * (1 - source.a) * self.a + \ (* source.a) / self.a source.b
Here the destination pixel
self is modified to blend in
the source pixel
source. The mathematical expressions for
the red, green, and blue color channels are identical, and basically
average the source and destination colors, weighted by alpha.For example, if the alpha of
the source pixel is 1, the result is just the source pixel color, and if
it is 0 the result is the backdrop pixel color. You might
imagine the overall operation of
SaveLayer with an
Alphaf parameter as something like this:In reality, reading individual
pixels into memory to manipulate them like this is slow. So libraries
such as Skia don’t make it convenient to do so. (Skia canvases do have
peekPixels and
readPixels methods that are
sometimes used, but not for this.)
for (x, y) in destination.coordinates(): source[x, y].alphaf(opacity) destination[x, y].source_over(source[x, y])
Source-over compositing is one way to combine two pixel values. But it’s not the only method—you could write literally any computation that combines two pixel values if you wanted. Two computations that produce interesting effects are traditionally called “multiply” and “difference” and use simple mathematical operations. “Multiply” multiplies the color values:
class Pixel: def multiply(self, source): self.r = self.r * source.r self.g = self.g * source.g self.b = self.b * source.b
And “difference” computes their absolute differences:
class Pixel: def difference(self, source): self.r = abs(self.r - source.r) self.g = abs(self.g - source.g) self.b = abs(self.b - source.b)
CSS supports these and many other blending modesMany of these blending modes
are common to
other graphics editing programs like Photoshop and GIMP. Some, like “dodge” and
“burn”, go back to analog photography, where photographers would
expose some parts of the image more than others to manipulate their
brightness. via the
mix-blend-mode
property, like this:
<div style="background-color:orange"> Parent <div style="background-color:blue;mix-blend-mode:difference"> Child </div> Parent </div>
This HTML will look like:
Parent
Here, when blue overlaps with orange, we see pink: blue has (red,
green, blue) color channels of
(0, 0, 1), and orange has
(1, .65, 0), so with “difference” blending the resulting
pixel will be
(1, 0.65, 1), which is pink. On a pixel
level, what’s happening is something like this:
for (x, y) in destination.coordinates(): source[x, y].alphaf(opacity) source[x, y].difference(destination[x, y]) destination[x, y].source_over(source[x, y])
This looks weird, but conceptually it blends the destination into the source (which ignores alpha) and then draws the source over the destination (with alpha considered). In some sense, blending thus happens twice.
Skia supports the multiply and difference blend modes natively:
def parse_blend_mode(blend_mode_str): if blend_mode_str == "multiply": return skia.BlendMode.kMultiply elif blend_mode_str == "difference": return skia.BlendMode.kDifference else: return skia.BlendMode.kSrcOver
This makes adding support for blend modes to our browser as simple as
passing the
BlendMode parameter to the
Paint
object:
def paint_visual_effects(node, cmds, rect): # ... = parse_blend_mode(node.style.get("mix-blend-mode")) blend_mode return [ =blend_mode), [ SaveLayer(skia.Paint(BlendMode=opacity), cmds), SaveLayer(skia.Paint(Alphaf ]), ]
Note the order of operations here: we first apply
transparency, and then blend the result into the rest of the
page. If we switched the two
SaveLayer calls, so that we
first applied blending, there wouldn’t be anything to blend it into!
Alpha might seem intuitive, but it’s less obvious than you think:
see, for example, this history of
alpha written by its co-inventor (and co-founder of Pixar). And
there are several different implementation options. For example, many
graphics libraries, Skia included, multiply the color channels by the
opacity instead of allocating a whole color channel. This premultiplied
representation is generally more efficient; for example,
source_over above had to divide by
self.a at
the end, because otherwise the result would be premultiplied. Using a
premultiplied representation throughout would save a division. Nor is it
obvious how alpha behaves when
resized.
The “multiply” and “difference” blend modes can seem kind of obscure, but blend modes are a flexible way to implement per-pixel operations. One common use case is clipping—intersecting a surface with a given shape. It’s called clipping because it’s like putting a second piece of paper (called a mask) over the first one, and then using scissors to cut along the mask’s edge.
There are all sorts of powerful methodsThe CSS
clip-path
property lets specify a mask shape using a curve, while the
mask
property lets you instead specify a image URL for the
mask. for clipping content on the web, but the most common
form involves the
overflow property. This property has lots
of possible values,For
example,
overflow: scroll adds scroll bars and makes an
element scrollable, while
overflow: hidden is similar to
but subtly different from
overflow: clip. but
let’s focus here on
overflow: clip, which cuts off contents
of an element that are outside the element’s bounds.
Usually,
overflow: clip is used with properties like
height or
rotate which can make an element’s
children poke outside their parent. Our browser doesn’t support these,
but there is one edge case where
overflow: clip is
relevant: rounded corners. Consider this example:
<div style="border-radius:30px;background-color:lightblue;overflow:clip"> This test text exists here to ensure that the "div" element is large enough that the border radius is obvious. </div>
That HTML looks like this:
This test text exists here to ensure that the “div” element is large enough that the border radius is obvious.
Observe that the letters near the corner are cut off to maintain a
sharp rounded edge. (Uhh… actually, at the time of this writing, Safari
does not support
overflow: clip, so if you’re using Safari
you won’t see this effect.The similar
overflow: hidden is supported by
all browsers. However, in this case,
overflow: hidden will
also increase the height of
div until the rounded corners
no longer clip out the text. This is because
overflow:hidden has different rules for sizing boxes,
having to do with the possibility of the child content being
scrolled—
hidden means “clipped, but might be scrolled by
JavaScript”. If the blue box had not been taller, than it would have
been impossible to see the text, which is really bad if it’s intended
that there should be a way to scroll it on-screen.) That’s
clipping; without the
overflow: clip property these letters
would instead be fully drawn, like we saw earlier in this chapter.
Counterintuitively, we’ll implement clipping using blending modes. We’ll make a new surface (the mask), draw a rounded rectangle into it, and then blend it with the element contents. But we want to see the element contents, not the mask, so when we do this blending we will use destination-in compositing.
Destination-in compositing basically means keeping the pixels of the destination surface that intersect with the source surface. The source surface’s color is not used—just its alpha. In our case, the source surface is the rounded rectangle mask and the destination surface is the content we want to clip, so destination-in fits perfectly. In code, destination-in looks like this:
class Pixel: def destination_in(self, source): self.a = self.a * source.a if self.a == 0: return self self.r = (self.r * self.a * source.a) / self.a self.g = (self.g * self.a * source.a) / self.a self.b = (self.b * self.a * source.a) / self.a
Now, in
paint_visual_effects, we need to create a new
layer, draw the mask image into it, and then blend it with the element
contents with destination-in blending:
def paint_visual_effects(node, cmds, rect): # ... = float(node.style.get("border-radius", "0px")[:-2]) border_radius if node.style.get("overflow", "visible") == "clip": = border_radius clip_radius else: = 0 clip_radius return [ =blend_mode), [ SaveLayer(skia.Paint(BlendMode=opacity), cmds), SaveLayer(skia.Paint(Alphaf=skia.kDstIn), [ SaveLayer(skia.Paint(BlendMode"white") DrawRRect(rect, clip_radius, ]), ]), ]
After drawing all of the element contents with
cmds (and
applying opacity), this code draws a rounded rectangle on another layer
to serve as the mask, and uses destination-in blending to clip the
element contents. Here I chose to draw the rounded rectangle in white,
but the color doesn’t matter as long as it’s opaque. On the other hand,
if there’s no clipping, I don’t round the corners of the mask, which
means nothing is clipped out.
Notice how similar this masking technique is to the physical analogy with scissors described earlier, with the two layers playing the role of two sheets of paper and destination-in compositing playing the role of the scissors. This implementation technique for clipping is called masking, and it is very general—you can use it with arbitrarily complex mask shapes, like text, bitmap images, or anything else you can imagine.
Rounded corners have an interesting
history in computing. Features that are simple today were very
complex to implement on early personal computers with limited memory
and no hardware floating-point arithmetic. Even when floating-point
hardware and eventually GPUs became standard, the
border-radius CSS property didn’t appear in browsers until
around 2010.The lack of
support didn’t stop web developers from putting rounded corners on their
sites before
border-radius was supported. There are a
number of clever ways to do it; this
video walks through several. More recently, the
introduction of animations, visual effects, multi-process compositing,
and hardware
overlays have again rounded corners pretty complex. The
clipRRect fast path, for example, can fail to apply for
cases such as hardware video overlays and nested rounded corner
clips.
Our browser now works correctly, but uses way too many surfaces. For example, for a single, no-effects-needed div with some text content, there are currently 18 surfaces allocated in the display list. If there’s no blending going on, we should only need one!
Let’s review all the surfaces that our code can create for an element:
But not every element has opacity, blend modes, or clipping applied,
and we could skip creating those surfaces most of the time. To implement
this without making the code hard to read, let’s change
SaveLayer to take two additional optional parameters:
should_save and
should_paint_cmds. These
control whether
saveLayer is called and whether subcommands
are actually painted:
class SaveLayer: def __init__(self, sk_paint, children, =True, should_paint_cmds=True): should_saveself.should_save = should_save self.should_paint_cmds = should_paint_cmds # ... def execute(self, canvas): if self.should_save: =self.sk_paint) canvas.saveLayer(paintif self.should_paint_cmds: for cmd in self.children: cmd.execute(canvas)if self.should_save: canvas.restore()
Turn off those parameters if an effect isn’t applied:
def paint_visual_effects(node, cmds, rect): # ... = node.style.get("overflow", "visible") == "clip" needs_clip = blend_mode != skia.BlendMode.kSrcOver or \ needs_blend_isolation needs_clip= opacity != 1.0 needs_opacity return [ =blend_mode), [ SaveLayer(skia.Paint(BlendMode=opacity), cmds, SaveLayer(skia.Paint(Alphaf=needs_opacity), should_save=skia.kDstIn), [ SaveLayer(skia.Paint(BlendMode"white") DrawRRect(rect, clip_radius, =needs_clip, should_paint_cmds=needs_clip), ], should_save=needs_blend_isolation), ], should_save ]
Now simple web pages always use a single surface—a huge saving in memory. But we can save even more surfaces. For example, what if there is a blend mode and opacity at the same time: can we use the same surface? Indeed, yes you can! That’s also pretty simple:This works for opacity, but not for filters that “move pixels” such as blur. Such a filter needs to be applied before clipping, not when blending into the parent surface. Otherwise, the edge of the blur will not be sharp.
def paint_visual_effects(node, cmds, rect): # ... = node.style.get("overflow", "visible") == "clip" needs_clip = blend_mode != skia.BlendMode.kSrcOver or \ needs_blend_isolation needs_clip= opacity != 1.0 needs_opacity return [ =blend_mode, Alphaf=opacity), SaveLayer(skia.Paint(BlendMode+ [ cmds =skia.kDstIn), [ SaveLayer(skia.Paint(BlendMode"white") DrawRRect(rect, clip_radius, =needs_clip, should_paint_cmds=needs_clip), ], should_save=needs_blend_isolation or needs_opacity), ], should_save ]
There’s one more optimization to make: using Skia’s
clipRRect operation to get rid of the destination-in
blended surface. This operation takes in a rounded rectangle and changes
the canvas state so that all future commands skip drawing any
pixels outside that rounded rectangle.
There are multiple advantages to using
clipRRect over an
explicit destination-in surface. First, most of the time, it allows Skia
to avoid making a surface for the mask.Typically in a browser this
means code in GPU shaders. GPU programs are out of scope for this book,
but if you’re curious there are many online resources describing ways to
do this. It also allows Skia to skip draw operations that
don’t intersect the mask, or dynamically draw only the parts of
operations that intersect it. It’s basically the optimization we
implemented for scrolling in
Chapter 2.This kind
of code is complex for Skia to implement, so it only makes sense to do
it for common patterns, like rounded rectangles. This is why Skia only
supports optimized clips for a few common shapes.
Since
clipRRect changes the canvas state, we’ll need to
restore it once we’re done with clipping. That uses the
save and
restore methods—you call
save before calling
clipRRect, and
restore after finishing drawing the commands that should be
clipped:
# Draw commands that should not be clipped. canvas.save() canvas.clipRRect(rounded_rect) # Draw commands that should be clipped. canvas.restore() # Draw commands that should not be clipped.
If you’ve noticed that
restore is used for both saving
state and pushing surfaces, that’s because Skia has a combined stack of
surfaces and canvas states. Unlike
saveLayer, however,
save never creates a new surface.
Let’s wrap this pattern into a
ClipRRect drawing
command, which like
SaveLayer takes a list of subcommands
and a
should_clip parameter indicating whether the clip is
necessary:If you’re
doing two clips at once, or a clip and a transform, or some other more
complex setup that would benefit from only saving once but doing
multiple things inside it, this pattern of always saving canvas
parameters might be wasteful, but since it doesn’t create a surface it’s
still a big optimization here.
class ClipRRect: def __init__(self, rect, radius, children, should_clip=True): self.rect = rect self.rrect = skia.RRect.MakeRectXY(rect, radius, radius) self.children = children self.should_clip = should_clip def execute(self, canvas): if self.should_clip: canvas.save()self.rrect) canvas.clipRRect( for cmd in self.children: cmd.execute(canvas) if self.should_clip: canvas.restore()
Now, in
paint_visual_effects, we can use
ClipRRect instead of destination-in blending with
DrawRRect:
def paint_visual_effects(node, cmds, rect): # ... return [ =blend_mode, Alphaf=opacity), [ SaveLayer(skia.Paint(BlendMode ClipRRect(rect, clip_radius, cmds,=needs_clip), should_clip=needs_blend_isolation), ], should_save ]
Of course,
clipRRect only applies for rounded
rectangles, while masking is a general technique that can be used to
implement all sorts of clips and masks (like CSS’s
clip-path and
mask), so a real browser will
typically have both code paths.
So now, each element uses at most one surface, and even then only if it has opacity or a non-default blend mode. Everything else should look visually the same, but will be faster and use less memory.
Besides using fewer surfaces, real browsers also need to avoid surfaces getting too big. Real browsers use tiling for this, breaking up the surface into a grid of tiles which have their own raster surfaces and their own x and y offset to the page. Whenever content that intersects a tile changes its display list, the tile is re-rastered. Tiles that are not on or “near”For example, tiles that just scrolled off-screen. the screen are not rastered at all. This all happens on the GPU, since surfaces (Skia ones in particular) can be stored on the GPU.
Optimizing away surfaces is great when they’re not needed, but sometimes having more surfaces allows faster scrolling and animatations.
So far, any time anything changed in the browser chrome or the web page itself, we had to clear the canvas and re-raster everything on it from scratch. This is inefficient—ideally, things should be re-rastered only if they actually change. When the context is complex or the screen is large, rastering too often produces a visible slowdown, and laptop and mobile batteries are drained unnecessarily. Real browsers optimize these situations by using a technique I’ll call browser compositing. The idea is to create a tree of explicitly cached surfaces for different pieces of content. Whenever something changes, we’ll re-raster only the surface where that content appears. Then these surfaces are blended (or “composited”) together to form the final image that the user sees.
Let’s implement this, with a surface for browser chrome and a surface
for the current
Tab’s contents. This way, we’ll only need
to re-raster the
Tab surface if page contents change, but
not when (say) the user types into the address bar. This technique also
allows us to scroll the
Tab without any raster at all—we
can just translate the page contents surface when drawing it.
To start with, we’ll need two new surfaces on
Browser,
chrome_surface and
tab_surface:We could even use a different
surface for each
Tab, but real browsers don’t do this,
since each surface uses up a lot of memory, and typically users don’t
notice the small raster delay when switching tabs.
class Browser: def __init__(self): # ... self.chrome_surface = skia.Surface(WIDTH, CHROME_PX) self.tab_surface = None
I’m not explicitly creating
tab_surface right away,
because we need to lay out the page contents to know how tall the
surface needs to be.
We’ll also need to split the browser’s
draw method into
three parts:
drawwill composite the chrome and tab surfaces and copy the result from Skia to SDL;
raster_tabwill draw the page to the
tab_surface; and
raster_chromewill draw the browser chrome to the
chrome_surface.
Let’s start by doing the split:
class Browser: def raster_tab(self): = self.tab_surface.getCanvas() canvas canvas.clear(skia.ColorWHITE)# ... def raster_chrome(self): = self.chrome_surface.getCanvas() canvas canvas.clear(skia.ColorWHITE)# ... def draw(self): = self.root_surface.getCanvas() canvas canvas.clear(skia.ColorWHITE)# ...
Since we didn’t create the
tab_surface on startup, we
need to create it at the top of
raster_tab:For a very big web page, the
tab_surface can be much larger than the size of the SDL
window, and therefore take up a very large amount of memory. We’ll
ignore that, but a real browser would only paint and raster surface
content up to a certain distance from the visible region, and
re-paint/raster as the user scrolls.
import math class Browser: def raster_tab(self): = self.tabs[self.active_tab] active_tab = math.ceil(active_tab.document.height) tab_height if not self.tab_surface or \ != self.tab_surface.height(): tab_height self.tab_surface = skia.Surface(WIDTH, tab_height) # ...
The way we compute the page bounds here, based on the layout tree’s height, would be incorrect if page elements could stick out below (or to the right) of their parents—but our browser doesn’t support any features like that. Note that we need to recreate the tab surface if the page’s height changes.
Next, we need new code in
draw to copy from the chrome
and tab surfaces to the root surface. Moreover, we need to translate the
tab_surface down by
CHROME_PX and up by
scroll, and clips it to only the area of the window that
doesn’t overlap the browser chrome:
class Browser: def draw(self): # ... = skia.Rect.MakeLTRB(0, CHROME_PX, WIDTH, HEIGHT) tab_rect = CHROME_PX - self.tabs[self.active_tab].scroll tab_offset canvas.save() canvas.clipRect(tab_rect)0, tab_offset) canvas.translate(self.tab_surface.draw(canvas, 0, 0) canvas.restore() = skia.Rect.MakeLTRB(0, 0, WIDTH, CHROME_PX) chrome_rect canvas.save() canvas.clipRect(chrome_rect)self.chrome_surface.draw(canvas, 0, 0) canvas.restore() # ...
Finally, everywhere in
Browser that we call
draw, we now need to call either
raster_tab or
raster_chrome first. For example, in
handle_click, we do this:
class Browser: def handle_click(self, e): if e.y < CHROME_PX: # ... self.raster_chrome() else: # ... self.raster_tab() self.draw()
Notice how we don’t redraw the chrome when the only the tab changes,
and vice versa. In
handle_down, which scrolls the page, we
don’t need to call
raster_tab at all, since scrolling
doesn’t change the page.
We also have some related changes in
Tab. First, we no
longer need to pass around the scroll offset to the
execute
methods, or account for
CHROME_PX, because we always draw
the whole tab to the tab surface:
class Tab: def raster(self, canvas): for cmd in self.display_list: cmd.execute(canvas)
Likewise, we can remove the
scroll parameter from each
drawing command’s
execute method:
class DrawRect: def execute(self, canvas): draw_rect(canvas,self.left, self.top, self.right, self.bottom, =self.color, width=0) fill
Our browser now uses composited scrolling, making scrolling faster and smoother. In fact, in terms of conceptual phases of execution, our browser is now very close to real browsers: real browsers paint display lists, break content up into different rastered surfaces, and finally draw the tree of surfaces to the screen. There’s more we can do for performance—ideally we’d avoid all duplicate or unnecessary operations—but let’s leave that for the next few chapters.
Real browsers allocate new surfaces for various different situations,
such as implementing accelerated overflow scrolling and animations of
certain CSS properties such as transform
and opacity that can be done without raster. They also allow scrolling
arbitrary HTML elements via
overflow: scroll
in CSS. Basic scrolling for DOM elements is very similar to what we’ve
just implemented. But implementing it in its full generality, and with
excellent performance, is extremely challenging. Scrolling is
probably the single most complicated feature in a browser rendering
engine. The corner cases and subtleties involved are almost endless.
So there you have it: our browser can draw not only boring text and boxes but also:
mix-blend-mode
Besides the new features, we’ve upgraded from Tkinter to SDL and Skia, which makes our browser faster and more responsive, and also sets a foundation for more work on browser performance to come.)
FONTS
def get_font(size, weight, style)
def parse_color(color)
def parse_blend_mode(blend_mode_str)
def linespace(font)
class SaveLayer:
def __init__(sk_paint, children, should_save, should_paint_cmds)
def execute(canvas)
class DrawRRect:
def __init__(rect, radius, color)
def execute(canvas)
class DrawText:
def __init__(x1, y1, text, font, color)
def execute(canvas)
def __repr__()
class DrawRect:
def __init__(x1, y1, x2, y2, color)
def execute(canvas)
def __repr__()
class DrawLine:
def __init__(x1, y1, x2, y2)
def execute(canvas)
class ClipRRect:
def __init__(rect, radius, children, should_clip)
def execute(canvas)
def draw_line(canvas, x1, y1, x2, y2)
def draw_text(canvas, x, y, text, font, color)
def draw_rect(canvas, l, t, r, b, fill, width) paint_visual_effects(node, cmds, rect)
SCROLL_STEP
CHROME_PX
class Tab:
def __init__()
def allowed_request(url)
def load(url, body)
def render()
def raster(canvas)
def scrolldown()
def click(x, y)
def submit_form(elt)
def keypress(char)
def go_back()
WIDTH, HEIGHT
HSTEP, VSTEP
class Browser:
def __init__()
def handle_down()
def handle_click(e)
def handle_key(char)
def handle_enter()
def load(url)
def raster_tab()
def raster_chrome()
def draw()
def handle_quit()
if __name__ == "__main__"
CSS transforms: Add support for the transform
CSS property, specifically the
translate and
rotate transforms.There is a lot more complexity to 3D transforms having to
do with the definition of 3D spaces, flatting, backfaces, and plane
intersections. Skia has built-in support for these via
canvas state.
Filters: The
filter CSS property allows
specifying various kinds of more complex
effects, such as grayscale or blur. These are fun to implement, and
a number of them have built-in support in Skia. Implement, for example,
the
blur filter. Think carefully about when filters occur,
relative to other effects like transparency, clipping, and blending.
Hit testing: If you have an element with a
border-radius, it’s possible to click outside the element
but inside its containing rectangle, by clicking in the part of the
corner that is “rounded off”. This shouldn’t result in clicking on the
element, but in our browser it currently does. Modify the
click method to take border radii into account.
Interest region: Our browser now draws the whole web page to
a single surface, and then shows parts of that surface as the user
scrolls. That means a very long web page (like this one!) can create a
large surface, thereby using a lot of memory. Modify the browser so that
the height of that surface is limited, say to
4 * HEIGHT
pixels. The (limited) region of the page drawn to this surface is called
the interest region; you’ll need to track what part of the interest
region is being shown on the screen, and re-raster the interest region
when the user attempts to scroll outside of it.
One way to do this is to filter out all display list items that don’t
intersect the interest rect. Another, easier way is to take advantage of
Skia’s internal optimizations: if you call
save and
clipRect on a Skia canvas and then some draw operations,
Skia will automatically avoid display item raster work outside of the
clipping rectangle before the next
restore.
Z-index: Right now, elements later in the HTML document are
drawn “on top” of earlier ones. The
z-index CSS property
changes that order: an element with the larger
z-index
draws on top (with ties broken by the current order, and with the
default
z-index being 0). For
z-index to have
any effect, the element’s
position property must be set to
something other than
static (the default). Add support for
z-index. One thing you’ll run into is that with our
browser’s minimal layout features, you might not be able to
create any overlapping elements to test this feature! However,
lots of exercises throughout the book allow you to create overlapping
elements, including
transform and
width/
height. For an extra challenge, add
support for nested
elements with
z-index properties.
Overflow scrolling: An element with the
overflow property set to
scroll and a fixed
pixel
height is scrollable. (You’ll want to implement the
width/height exercise from Chapter 6
so that
height is supported.) Implement some version of
overflow: scroll. I recommend the following user
interaction: the user clicks within a scrollable element to focus it,
and then can press the arrow keys to scroll up and down. You’ll need to
keep track of the layout
overflow. For an extra challenge, make sure you support
scrollable elements nested within other scrollable elements.
Did you find this chapter useful?
|
https://browser.engineering/visual-effects.html
|
CC-MAIN-2022-33
|
refinedweb
| 9,662
| 55.24
|
Need help in hovercraft question
Here's my try👇👇 #include <iostream> using namespace std; int main() { int month, hovercraft; month = (10*2000000)+1000000; cin>> hovercraft ; int sale; sale = hovercraft*3000000; if(month=hovercraft){ cout<<"Broke Even"; } else if (month >hovercraft ){ cout<<"Loss"; } else { cout<<"Profit"; } return 0; }
4/11/2021 4:50:14 AMShravan Mathapati
5 AnswersNew Answer
You need to use `==` operator to compare two variables. month == sale hovercraft is your input variable. You can use other variables to check the condition. month < sale
Nothing much! You can check why you declared month & sale variables once. Your month variable indicates how much money you spent to create hovercrafts whereas your sale variable indicates how much money you got by selling hovercrafts. Hovercraft is an input variable to count how many hovercrafts you sold. Let's say you sold 10 hovercrafts. So, hovercraft = 10 sale = 10*3000000 month = (10*200000)+1000000 Which two variables you will take to calculate the profit or loss?
Shravan Mathapati He want to say use double (==) for comparison because single equal (=) use for assignment hovercraft is a month so you can't compare with amount. You have to compare total amount with total sell So here month = (10 * 2000000) + 1000000; sale = hovercraft * 3000000; if (sale < month) { cout << "Loss"; } else if(sale > month) { cout << "Profit"; } else { cout << "Broken Even"; }
🅰🅹 (Challenge Accepted) thank you 😅😅
Simba can you explain, i couldn't understand what you told
|
https://www.sololearn.com/Discuss/2751720/need-help-in-hovercraft-question
|
CC-MAIN-2021-21
|
refinedweb
| 238
| 59.84
|
Developer Example: Web Integration
This section describes some possibilities for integration of the Access Grid with the web. These include modifications to the Venue Server to handle calls from web browsers to using web-oriented languages to call the Access Grid services directly.
VenueServer / SOAP Server (ZSI) / SSLServer / SocketServer
AGSOAPRequestHandler / SOAPRequestHandler (ZSI) / BaseHTTPRequestHandler
The request handlers define do_GET and do_POST methods that handle these two request types. do_POST is used by the SOAP server for handling method calls. do_GET is ignored, except for requests for the WSDL of a service, which is obtained by appending '?wsdl' to the URL of the service.
By modifying the behavior of the request handler, however, one can modify the behavior of the Venue Server with regard to HTTP GET requests.
Integrating the custom request handler into the Venue Server (a hack for now).
Edit AccessGrid/hosting/ZSI/ServiceContainer.py. Add the following import line at the top of the file:
from CustomRequestHandler import CustomRequestHandler
and modify the SecureServiceContainer constructor (__init__) to use the CustomRequestHandler:
def __init__(self, server_address,context, services=[],RequestHandlerClass=CustomRequestHandler):
Now the CustomRequestHandler will be called for each request.
(review the CustomRequestHandler.py code)
Starting the VenueServer with these changes, and entering the Venue Server URL in a web browser returns an HTML representation of the Venue. Note that other rooms are represented by links which, if clicked, show the HTML view of that room. Also, data is represnted as links and can be viewed directly in the browser.
do_GET really must check the security of the Venue before allowing HTTP GET requests through. In the trivial case, one could check if a certificate is required for accessing the Venue and, if so, disallowing the GET request. More correct would be to check if the certificate has been specifically authorized; in this case, the browser would have to present the appropriate certificate, which it should be able to do without trouble.
Perhaps hacking the Venue Server is distasteful to you. In that case, consider the possibility of an adapter that talks to the VenueServer on one side and presents suitable HTML representations on the other side. A simple example doing this with PHP follows.
$venueclient = new soapclient('');
print $venueclient->GetState();
Ideally, the Venue Server would support plugins for integration of third-party code, similar to the mod_ support of Apache. In that case, a custom request handler would be integrated with the Venue Server via a plugin
login or register to post comments
|
http://www.accessgrid.org/developer/example/WebIntegration
|
CC-MAIN-2018-05
|
refinedweb
| 411
| 52.19
|
explain_bind_or_die - bind a name to a socket and report errors
#include <libexplain/bind.h> void explain_bind_or_die(int fildes, const struct sockaddr *sock_addr, int sock_addr_size);
The explain_bind_or_die function is used to call the bind(2) system call. On failure an explanation will be printed to stderr, obtained from explain_bind(3), and then the process terminates by calling exit(EXIT_FAILURE). This function is intended to be used in a fashion similar to the following example: explain_bind_or_die(fildes, sock_addr, sock_addr_size); fildes The fildes, exactly as to be passed to the bind(2) system call. sock_addr The sock_addr, exactly as to be passed to the bind(2) system call. sock_addr_size The sock_addr_size, exactly as to be passed to the bind(2) system call. Returns: This function only returns on success. On failure, prints an explanation and exits.
bind(2) bind a name to a socket explain_bind(3) explain bind(2) errors exit(2) terminate the calling process
libexplain version 0.19 Copyright (C) 2008 Peter Miller explain_bind_or_die(3)
|
http://huge-man-linux.net/man3/explain_bind_or_die.html
|
CC-MAIN-2018-05
|
refinedweb
| 164
| 56.45
|
I managed to get exult cross compiled for oz 3.5.2
Here is the working binary
It works perfectly however there is a weird problem, the default fmopl midi driver seems to stutter on my 5500.
So my solution was to use the libsdl's mixer_midi driver. I had to edit the audio/Midi.cc and add the lines,
#include "midi_drivers/mixer_midiout.h"
TRY_MIDI_DRIVER(Mixer_MidiOut);
Of course this requires that you have the timidity patch set installed and that /usr/local/timidity is symlinked to that patch set, when run sdl_mixer finds the patches and you get beautiful midi music on the Z :-)
Here is a link to that binary
I setup everything in the /mnt/card/u7 directory.
Here is my ~/.exult.cfg
Here is a directory listing of my /mnt/card/u7 directory......
Hope you have fun with exult :-)
I will post the compilation instructions shortly, in a seperate mail, i am busy now and have to go......compilation involves some hacks for example the sdl-config file has to be changed etc....i will cover this soon.....
I am aware that some people are reluctant to run binaries on there Z, but rest assured that this is the real thing, you can see in the oz updates changelog that my suggestions for prboom have resulted in it been added to the oz feed, so you know that i am not some script kiddie posting trojans here.
|
http://www.oesf.org/forum/lofiversion/index.php/t11041.html
|
CC-MAIN-2014-10
|
refinedweb
| 240
| 61.16
|
This namespace contains G-API functions, structures, and symbols related to the Streaming execution mode. More...
This namespace contains G-API functions, structures, and symbols related to the Streaming execution mode.
Some of the operations defined in this namespace (e.g. size(), BGR(), etc.) can be used in the traditional execution mode too.
Gets bgr plane from input frame.
Starts a desynchronized branch in the graph.
This operation takes a single G-API data object and returns a graph-level "duplicate" of this object.
Operations which use this data object can be desynchronized from the rest of the graph.
This operation has no effect when a GComputation is compiled with regular cv::GComputation::compile(), since cv::GCompiled objects always produce their full output vectors.
This operation only makes sense when a GComputation is compiled in streaming mode with cv::GComputation::compileStreaming(). If this operation is used and there are desynchronized outputs, the user should use a special version of cv::GStreamingCompiled::pull() which produces an array of cv::util::optional<> objects.
Gets dimensions from Mat.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Gets dimensions from rectangle.
Gets dimensions from MediaFrame.
|
https://docs.opencv.org/5.x/df/d5b/namespacecv_1_1gapi_1_1streaming.html
|
CC-MAIN-2022-21
|
refinedweb
| 205
| 51.65
|
fgetws - read a wide-character string from a FILE stream
#include <wchar.h>
wchar_t *fgetws(wchar_t *ws, int n, FILE *stream);
The fgetws() function is the wide-character equivalent of the fgets(3) function. It reads a string of at most n-1 wide characters into the wide-character array pointed to by ws, and adds a terminating null wide character (L'\0'). It stops reading wide characters after it has encountered and stored a newline wide character. It also stops when end of stream is reached.
The programmer must ensure that there is room for at least n wide characters at ws.
For a nonlocking counterpart, see unlocked_stdio(3).
The fgetws() function, if successful, returns ws. If end of stream was already reached or if an error occurred, it returns NULL.
For an explanation of the terms used in this section, see attributes(7).
POSIX.1-2001, POSIX.1-2008, C99.
The behavior of fgetws() depends on the LC_CTYPE category of the current.
fgetwc(3), unlocked_stdio(3)
This page is part of release 4.15 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
|
https://www.zanteres.com/manpages/fgetws.3.html
|
CC-MAIN-2022-33
|
refinedweb
| 202
| 75.1
|
This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.
This version built as cleanly as anything ever does on win95. Minor nits: complaints about redefines of POSIX may be cured by putting #ifndef POSIX..#endif in the xm-cygwin32.h. Also, the tendency to set HAVE_INTTYPES_H erroneously remains, and that can be cured by putting #undef HAVE_INTTYPES_H in following the above. config.log looks like the tests are as expected, yet the macro may become defined anyway. In order to persuade libf2c to build, I went into libf2c/Makefile.in and changed the undefined s-lib[if]77 to [if]77. That one I suspect may be needed in some builds other than wiin95. To: INTERNET - IBMMAIL
|
http://gcc.gnu.org/ml/gcc-bugs/1998-08/msg00071.html
|
CC-MAIN-2019-22
|
refinedweb
| 126
| 69.58
|
Results 1 to 2 of 2
Thread: Inheritance Class help
- Join Date
- Nov 2010
- 2
- Thanks
- 1
- Thanked 0 Times in 0 Posts
Inheritance Class help
I was given this assignment to coplete, however know nothing about inhetiance in java
i have this code already but by use of inheritance have to add 2 other classes and a user class, how do i do this?
the code i have so far is:
Code:
public class Piece { // attributes protected String name; protected int posX; protected int posY; protected boolean moves = true; // constructors public Piece (String theName, int x, int y) { name = theName; posX = x; posY = y; } // methods // Gets the value of the name public String getName() { return name; } // Gets the value of the x coordinate public int getPosX() { return posX; } // Gets the value of the y coordinate public int getPosY() { return posY; } // Gets the value of moves public boolean getMoves() { return moves; } // Sets the value of the x coordinate public void setPosX(int x) { posX = x; } // Sets the value of the y coordinate public void setPosY(int y) { posY = y; } // Converts posX and posY into a single integer. For example (2,1) will return 21. // This may help defining move methods given a particular position. public int positionCode () { return (posX*10) + posY; } }
i have to add a treasure and person class as said below
The pieces have a name, x and y co-ordinates (each between 1 and 3) and
whether they can be moved or not. Treasure has the value a positive integer. In the person class it must state if the treasure has been found.
Treasure is placed at one ofnine locations, it cannot move. person is placed at one of the nine locations and searches for the treasure.
The person can move from its location right, left, up or down (where possible)
one square, but not diagonally. For example from (1,2) a person could move to either (1,1), (2,2) or (1,3). From the location (3,3) the person could move to (2,3) or (3,2).
The person can see the treasure if it is in the same row or column (i.e. has the same x coordinates or the same y coordinates). For example if the person is at (1,1) and the treasure is at (1,3) the person can see the treasure. However if the person is at (1,1) and the treasure is at (2,2) the person cannot see the treasure. If the person can see the treasure they move one step towards it. For example if the person is at (1,1) and the treasure is at (1,3) the person moves to (1,2). If they cannot see the treasure they move in some direction one step.
The program should input the name, co-ordinates and value of the treasure, and the name and co-ordinates of the person. Negative or zero treasure values should be disallowed.
Co-ordinates not in the range 1-3 should be disallowed. Additionally the program should print out the moves of the person, i.e. the name and location of the person
and whether the treasure has been found until they find the treasure. You should use inheritance in your solution to obtain the classes Treasure and Person. There should be a user class that asks for input and instantiates Treasure and Person.
- Join Date
- Feb 2008
- Location
- Edinburgh - Scotland
- 107
- Thanks
- 0
- Thanked 12 Times in 12 Posts
Hi,
I havent read your post fully **lack of time** but I can show you what inheritance is and why you would want it.
If you were creating a game - with lots of types of monsters in it, you might have a class for each type of monster with their attributes, health, magic power, size, x coord, y coord, power etc etc etc.
If you have 20 monsters, you then need 20 of the above code repeated 20 times which is a massive waste.
So you can you use inheritance as follows:
Code:
public class Monster{ String name; int xCoord; int yCoord; int health; public Monster(String name, int xCoord, int yCoord, int health){ this.name = name; this.xCoord = xCoord; this.yCoord = yCoord; this.health = health; } } public class MonkeyManMonster extends Monster{ Color color; public MonkeyManMonster((String name, int xCoord, int yCoord, int health,Color color){ super(name,xCoord,yCoord,health); // calls the Monster class constructor this.color = color; } } }
Hope this helps
|
http://www.codingforums.com/java-and-jsp/210974-inheritance-class-help.html
|
CC-MAIN-2015-48
|
refinedweb
| 739
| 67.99
|
Created on 2014-02-26 18:25 by r.david.murray, last changed 2014-03-13 16:05 by r.david.murray.
collections.abc was renamed _collections_abc in issue 19218. The __init__ file was modified to load all the abc into the collections namespace, but the 'abc' name itself is no longer defined:
Python 3.3.2 (default, Dec 17 2013, 17:24:42)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections
>>> collections.abc
<module 'collections.abc' from '/usr/lib/python3.3/collections/abc.py'>
Python 3.4.0rc1+ (default:1bc585ba5df2, Feb 24 2014, 15:04:31)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections
>>> collections.abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'abc'
It looks like the import statement for _collections_abc in the __init__ file as has missing "as abc" phrase.
This is probably not important enough to require fixing in the RC, since 'import collections.abc' works fine, but it is a regression.
I'm pretty sure that if you import "x", there are zero guarantees that "x.y" will work. The offical line is that you must explicitly import all the deepest submodules you use. So I don't think this is even a bug.
It is a backward compatibility bug. Something that used to work doesn't any more. And it was explicitly *made* to work previously (the original __init__ statement was 'import collections.abc'). And it is is an implementation bug in the original patch because otherwise there would be no point in importing _collections_abc in __init__.
But you are right, it is relatively unlikely that anyone is relying on it.
If we decide we want this (small) backward compatibility break, to make collections.abc consistent with the other modules (except os.path), then I should mention it in the whatsnew porting section for 3.4, which is really why I opened this issue :)
I that case, IMO, the import for _collections_abc should be removed from the collections __init__ file (in 3.4.1), just to keep things tidy.
> I'm pretty sure that if you import "x", there are zero guarantees that
> "x.y" will work. The offical line is that you must explicitly import
> all the deepest submodules you use.
I'm not sure why you're saying that. I think it's quite common to only
"import os" and then use os.path.
A quick grep indicates at least the following modules use os.path but only import os:
bdb, binhex, cgitb, compileall, cProfile, doctest, filecmp, fileinput, fnmatch, ftplib, gettext, glob, imghdr, imp, inspect, linecache, mailbox, mimetypes, modulefinder, netrc, optparse, pdb, platform, profile, pstats, pyclbr, pydoc, shlex, site, sndhdr, ssl, subprocess, tabnanny, tarfile, trace, uuid, uu, webbrowser, zipfile.
So, it's a very common idiom.
May be add temporary replacement for collections.abc?
class _AbcModulePlaceholder(type(_collections_abc)):
def __warn(self):
import warnings
warnings.warn('collections.abc used without importing',
DeprecationWarning, 3)
def __getattr__(self, name):
self.__warn()
return getattr(_collections_abc, name)
def __setattr__(self, name, value):
self.__warn()
setattr(_collections_abc, name, value)
def __delattr__(self, name):
self.__warn()
delattr(_collections_abc, name)
def __dir__(self):
self.__warn()
return dir(_collections_abc)
abc = _AbcModulePlaceholder('abc')
>.
I stand by my statement.
> >.
Yes, you are technically right. But this is an idealized view of what
backwards compatibility means in the real world.
Well, let's see if people complain after 3.4 is released, anyway.
Item possibly related to this. When packaging a simple HelloWorld-like application like this:
print("Hello world")
import configparser
using cx_Freeze and Python 3.4, you get the following error on packaged application startup:
Traceback (most recent call last):
File "C:\Program Files\Python\Python34rc3\lib\site-packages\cx_freeze-4.3.2-py3.4-win-amd64.egg\cx_Freeze\initscripts\Console3.py", line 27, in <module>
exec(code, m.__dict__)
File "hello_world.py", line 4, in <module>
File "C:\Program Files\Python\Python34rc3\lib\importlib\_bootstrap.py", line 2214, in _find_and_load
return _find_and_load_unlocked(name, import_)
File "C:\Program Files\Python\Python34rc3\lib\importlib\_bootstrap.py", line 2203, in _find_and_load_unlocked
module = _SpecMethods(spec)._load_unlocked()
File "C:\Program Files\Python\Python34rc3\lib\importlib\_bootstrap.py", line 1191, in _load_unlocked
return self._load_backward_compatible()
File "C:\Program Files\Python\Python34rc3\lib\importlib\_bootstrap.py", line 1161, in _load_backward_compatible
spec.loader.load_module(spec.name)
File "C:\Program Files\Python\Python34rc3\lib\configparser.py", line 121, in <module>
from collections.abc import MutableMapping
File "C:\Program Files\Python\Python34rc3\lib\importlib\_bootstrap.py", line 2214, in _find_and_load
return _find_and_load_unlocked(name, import_)
File "C:\Program Files\Python\Python34rc3\lib\importlib\_bootstrap.py", line 2201, in _find_and_load_unlocked
raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named 'collections.abc'
As I see it, the config parser module is attempting to import
'collections.abc'.
The same does not occur with Python 3.3.5 or 3.3.3.
Not sure if this is due to something cx_Freeze does so it failed to collect some module in the created installation package, or if it's something to look into in Python itself. Just looked similar to this so I bring it up as additional info for anyone looking deeper into this issue.
Hope this helps.
Best regards,
Jurko Gospodnetić
> Item possibly related to this.
I cannot reproduce your issue, it looks like a bug in cx_Freeze. "import collections" doesn't import "collections.abc" by default anymore, but configparser is correct: "from collections.abc import MutableMapping". So it imports explicitly "collections.abc".
> I cannot reproduce your issue
Meaning you do not have the environment set up for this or that you tried it and it worked for you?
If it 'worked for you', I can send you more detailed environment information when get back to my office in an hour or so.
>> I cannot reproduce your issue
> Meaning you do not have the environment set up for this or that
> you tried it and it worked for you?
I mean that executing the following lines in Python doesn't fail:
---
print("Hello world")
import configparser
---
It's specific to cx_Freeze and unrelated to this issue.
cx-freeze feedback is better added to issue 20884 - I currently still suspect that 3.4 has just uncovered some latent spec non-compliance in the cx-freeze import system emulation (although I need to investigate further to be sure, since it's also possible we accidentally broke backwards compatibility with certain kinds of legacy behaviour when implementing PEP 451).
For this issue, I don't think os.path can be used as a precedent - "os" isn't a package, and "os.path" isn't a normal submodule (instead, the os module does a dance to figure out which top level module to import as path - it's usually either ntpath or posixpath).
Instead, this is just normal submodule import behaviour - "import collections" doesn't necessarily imply "import collections.abc", it just used to do so because that was how the backwards compatibility for the old names happened to be implemented.
Setting the attribute would also shadow the submodule, which would be a little weird (since collections.abc could then refer to either that module or to _collections_abc). Really, the change to collections/__init__.py could just be reverted - the _collections_abc move was just to avoid running collections/__init__.py at startup, so there's no need to use the hack inside collections/__init__.py itself.
Oh, and yes, this is *definitely* a bug: _collections_abc.__name__ is set to "collections.abc", but if "collections.abc" isn't imported anywhere in the program, then cx-freeze and similar tools will miss the fact that "collections.abc" should be bundled.
If "collections" is changed back to implicitly importing the submodule, that problem should go away (although the lie in __name__ for pickle compatibility may still cause problems with freezing, so it's perhaps worth mentioning in the porting notes regardless).
New changeset d575398d1916 by R David Murray in branch 'default':
whatsnew: collections no longer implicitly imports 'abc' (#20784).
I've documented that 'collections.abc' is no longer implicit, which I presume means we are going to keep this behavior. (Unless you tell me to revert that and we fix it as a regression in 3.4.1).
As long as an application follows the note and explicitly imports collections.abc, I would think that the freeze tools would do the right thing. I'd think they'd do the right thing anyway, since _collections_abc appears in an 'import from' in collections.__init__, so I'm not clear what problem is anticipated for freeze tools that is different from the one that any program relying on the implicit import would face.
|
http://bugs.python.org/issue20784
|
CC-MAIN-2016-30
|
refinedweb
| 1,459
| 51.55
|
import "cuelang.org/go/pkg/list"
Package list contains functions for manipulating and examining lists.
list.go math.go pkg.go sort.go
Avg returns the average value of a non empty list xs.
Contains reports whether v is contained in a. The value must be a comparable value.
Drop reports the suffix of list x after the first n elements, or [] if n > len(x).
For instance:
Drop([1, 2, 3, 4], 2)
results in
[3, 4]
FlattenN reports a flattend sequence of the list xs by expanding any elements depth levels deep. If depth is negative all elements are expanded.
For instance:
FlattenN([1, [[2, 3], []], [4]], 1)
results in
[1, [2, 3], [], 4]
IsSorted tests whether a list is sorted.
See Sort for an example comparator.
IsSortedStrings tests whether a list is a sorted lists of strings.
Max returns the maximum value of a non empty list xs.
MaxItems reports whether a has at most n items.
Min returns the minimum value of a non empty list xs.
MinItems reports whether a has at least n items.
Product returns the product of a non empty list xs.
Range generates a list of numbers using a start value, a limit value, and a step value.
For instance:
Range(0, 5, 2)
results in
[0, 2, 4]
Slice extracts the consecutive elements from list x starting from position i up till, but not including, position j, where 0 <= i < j <= len(x).
For instance:
Slice([1, 2, 3, 4], 1, 3)
results in
[2, 3]
Sort sorts data. It does O(n*log(n)) comparisons. The sort is not guaranteed to be stable.
cmp is a struct of the form {T: _, x: T, y: T, less: bool}, where less should reflect x < y.
Example:
Sort([2, 3, 1], list.Ascending) Sort{{a: 2}, {a: 3}, {a: 1}, {x: {}, y: {}, less: x.a < y.a}}
SortStable sorts data while keeping the original order of equal elements. It does O(n*log(n)) comparisons.
See Sort for an example usage.
Strings sorts a list of strings in increasing order.
Sum returns the sum of a list non empty xs.
Take reports the prefix of length n of list x, or x itself if n > len(x).
For instance:
Take([1, 2, 3, 4], 2)
results in
[1, 2]
UniqueItems reports whether all elements in the list are unique.
Package list imports 7 packages (graph) and is imported by 1 packages. Updated 2020-09-18. Refresh now. Tools for package owners.
|
https://godoc.org/cuelang.org/go/pkg/list
|
CC-MAIN-2020-40
|
refinedweb
| 420
| 76.01
|
ZORP: A helpful GWAS parser
Project description
ZORP: A helpful GWAS parser
Why?
ZORP is intended to abstract away differences in file formats, and help you work with GWAS data from many different sources.
- Provide a single unified interface to read text, gzip, or tabixed data
- Separation of concerns between reading and parsing (with parsers that can handle the most common file formats)
- Includes helpers to auto-detect data format and filter for variants of interest
Why not?
ZORP provides a high level abstraction. This means that it is convenient, at the expense of speed.
For GWAS files, ZORP does not sort the data for you, because doing so in python would be quite slow. You will still need to do some basic data preparation before using.
Installation
By default, zorp installs with as few python dependencies as practical. For more performance, and to use special features, install the additional required dependencies as follows:
$ pip install zorp[perf,lookups]
The snp-to-rsid lookup requires a very large file in order to work efficiently. You can download the pre-generated file
using the
zorp-assets command line script, as follows.
(use "--no-update" to skip warnings about already having the latest version)
$ zorp-assets download --type snp_to_rsid --tag genome_build GRCh37 --no-update $ zorp-assets download --type snp_to_rsid --tag genome_build GRCh37
Or build it manually (which may require first downloading a large source file):
$ zorp-assets build --type snp_to_rsid --tag genome_build GRCh37
Assets will be downloaded to the least user-specific location available, which may be overridden by setting the
environment variable
ZORP_ASSETS_DIR. Run
zorp-assets show --all to see the currently selected asset directory.
A note on rsID lookups
When developing on your laptop, you may not wish to download 16 GB of data per rsID lookup. A much smaller "test" dataset is available, which contains rsID data for a handful of pre-selected genes of known biological functionality.
$ zorp-assets download --type snp_to_rsid_test --tag genome_build GRCh37
To use it in your python script, simply add an argument to the SnpToRsid constructor:
rsid_finder = lookups.SnpToRsid('GRCh37', test=True)
If you have generated your own lookup using the code in this repo (
make_rsid_lookup.py), you may also replace
the genome build with a hardcoded path to the LMDB file of lookup data. This use case is fairly uncommon, however.
Usage
Python
from zorp import lookups, readers, parsers # Create a reader instance. This example specifies each option for clarity, but sniffers are provided to auto-detect # common format options. sample_parser = parsers.GenericGwasLineParser(marker_col=1, pvalue_col=2, is_neg_log_pvalue=True, delimiter='\t') reader = readers.TabixReader('input.bgz', parser=sample_parser, skip_rows=1, skip_errors=True) # After parsing the data, values of pre-defined fields can be used to perform lookups for the value of one field # Lookups can be reusable functions with no dependence on zorp rsid_finder = lookups.SnpToRsid('GRCh37') reader.add_lookup('rsid', lambda variant: rsid_finder(variant.chrom, variant.pos, variant.ref, variant.alt)) # Sometimes a more powerful syntax is needed- the ability to look up several fields at once, or clean up parsed data # in some way unique to this dataset reader.add_transform(lambda variant: mutate_entire_variant(variant)) # We can filter data to the variants of interest. If you use a domain specific parser, columns can be referenced by name reader.add_filter('chrom', '19') # This row must have the specified value for the "chrom" field reader.add_filter(lambda row: row.neg_log_pvalue > 7.301) # Provide a function that can operate on all parsed fields reader.add_filter('neg_log_pvalue') # Exclude values with missing data for the named field # Iteration returns containers of cleaned, parsed data (with fields accessible by name). for row in reader: print(row.chrom) # Tabix files support iterating over all or part of the file for row in reader.fetch('X', 500_000, 1_000_000): print(row) # Write a compressed, tabix-indexed file containing the subset of variants that match filters, choosing only specific # columns. The data written out will be cleaned and standardized by the parser into a well-defined format. out_fn = reader.write('outfile.txt', columns=['chrom', 'pos', 'pvalue'], make_tabix=True) # Real data is often messy. If a line fails to parse, the problem will be recorded. for number, message, raw_line in reader.errors: print('Line {} failed to parse: {}'.format(number, message))
Command line file conversion
The file conversion feature of zorp is also available as a command line utility. See
zorp-convert --help for details
and the full list of supported options.
This utility is currently in beta; please inspect the results carefully.
To auto-detect columns based on a library of commonly known file formats:
$ zorp-convert --auto infile.txt --dest outfile.txt --compress
Or specify your data columns exactly:
$ zorp-convert infile.txt --dest outfile.txt --index --skip-rows 1 --chrom_col 1 --pos_col 2 --ref_col 3 --alt_col 4 --pvalue_col 5 --beta_col 6 --stderr_beta_col 7 --allele_freq_col 8
The
--index option requires that your file be sorted first. If not, you can tabix the standard output format manually
as follows.
$ (head -n 1 <filename.txt> && tail -n +2 <file> | sort -k1,1 -k 2,2n) | bgzip > <filename.sorted.gz> $ tabix <filename.sorted.gz> -p vcf
Development
To install dependencies and run in development mode:
pip install -e '.[test,perf,lookups]'
To run unit tests, use
$ flake8 zorp $ mypy zorp $ pytest tests/
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/zorp/0.3.1/
|
CC-MAIN-2021-39
|
refinedweb
| 899
| 55.95
|
- The Anatomy of a FieldTemplate.
- Your First FieldTemplate.
- An Advanced FieldTemplate.
- A Second Advanced FieldTemplate.
- An Advanced FieldTemplate with a GridView.
- An Advanced FieldTemplate with a DetailsView.
- An Advanced FieldTemplate with a GridView/DetailsView Project.
Your First FieldTemplateWe’ll create a simple FieldTemplate that displays an enumeration as RadioButtonList.
Create Database and Table
We will need a database to run against so in Solution Explorer create a new ASP.Net folder App_Data in the root of the website and create a new Database in there called Animals. Now create a new table called Pets with the following columns.
Figure 1 – Pets Table
Create the Enumeration Type
/// <summary> /// My not very exhaustive set of animals /// </summary> public enum AnimalType { Budgie, Cat, Dog, Gerbil, Hamster, Lizard, Mouse, Parrot, Rat, Snake }
public enum Gender // Added { Male = 0, Female = 1 }
Listing 1 – AnimalType & Gender ***UPDATED***
Create the Model
Add a new Linq to SQL to the App_Code folder and and call it Animals. Copy the Pets table to it. Now we need to set the type of the Pets.Type to AnimalTypes and also do the same for the sex column setting its type to Gender.
Figure 2 - Setting the Pets.Type to the AnimalType enum
Save the and Close the Model.
In the same class file as the enums add your metadata.
using System.ComponentModel.DataAnnotations; using System.ComponentModel; [MetadataType(typeof(PetMetaData))] public partial class Pet { public class PetMetaData { [UIHint("Enumeration")] public object Animal { get; set; } [UIHint("Enumeration")] public object sex { get; set; } } }
Listing 2 – Pet metadata ***UPDATED***
Creating a New FieldTemplate
Expand the DynamicData folder and right-click on the FieldTemplates folder, choose Add New Item… and choose Web User Control from the list of items. Give it the name Enumeration_Edit.ascx
Change the base class that the user control inherits from System.Web.UI.UserControl to System.Web.DynamicData.FieldTemplateUserControl. and a new using System.Web.DynamicData. Change the class name to Enumeration_EditField from DynamicData_FieldTemplates_Enumeration_Edit in both the ascx and code behind files.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Enumeration.ascx.cs" Inherits="Enumeration_EditField" %>
Listing 3 – Enumeration_Edit.ascx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.DynamicData; public partial class Enumeration_EditField : System.Web.DynamicData.FieldTemplateUserControl { }
Listing 4 – Enumeration_Edit.ascx.cs code behind
The UserControl is now ready for us to add our code to make it show a DropDownList control populated with AnimalTypes.
Building Our Custom FieldTemplate
Add a DropDownList to the UserControl leave it as DropDownList1 and switch to the code behind.
In the code behind body of the class type protected override On and as you type On you will notice the auto-complete intellisense offer you some options use the arrow keys to select OnDataBinding and hit the tab key (but not too hard or you will break your keyboard :D).
Figure 3 - Auto-Complete Intellisense
Now you should have:
public partial class Enumeration_EditField : System.Web.DynamicData.FieldTemplateUserControl { protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); } }
Listing 5 – OnDataBinding event handler
I mentioned the above because I think it’s really neat
.
After the base.OnDataBinding(e); line we need to add our code to populate the DropDownList.
<%@ Control </asp:DropDownList>Listing 6 – Finished Enumeration_Edit.ascx note the OnDataBound
using System; using System.Web.UI; using System.Web.UI.WebControls; public partial class Enumeration_EditField : System.Web.DynamicData.FieldTemplateUserControl { protected override void OnDataBinding(EventArgs e) { // When overriding OnDataBinding be sure to call the base class's // OnDataBinding method so that registered delegates receive the event. base.OnDataBinding(e); // get a data bindable list of permissions for the DDL var enumList = Enum.GetValues(Column.ColumnType); DropDownList1.DataSource = enumList; DropDownList1.DataBind(); } protected override void ExtractValues(System.Collections.Specialized.IOrderedDictionary dictionary) { dictionary[Column.Name] = ConvertEditedValue(DropDownList1.SelectedValue); } protected void DropDownList1_DataBound(object sender, EventArgs e) { // make sure we are in edit mode if (Mode == DataBoundControlMode.Edit) { // try to get an item in the list that matched the FieldValueString ListItem item = DropDownList1.Items.FindByValue(FieldValueString); if (item != null) { // if we get the value set the drop down list to FieldValueString DropDownList1.SelectedValue = FieldValueString; } } } // This is one of those needed things I think it allows // access to the actual control through Controls property public override Control DataControl { get { return DropDownList1; } } }
Listing 7 – Finished Enumeration_Edit.ascx.cs
Now we need an Enumeration.ascx file for this FieldTemplate all we need is to create a copy of the Text.ascx FieldTemplate control.
<%@ Control
Listing 8 – Enumeration.ascx
using System.Web.UI; public partial class EnumerationField : System.Web.DynamicData.FieldTemplateUserControl { public override Control DataControl { get { return Literal1; } } }Listing 9 – Enumeration.ascx.cs
This blatant copy if the Text.ascx FieldTemplate is due to the fact that our enumeration types don’t have a direct conversion to text and so don’t automatically drop through to the Text.ascx FieldTemplate.
Now we can edit and view our data.
26 comments:
Great Post... Would this work the same way with Entity Framework ?
I don't see why not i've not done anything that is excluded by the EF
Steve
Would you please post a ZIP of the project thanks
Once again, Stephen pulls through! Your blog on all things Dynamic Data has saved me countless hours of pulling my hair out! THANK YOU!
A few things:
Even when changing the database field "Type" to a type of Animal, the properties in the code-behind still remain as Integers, at least when using VB.NET. So I had to find:
private _Type As Integer
and change to:
private _Type As Animal
and correct the properties as necessary (VB.NET doesn't have the nice generic { get; set; } functionality)
Even so, the dropdown I get has only the enumeration name, not the value. I.E.
<option value="Budgie">Budgie</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
I'm not sure, but I think because the value isn't an integer, it is blowing up for me when I try to update it. Should that be the case, or when it saves is it magically getting the value for the enum and saving it?
The error I get is:
"Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Row not found or changed."
What am I doing wrong?
~I'm really sorry but VB.Net makes my head ache, I have had no problems with this setting the type in the Designer.
Steve :D
Please....
Anyone know how to create a new field template for EntityModel??? In LinqModel seens easy.... but in EntityModel? Is it possible? How? I create my field values, but i cant use it by puting uihint on property in design.cs class.
Hi Thiago, send me an e-mail and we can have a chat about your requirements and see what can be done.
Steve :D
Do you have a simple sample like above that you could share? I've been attempting to get this working for the last couple days. I keep getting this error:
Type provided must be an Enum.
Parameter name: enumType
I've set the Type of the column in question in the data model and followed the rest of your example. Looking at a sample that works, may help me out.
Thanks,
Kel
Hi Kel, I can provid the sample if you send me an e-mail to the e-mail address I have on this blog.
Steve :D
Hi
I've got the same error Type provided must be an Enum.
Parameter name: enumType
In Linq to SQL datacontext, i do the same as above with Gender and AnimalType and leave Server Data Type as Int not Null
Nam Vo.
Hi Nam, this will only work with Linq to SQL and you must have the Enum in the same namespace as the dbml or fully qualify it.
Steve
Hi Steve, thanks for the excellent Dynamic Data resources you are providing here - saved me so many headaches. I have just implemented this Enum FieldTemplate, which works great. I was wondering however how to implement something similar to an Enum but permits spaces i.e. the Animal example works ok, but if I was wanting to set the Status of an Order to 'Awaiting Processing' rather than 'AwaitingProcessing'?
HiGareth, try this:
// get a data bindable list of permissions for the DDL
var enumList = Enum.GetValues(enumType);
foreach (var enumItem in enumList)
{
listControl.Items.Add(new ListItem()
{
Text = enumItem.ToString().ToTitleFromPascal(),
Value = enumItem.ToString()
});
}
and here is the extension method ToTitleFromPascal:
public static String ToTitleFromPascal(this String s)
{
// remove name space
String s0 = Regex.Replace(s, "(.*\\.)(.*)", "$2");
// add space before Capital letter
String s1 = Regex.Replace(s0, "[A-Z]", " $&");
// replace '_' with space
String s2 = Regex.Replace(s1, "[_]", " ");
// replace double space with single space
String s3 = Regex.Replace(s2, " ", " ");
// remove and double capitals with inserted space
String s4 = Regex.Replace(s3, "(?[A-Z])\\s(?[A-Z])", "${before}${after}");
// remove and double capitals with inserted space
String sf = Regex.Replace(s4, "^\\s", "");
// force title case i.e. 'this is a title' becomes 'This Is A Title'
return sf.ToTitleCase();
}
public static String ToTitleCase(this String text)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
if (i > 0)
{
if (text.Substring(i - 1, 1) == " " ||
text.Substring(i - 1, 1) == "\t" ||
text.Substring(i - 1, 1) == "/")
sb.Append(text.Substring(i, 1).ToString().ToUpper());
else
sb.Append(text.Substring(i, 1).ToString().ToLower());
}
else
sb.Append(text.Substring(i, 1).ToString().ToUpper());
}
return sb.ToString();
}
public static String ToSentenceCase(this String text)
{
return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1).ToLower();
}
public static String GetDisplayFormat(this Type type)
{
string defaultFormat = "{0}";
if (type == typeof(DateTime) || type == typeof(Nullable))
{
defaultFormat = "{0:d}";
}
else if (type == typeof(decimal) || type == typeof(Nullable))
{
defaultFormat = "{0:c}";
}
return defaultFormat;
}
Hope this helps:
thanks for the post ... I tried it and it works great for inserting, but it ends up an error on editing and deleting. :-(
Please help.
Hi there I'll look into that as soon as I get a chance, I just got back of vacation and I have a major backlog to attend to :)
Steve
Hi Steve, i want to create RadioButtonList in FieldTemplate, can you tell me how to do that, data should be retrieved from Database not from Enum
Hi Giribabu, can you email me directly e-mail is at the top of the page.
Steve
Hi Steave, I had sent you an e-mail from my company e-mail id.
I want to know the Positives and Negatives of ASP.NET Web Forms with Dynamics.
After creating this sample i inserted values from backend and executed the sample its showing with 3coloumns from DB [ NAME, Gender & Age] when i try to edit that info then error is comming
Type provided must be an Enum.
Parameter name: enumType
even i checked the namespace everything is fine.
Created this sample in VS2008
YOU MENTIONED IN TITLE
"We’ll create a simple FieldTemplate that displays an enumeration as RadioButtonList."
i didn't found any RADIOBUTTONLIST control is used in the code.
Hi giribabu, this is an old sample in VS2010 and .Net 4 DD already has a way of doing Enum field templates this way is out of date.
Steve
Hi Steve,
i tried this in Entity Framework but doesn't seems to work. Do you know the work around fix for entity framework?
Thxu.
Hi Adi, you can't do it this way in EF, what version of DD are you running VS20008 & .Net 3.5 SP1 or VS2010 & .Net 4?
Steve
VB.NET has had the 'generic get set' properties for quite awhile.
It's termed the explicit property setting. If you declare the property in an interface, it has to be explicit. if you declare in the class, you type 'End Property' and than type 'Get' or 'Set' within the property declaration. You'll end up seeing something like this.
Private _Name as DataType
Property PropertyName As DataType
Get
return me._Name 'Private Variable
End Get
Set(value as DataType)
me._Name = value
End Set
End Property
Though, I took the liberty of including the Private variable declaration, return statement, and value assignment.
How to apply below two query in my DD using query extender
select regno, count(regno) as cnt INTO #TEMP1 from MainTable
group by regno having count(regno) >= 2
select * from MainTable where regno in (select regno from #TEMP1) order by regno
|
http://csharpbits.notaclue.net/2008/07/dynamic-data-and-field-templates-your.html?showComment=1255999590963
|
CC-MAIN-2019-35
|
refinedweb
| 2,075
| 58.69
|
Analyzing Data in Amazon Redshift with Pandas
Redshift is Amazon Web Services’ data warehousing solution. They’ve extended PostgreSQL to better suit large datasets used for analysis. When you hear about this kind of technology as a Python developer, it just makes sense to then unleash Pandas on it. So let’s have a look to see how we can analyze data in Redshift using a Pandas script!
Setting up Redshift
If you haven’t used Redshift before,:
connstr = 'redshift+psycopg2://<username>:<password>@<your cluster>.redshift.amazonaws.com:5439/<database name>'
Also note that Redshift by default listens on port 5439, rather than Postgres’ 5432.
After we’ve connected we can use Pandas’ standard way to load data from an SQL database:
import pandas as pd from sqlalchemy import create_engine engine = create_engine(connstr) with engine.connect() as conn, conn.begin(): df = pd.read_sql(""" select likesports as sports, liketheatre as theater, likeconcerts as concerts, likejazz as jazz, likeclassical as classical, likeopera as opera, likerock as rock, likevegas as vegas, likebroadway as broadway, likemusicals as musicals from users;""", conn)
The dataset holds users’ preferences as False, None, or True. Let’s interpret this as True being a ‘like’, None being ambivalent, and False being a dislike. To make a correlation possible, we should convert this into numeric values:
# Map dataframe to have 1 for 'True', 0 for null, and -1 for False def bool_to_numeric(x): if x: return 1 elif x is None: return 0 else: return -1 df = df.applymap(bool_to_numeric)
And now we’re ready to calculate the correlation matrix, and present it. To present it we’ll use Seaborn’s heatmap. We’ll also create a mask to only show the bottom half of the correlation matrix (the top half mirrors the bottom).
import seaborn as sns import matplotlib.pyplot as plt import numpy as np # Calculate correlations corr = df.corr() mask = np.zeros_like(corr) mask[np.triu_indices_from(mask)] = True sns.heatmap(corr, mask=mask, xticklabels=corr.columns.values, yticklabels=corr.columns.values) plt.xticks(rotation=45) plt.yticks(rotation=45) plt.tight_layout() plt.show()!
3 Responses to Analyzing Data in Amazon Redshift with Pandas
Adelle says:August 17, 2017
A bit too heavy for me but welcome to read it! Thanks!
Bruce says:June 16, 2019
Is there a method to retrieve the connection string created in the database tool window from within the Python code?
For example
mydbconnstr = ‘$intellijvars:database-definition-name’
Then use
engine = create_engine(mydbconnstr)
Alex Fedotov says:April 29, 2020
`sqlalchemy-redshift` breaks all the time (right now, for sqlalchemy 1.3.16 it is broken). This recipe is ‘slightly misleading’.
|
https://blog.jetbrains.com/pycharm/2017/08/analyzing-data-in-amazon-redshift-with-pandas/
|
CC-MAIN-2021-17
|
refinedweb
| 437
| 56.15
|
The Java Specialists' Newsletter
Issue 1942011-08-27
Category:
Concurrency
Java version: Sun Java 6
GitHub
Subscribe Free
RSS Feed
Welcome to the 194th issue of The Java(tm) Specialists' Newsletter. This coming Monday we
are running our first Java
Specialists Symposium here on Crete. 40 Java
experts and enthusiasts from all around the world from as far
afield as Canada are honouring our little island with their
presence. We will spend 4 intense days discussing Java with
the theme "Making Java Fun Again". Not just will we talk
Java, but we will walk the mountains and swim the seas. We
will try to record as much as possible of the discussions,
but nothing will replace coming down to Crete yourself.
This open spaces conference was first named the Java
Specialist Roundup. But since we are in Greece, John Kostaras
suggested "Symposium" would be a better name. As in previous
newsletters, a quick Greek lesson for the Philistines amongst
us: The word symposium is made up out of two words. "Sym"
comes from "syn" and means "together", as you will find in
"symphony", "symbiosis", etc. The word "posium" comes from
"poto", meaning drink. Thus the literal and historical
meaning is a drinking party for philosophers.
Crete produces so much food, that it is impossible to eat
and drink it all. Since the transport system does not work
well, we often have to simply throw our produce away. For
example, we planted water melons and even after harvesting
several tons, still had about 50 that we kept at home. Water
melon becomes delicious juice in a blender, pips and all.
You can even throw a bit of the rind in. Even en route to
our conference hotel, you will drive past fields with
hundreds of abandoned water melons.
Another excess is the village wine. It is an interesting
drink that takes some getting used to. It is more like dry
sherry than red wine. For the South Africans amongst our
readership, think Sedgwick's Old Brown. The locals have so
much that they simply cannot drink it all, so we are given an
abundant supply, far more than would be good for me. I have
about 30 liters that need to be finished next week at the
Symposium. My friends are harvesting in September and I will
probably be inundated with last year's stock!
This brought me to this idea. Instead of the classical
"eating philosophers" we will have "drinking philosophers".
And instead of forks, we have two cups, because around this
table you have to drink with both hands.
The lock for our "symposium" is the class Krasi, Greek for
"wine".
public class Krasi { }
Our first "Thinker" has a deadlock, because if everyone picks
up the right cup at the same time, then it forms a ring and
they cannot pick up the left cup. Thus they end up in a
state of limbo and the symposium deadlocks.
import java.util.concurrent.*;
public class Thinker implements Callable<String> {
private final int id;
private final Krasi left, right;
public Thinker(int id, Krasi left, Krasi right) {
this.id = id;
this.left = left;
this.right = right;
}
public String call() throws Exception {
for (int i = 0; i < 1000; i++) {
drink();
think();
}
return "Java is fun";
}
public void drink() {
synchronized (left) {
synchronized (right) {
System.out.printf("(%d) Drinking%n", id);
}
}
}
public void think() {
System.out.printf("(%d) Thinking%n", id);
}
}
It is fairly easy to prove that the system can deadlock. We
simply construct a bunch of Thinkers and make their locks
form a circle. In order to not cause an early escape of
"this" by starting threads in the constructor, we only start
the symposium once it has been constructed.
import java.util.concurrent.*;
public class Symposium {
private final Krasi[] cups;
private final Thinker[] thinkers;
public Symposium(int delegates) {
cups = new Krasi[delegates];
thinkers = new Thinker[delegates];
for (int i = 0; i < cups.length; i++) {
cups[i] = new Krasi();
}
for (int i = 0; i < delegates; i++) {
Krasi left = cups[i];
Krasi right = cups[(i + 1) % delegates];
thinkers[i] = new Thinker(i, left, right);
}
}
public void run() throws InterruptedException {
// do this after we created the symposium, so that we do not
// let the reference to the Symposium escape.
ExecutorService exec = Executors.newCachedThreadPool();
CompletionService<String> results =
new ExecutorCompletionService<String>(exec);
for (Thinker thinker : thinkers) {
results.submit(thinker);
}
System.out.println("Waiting for results");
for (int i = 0; i < thinkers.length; i++) {
try {
System.out.println(results.take().get());
} catch (ExecutionException e) {
e.getCause().printStackTrace();
}
}
exec.shutdown();
}
}
We can create a Symposium with 5 thinkers and very quickly
we will see that there is a deadlock.
public class JavaSpecialistsSymposium2011Crete {
public static void main(String[] args)
throws InterruptedException {
Symposium symposium = new Symposium(5);
symposium.run();
}
}
Here is some output we might see:
(0) Drinking
(0) Thinking
Waiting for results
(2) Drinking
(2) Thinking
(2) Drinking
(2) Thinking
The jstack program also verifies that we have a deadlock:
Found one Java-level deadlock:
=============================
"pool-1-thread-5":
waiting to lock monitor 10086e908 (object 7f319c300, a Krasi),
which is held by "pool-1-thread-1"
"pool-1-thread-1":
waiting to lock monitor 10080d360 (object 7f319c310, a Krasi),
which is held by "pool-1-thread-2"
"pool-1-thread-2":
waiting to lock monitor 10080d2b8 (object 7f319c320, a Krasi),
which is held by "pool-1-thread-3"
"pool-1-thread-3":
waiting to lock monitor 10086d408 (object 7f319c330, a Krasi),
which is held by "pool-1-thread-4"
"pool-1-thread-4":
waiting to lock monitor 10086d360 (object 7f319c340, a Krasi),
which is held by "pool-1-thread-5"
There are several ways of avoiding deadlocks. One is to
do lock ordering, where we guarantee to always synchronize
the same lock first. The last thinker would thus first lock
right and then left, whereas all the others would be the
other way round. Another approach is to use Java 5 locks
which have a tryLock() method. Effectively you could do
something like:
while (true) {
if (Thread.interrupted()) throw new InterruptedException();
if (left.tryLock()) {
try {
if (right.tryLock()) {
try {
System.out.printf("(%d) Drinking%n", id);
return;
} finally {
right.unlock();
}
}
} finally {
left.unlock();
}
}
if (timeoutExceeded()) throw new TimeoutException();
sleepRandomTime();
}
You have probably seen code like that before. However, did
you know that it is also possible to try to
synchronize?!
Unsafe allows us to manually lock and unlock monitors, with
the monitorEnter() and monitorExit() methods. We can also
"try to lock" with the tryMonitorEnter() method. Here is a
wrapper class that we can use to do the dirty work for us:
import sun.misc.*;
import java.lang.reflect.*;
public class MonitorUtils {
private static Unsafe unsafe = getUnsafe();
public static boolean trySynchronize(Object monitor) {
return unsafe.tryMonitorEnter(monitor);
}
public static void unsynchronize(Object monitor) {
unsafe.monitorExit(monitor);
}
private static Unsafe getUnsafe() {
try {
for (Field field : Unsafe.class.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) {
if (field.getType() == Unsafe.class) {
field.setAccessible(true);
return (Unsafe) field.get(null);
}
}
}
throw new IllegalStateException("Unsafe field not found");
} catch (Exception e) {
throw new IllegalStateException(
"Could not initialize unsafe", e);
}
}
}
We can now change our "drink()" method to
while (true) {
if (Thread.interrupted()) throw new InterruptedException();
if (MonitorUtils.trySynchronize(left)) {
try {
if (MonitorUtils.trySynchronize(right)) {
try {
System.out.printf("(%d) Drinking%n", id);
return;
} finally {
MonitorUtils.unsynchronize(right);
}
}
} finally {
MonitorUtils.unsynchronize(left);
}
}
if (timeoutExceeded()) throw new TimeoutException();
sleepRandomTime();
}
Why use this when we have Lock.tryLock()? You might want to
change code that is already implemented with monitor locking.
Instead of modifying everything to use Lock, you could get
the same functionality with this trySynchronize().
Even better is to avoid locking yourself by using thread-safe
classes. Sadly this is not always an option.
Kind regards from Crete
Heinz
We now have a Facebook
page for the Java Specialists. If you've enjoyed
reading this newsletter, please take a moment to "like" our
group.
Concurrency Articles
Related Java Course
|
http://www.javaspecialists.eu/archive/Issue194.html
|
CC-MAIN-2014-49
|
refinedweb
| 1,312
| 56.96
|
If you have ever tried to write a user control in Visual Studio.NET, you'll already know that the process is bittersweet. On one hand, writing the control itself is painless and Visual Studio 2005 has greatly improved the process of making controls work on multiple .NET platforms via design-time attributes and "asmmeta" assemblies. On the other hand, however, deploying controls and adding them to the Toolbox is a process rife with errors. It is definitely not a matter of adding a registry key (as I would have liked to see).
After getting a lot of e-mails from customers asking me how to add real-time GPS controls to their Toolbox, I decided that I needed to come up with some kind of utility to get the job done. Visual Studio 2005 does already have some mechanisms for installing user controls, such as ".vsi" files, but unfortunately this approach typically results in a "Package Load Failure" and does not have a guarantee to work on every VS2005 installation. Fortunately, Chetan Chudasama generously gave out source code in his blog which explains how to add or remove Toolbox controls using code and the "DTE" (Design-Time Environment) for Visual Studio. Thanks to his efforts, I was able to turn the code into a command-line utility which is well-suited for installers (which is usually when Toolbox controls are installed).
This article describes how to use the utility and integrate it into your own installers. You are welcome to redistribute this utility and I consider it freeware.
When the utility runs, the following window will appear. Since the utility must launch a hidden instance of Visual Studio 2005 (devenv.exe), this can be a time-consuming process. A progress bar helps to show that something is actually happening during Toolbox modifications:
I kept the window free from company logos and branding so it will look like your own utility. The command line must follow the following syntax:
Toolbox.exe [/silent] /installdesktop assembly toolbox_tab [...]
Toolbox.exe [/silent] /installpocketpc assembly toolbox_tab [...]
Toolbox.exe [/silent] /installcustom template assembly toolbox_tab [...]
Toolbox.exe [/silent] /uninstall toolbox_tab [...]
/silent Suppresses all output during installation or uninstallation.
/installdesktop Installs controls written for Desktop Framework 2.0 to the toolbox.
/installpocketpc Installs controls written for Compact Framework 2.0 to the toolbox.
/installcustom Installs controls written for a specific kind of device project to the toolbox.
/uninstall Removes an entire Toolbox tab.
[...] Multiple install commands can be appended to install/uninstall multiple controls at one time.
"assembly" is the absolute path to an assembly containing user controls.
"toolbox_tab" is the name of the Toolbox Tab where control should be installed.
"template" is the name of a ZIP file from the Templates folder indicating a specific kind of project.
/installdesktop
Toolbox.exe /installdesktop "C:\MyUserControl.dll" "My Toolbox Tab Name"
/installpocketpc
Toolbox.exe /installpocketpc "C:\MyUserControl.PocketPC.dll" "My Toolbox Tab Name (PocketPC)"
... if you provide the same user controls for multiple platforms, you should add "(PocketPC)" to the Toolbox tab name to keep the controls separated.
/installcustom
\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\CSharp\
... you don't need the name of the directory since Visual Studio 2005 keeps all of the ZIP file names unique. The following example installs controls for Smartphone:
Toolbox.exe /installcustom "Smartphone2003-WindowsApplication.zip"
"C:\MyUserControl.Smartphone.dll" "My Toolbox Tab Name (Smartphone)"
Toolbox.exe /uninstall "My Toolbox Tab"
/uninstall
Toolbox.exe /uninstall "My Toolbox Tab" /installdesktop "C:\MyUserControl.dll" "My Toolbox Tab"
/silent
Toolbox.exe /silent /uninstall "My Toolbox Tab" /uninstall "Another Toolbox Tab"
AssemblyFolders
If you find any bugs or wish to see improvements, you can post in the thread on my web site for this utility, located here: Toolbox Utility Forum.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
[ToolboxBitmap(typeof(MyControl), "image.bmp")]
public class MyControl : UserControl
{
...
}
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
http://www.codeproject.com/Articles/13949/Visual-Studio-2005-Toolbox-Utility?fid=298625&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None&fr=11
|
CC-MAIN-2015-35
|
refinedweb
| 681
| 50.23
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.