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
Casc. Tutorial Details - Program: Apache, PHP - Version: n/a - Difficulty: Intermediate - Estimated Completion Time: 20 minutes Introduction Using CSS to power up a website is a requisite in the contemporary web for non-Flash websites - and for good reason. CSS is powerful. It can make or break a website (although usually IE6 is doing the breaking). Even with its usefulness, designers and developers alike have have wished for more out of the language since its inception over twelve years ago with the CSS Level 1 Recommendation. Today, we're going to review some ways to Supercharge Your CSS With PHP Under The Hood. Note: I am not going to be arguing for or against the concept of CSS Variable and/or CSS Constants. This article is written with the assumption that you will make an informed decision regarding these once presented with what it can do. This article teaches how to set them up and use them, but does not address the controversy in full. Setting Things Up Before the supercharging begins, we have to ensure that you have the proper requirements for doing so. We are going to go over two methods of making your CSS work with PHP, one that is short and sweet, and one that is a bit more elegant and less noticeable to the user. Both of these have the same basic requirement of a server running PHP. The more elegant version requires a bit more: - Apache (running PHP, obviously) - An editable .htaccess file Setting Up the Simple Method Web browsers are not that picky about file extensions when dealing with the HTML link tag. What they are picky about is the header data that it receives for that file. What that means is that you can link a *.php file with the proper header data in the place of a *.css file, and the browser will interpret the result just like standard CSS. To do so, add the PHP header that tells Apache to output the file as CSS: <?php header("Content-type: text/css; charset: UTF-8"); ?> Then, just link to the PHP file like you normally would: <link rel="stylesheet" href="css/supercharged.php" media="screen"> Now that you have done this, you can--in theory--skip to the next section of the tutorial dealing with CSS variables and constants, if you would like; however, anyone who views your source is going to see that you have a PHP file where a CSS file should be. Additionally, just because the browser will interpret the result properly does not mean that it will necessarily do other things like caching the file in the browser. To fix this, we move on to the slightly more elegant version. Setting Up the Elegant Method Apache comes with a large number of .htaccess tricks. This is one of them. We are going to tell Apache to interpret all CSS files in a certain folder as PHP files, and the web browser (and your users) will, generally speaking, not know that you are doing so. First thing to do is to put the header data in your CSS file, just like the Simple Method: <?php header("Content-type: text/css; charset: UTF-8"); ?> Then, instead of saving the CSS file as a *.php file, you save it as a *.css file, and you place it in a folder for CSS (in our example, ~/css/). Once you have done this, create a *.htaccess file in that folder and add the following: AddHandler application/x-httpd-php .css This snippet tells Apache to interpret all CSS files in the folder with the *.htaccess file with the PHP script handler. If you do not have the ability to add this to a single folder or if you need this to be serverwide, you can also add this to the httpd.conf server configuration file for Apache. To do so, you would want to add the previous snippet right below the group of AddType and AddHandler declarations (like these from one of my servers): AddType application/x-httpd-php .php .php3 .php4 .php5 AddType application/x-httpd-php-source .phps AddHandler cgi-script .cgi .pl Just remember that if you do add this to your httpd.conf server configuration file that EVERY *.css file on the server now must have the PHP header for text/css prepended to it. This is why my recommendation is to add it via .htaccess Start the Engine with CSS Variables From the Average Top 100 Weblog Performance Survey:. That is a lot of CSS. Why is this? A lot of times it is because the CSS is being delivered uncompressed and not optimized. The more likely suspect is CSS bloat and poorly maintained code. One popular option to improving code maintainability is to implement CSS Variables through PHP. What this means is that instead of having CSS like this (yes, this would produce an aberration of design, but it's good at illustrating the point): body { color: #000; background: #fff; font-size: 10px; } div#content { background: #ccc; font-size: 1.1em; } div#sidebar { color: #fff; background: #000; font-size: 1.0em; } div#footer { color: #555; background: #ccc; } You could have CSS like this: <?php $primaryTextColor = '#000'; $secondaryTextColor = '#fff'; $tertiaryTextColor = '#555'; $primaryBGColor = '#fff'; $secondaryBGColor = '#ccc'; $tertiaryBGColor = '#000'; $primaryTextSize = '10'; //pixels ?> body { color: <?=$primaryTextColor?>; background: <?=$primaryBGColor?>; font-size: <?=$primaryTextSize?>px; } div#content { background: <?=$secondaryBGColor?>; font-size: <? echo 1.1*$primaryTextSize ?>px; } div#sidebar { color: <?=$secondaryTextColor?>; background: <?=$tertiaryBGColor?>; font-size: <?=$primaryTextSize;?>px; } div#footer { color: <?=$tertiaryTextColor?>; background: <?=$secondaryBGColor?>; } Note that the long variable names is for illustration purposes only. Obviously, these variables can be as long as or as short as you like, and shorter variables make for smaller file sizes. In the example above, we have used basic variables to set up a monochrome color scheme that could then be used throughout the website in other styles. These variables could easily have been interchanged with $color01, $color02, $color03, etc to produce similar effects. Often, designers and front-end web developers get asked by clients "Hey, can you make all of the text a little darker?" or "Can you make all of the text just a little bigger?" While using variables like this will not always be the best solution, it often would reduce the maintenance time when using many templating systems and blogging platforms (WordPress, Moveable Type, Expression Engine, etc) or corporate CMSes (Drupal, Joomla, Bitrix, etc). An alternative method of storing the variables is to store the data in associate arrays (which is my preferred method), which produces code more like the following: <?php $defaultCSS = array( 'color01' => '#000', 'color02' => '#fff', 'color03' => '#ccc', 'color04' => '#555', 'baseTextSize' => '10' ); ?> body { color: <?=$defaultCSS['color01']?>; background: <?=$defaultCSS['color02']?>; font-size: <?=$defaultCSS['baseTextSize']?>px; } div#content { background: <?=$defaultCSS['color03']?>; font-size: <? echo 1.1*$defaultCSS['baseTextSize']; ?>px; } div#sidebar { color: <?=$defaultCSS['color02']?>; background: <?=$defaultCSS['color01']?>; font-size: <?=$defaultCSS['baseTextSize'];?>px; } div#footer { color: <?=$defaultCSS['color04']?>; background: <?=$defaultCSS['color03']?>; } Calculations in CSS Once you have set things up for using PHP with your CSS, you can then do some neat things like calculations. Let's assume that you want to set up a system in you provide a bunch of DIVs on screen, each with a different type of element inside. Each element type (i.e. img, p, blockquote, etc) has a unique height and width controlled via CSS, and you want the amount of margin to be based off these values like so: In this scenario, you want to set up a standardized grid that contains three different types of elements (img, p, and blockquote) encapsulated in two different containers (div and li). Every DIV has to be 550px wide and 250px tall, every LI has to be 600px wide and 300px tall, and each of the element types has a different height and width. The positioning of the elements on the inside must be dead center. Over time, the heights and widths of the different DIVs/LIs and elements will likely need to be changed. You could manual enter the amount of margin for each of the different elements and/or use extra class information on the container DIVs to add the appropriate amount of padding, but this is not that useful for quick changes, like those wanted by someone who is prototyping in the browser or who has 200 of these different elements for which they would have to modify data. Step 1 - The Structure First, we set up the XHTML content that we are going to style like so: <div><p>Lorem ipsum dolor sit amet tellus.</p></div> <div><blockquote>Etiam quis nulla pretium et.</blockquote></div> <div><img src="images/inset.png" alt="Inset Image" /></div> <ul> <li><p>Lorem ipsum dolor sit amet tellus.</p></li> <li><blockquote>Etiam quis nulla pretium et.</blockquote></li> <li><img src="images/inset.png" alt="Inset Image" /></li> </ul> Step 2 - The PHP Header and Variable Declarations Next, we set up the PHP/CSS file that we are going to use to style the XHTML. This is where we declare the standard sizes of the different elements for use throughout the page. <?php header("Content-type: text/css; charset: UTF-8"); $divData = array( 'width' => '550', 'height' => '250', ); $liData = array( 'width' => '600', 'height' => '300', ); $blockquoteData = array( 'width' => '440', 'height' => '100' ); $imgData = array( 'width' => '450', 'height' => '150' ); $pData = array( 'width' => '480', 'height' => '130' ); ?> Step 3 - The CSS with Variables and PHP Calculations Next, we continue the PHP file from Step 2 and utilize the variables that we set in calculations. Additionally, we set the calculated MarginX and MarginY values of the different elements to reduce the number of calculations necessary. div { width: <?=$divData['width']?>px; height: <?=$divData['height']?>px; } li { width: <?=$liData['width']?>px; height: <?=$liData['height']?>px; } div blockquote { width: <?=$blockquoteData['width']?>px; height: <?=$blockquoteData['height']?>px; <? $blockquoteData['divMarginX'] = $divData['width']-$blockquoteData['width']; $blockquoteData['divMarginY'] = $divData['height']-$blockquoteData['height']; ?> margin: <? echo blockquoteData['divMarginY']/2; ?>px <? echo blockquoteData['divMarginX']/2; ?>px; } div img { width: <?=$imgData['width']?>px; height: <?=$imgData['height']?>px; <? $imgData['divMarginX'] = $divData['width']-$imgData['width']; $imgData['divMarginY'] = $divData['height']-$imgData['height']; ?> margin: <? echo imgData['divMarginY']/2; ?>px <? echo imgData['divMarginX']/2; ?>px; } div p { width: <?=$pData['width']?>px; height: <?=$pData['height']?>px; <? $pData['divMarginX'] = $divData['width']-$pData['width']; $pData['divMarginY'] = $divData['height']-$pData['height']; ?> margin: <? echo pData['divMarginY']/2; ?>px <? echo pData['divMarginX']/2; ?>px; } li blockquote { width: <?=$blockquoteData['width']?>px; height: <?=$blockquoteData['height']?>px; <? $blockquoteData['liMarginX'] = $liData['width']-$blockquoteData['width']; $blockquoteData['liMarginY'] = $liData['height']-$blockquoteData['height']; ?> margin: <? echo blockquoteData['liMarginY']/2; ?>px <? echo blockquoteData['liMarginX']/2; ?>px; } li img { width: <?=$imgData['width']?>px; height: <?=$imgData['height']?>px; <? $imgData['liMarginX'] = $liData['width']-$imgData['width']; $imgData['liMarginY'] = $liData['height']-$imgData['height']; ?> margin: <? echo imgData['liMarginY']/2; ?>px <? echo imgData['liMarginX']/2; ?>px; } li p { width: <?=$pData['width']?>px; height: <?=$pData['height']?>px; <? $pData['liMarginX'] = $liData['width']-$pData['width']; $pData['liMarginY'] = $liData['height']-$pData['height']; ?> margin: <? echo pData['liMarginY']/2; ?>px <? echo pData['liMarginX']/2; ?>px; } What this allows us to do now is to change the size of elements once at the top of the file and not recalculate 12 margin values (24 if the margin values were asymmetric). Understand that I am not suggesting this will be used in every one of your projects going forward, but this kind of technique has definite advantages over the standard "static" CSS method. Shrink that CSS As mentioned earlier, CSS can get pretty big. One thing that you can do to reduce CSS size is to automatically gzipping your CSS files. To do this, you have two options on how to do so: straight from Apache using mod_gzip / mod_deflate or use PHP's built-in compression methods, which we'll do here. Step One - Set Up The Gzipping Snippet Inside of our CSS file, we already have a snippet of PHP that sets up the header: <?php header("Content-type: text/css; charset: UTF-8"); ?> All we have to do now, is add a single line of code setting an output buffer to use ob_gzhandler before the header declaration like so: <?php ob_start("ob_gzhandler"); header("Content-type: text/css; charset: UTF-8"); ?> It should be noted that there are other ways of doing gzip compression and they all have their benefits and shortcomings. My preferred method is using mod_deflate as mentioned earlier, but not all designers and developers have that option. If($usingPHP==TRUE) { return 'Happiness'; } Adding programming logic to a style sheet language is nothing new. Many websites determine what stylesheets they use based on URL, login status, or even the date. Here's a simple example that can be applied easily to blogs and e-commerce sites (amongst others). Let's assume that you have a h1 tag that is replaced using the Phark image replacement method described by the following CSS: h1 { width: 300px; height: 80px; text-indent: -9999px; background: url(images/logo.png) no-repeat; } By adding a little PHP in the mix to determine the date when the CSS is loaded, you can then specify a different image for a holiday like Google often does with its Google Doodles (although they use a different technology solution to do so): <?php $month = date('m'); $day = date('d'); if($month=='12' && $day=='25') { $logoSrc = 'images/holidayLogo.png'; } else { $logoSrc = 'images/logo.png'; } ?> h1 { width: 300px; height: 80px; text-indent: -9999px; background: url(<?=$logoSrc?>) no-repeat; } This is just a super simple example. Your CSS is just waiting to be amped up by PHP. What you do with it can vary from person to person. One of my personal uses is to use it as a way of obscuring and embedding @font-face files using data URI strings and checking the referer requesting the file similar to parts of the technology that Typekit uses: <?php // This function grabs the file and converts it to a URI string function data_url($file, $mime) { $contents = file_get_contents($file); $base64 = base64_encode($contents); return ('data:' . $mime . ';base64,' . $base64); } $checkReferer = $_SERVER['HTTP_REFERER']; $checkMatch = preg_match('/yourdomain\.com/',$checkReferer); if($checkMatch) { ?> @font-face { font-family: FontName; src: local("FontName"), url(<?php echo data_url('FontFileName.otf','font/otf'); ?>) format("opentype"); } <?php } else { /* This @font-face asset is unavailable */ } ?> CSS Variable Controversy Using variables in CSS, no matter the pros and cons has been a controversial issue for years. Like I said at the beginning of this article, I am not going to argue for or against the concept of CSS Variables or CSS Constants. Some very respected designer and developers have argued against it, while others have argued for it. I hope, for the sake of a better web, that an effective CSS-only solution happens sooner than later. In the meantime, those of us who support CSS variables and constants can rely on our server-side languages while those who do not support them will simply continue on as normal. What Ideas Can You Come up With? I'm always on the lookout for new and innovative ways to supercharge my CSS with PHP. What are some of your favorite use-case scenarios for mixing CSS with PHP? - Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/articles/supercharge-your-css-with-php-under-the-hood--net-6409
CC-MAIN-2017-04
refinedweb
2,547
54.93
Example 2: Fragmentation¶ In this example, we are going to retrieve MS/MS data from an MGF file and compare it to identification info we read from a pepXML file. We are going to compare the MS/MS spectrum in the file with the theoretical spectrum of a peptide assigned to this spectrum by the search engine. The script source can be downloaded here. We will also need the example MGF file and the example pepXML file, but the script will download them for you. The MGF file has a single MS/MS spectrum in it. This spectrum is taken from the SwedCAD database of annotated MS/MS spectra. The pepXML file was obtained by running X!Tandem against the MGF file and converting the results to pepXML with the Tandem2XML tool from TPP. Let’s start with importing the modules. # This is written in Python 2 for simplicity # Can be done forward-compatible easily, though import matplotlib.pyplot as plt from pyteomics import mgf, pepxml, mass import os from urllib import urlretrieve import pylab Then we’ll download the files, if needed: for fname in ('mgf', 'pep.xml'): if not os.path.isfile('example.' + fname): urlretrieve('.' + fname, 'example.' + fname) Now it’s time to define the function that will give us m/z of theoretical fragments for a given sequence. We will use pyteomics.mass.fast_mass() to calculate the values. All we need to do is split the sequence at every bond and iterate over possible charges and ion types: def fragments(peptide, types=('b', 'y'), maxcharge=1): """ The function generates all possible m/z for fragments of types `types` and of charges from 1 to `maxharge`. """ for i in xrange(1, len(peptide)-1): for ion_type in types: for charge in xrange(1, maxcharge+1): if ion_type[0] in 'abc': yield mass.fast_mass( peptide[:i], ion_type=ion_type, charge=charge) else: yield mass.fast_mass( peptide[i:], ion_type=ion_type, charge=charge) So, the outer loop is over “fragmentation sites”, the next one is over ion types, then over charges, and lastly over two parts of the sequence (C- and N-terminal). All right, now it’s time to extract the info from the files. We are going to use the with statement syntax, which is not required, but recommended. with mgf.read('example.mgf') as spectra, pepxml.read('example.pep.xml') as psms: spectrum = next(spectra) psm = next(psms) Now prepare the figure... pylab.figure() pylab.title('Theoretical and experimental spectra for ' + psm['search_hit'][0]['peptide']) pylab.xlabel('m/z, Th') pylab.ylabel('Intensity, rel. units') ... plot the real spectrum: pylab.bar(spectrum['m/z array'], spectrum['intensity array'], width=0.1, linewidth=2, edgecolor='black') ... calculate and plot the theoretical spectrum, and show everything: theor_spectrum = list(fragments(psm['search_hit'][0]['peptide'], maxcharge=psm['assumed_charge'])) pylab.bar(theor_spectrum, [spectrum['intensity array'].max()]*len(theor_spectrum), width=0.1, edgecolor='red', alpha=0.7) pylab.show() You will see something like this. That’s it, as you can see, the most intensive peaks in the spectrum are indeed matched by the theoretical spectrum.
http://pythonhosted.org/pyteomics/examples/example_msms.html
CC-MAIN-2013-48
refinedweb
511
58.38
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo Hi, I am trying to solve a nonlinear PDE with libMesh. I have installed libmesh with petsc enabled and I have written a simple "hello world" program that links with the library mesh_dbg, which complies fine. However, at runtime I get the message: dyld: Symbol not found: _DM_CLASSID Referenced from: /usr/local/lib/libmesh_dbg.0.dylib Expected in: flat namespace in /usr/local/lib/libmesh_dbg.0.dylib Trace/BPT trap: 5 Does anyone know what this means? and/or how to fix this problem? Thanks! Andy View entire thread
http://sourceforge.net/p/libmesh/mailman/message/31007176/
CC-MAIN-2015-18
refinedweb
109
67.65
import "github.com/elves/elvish/pkg/eval/vals" Package vals contains basic facilities for manipulating values used in the Elvish runtime. aliased_types.go assoc.go bool.go concat.go conversion.go dissoc.go doc.go equal.go has_key.go hash.go index.go index_list.go index_string.go iterate.go iterate_keys.go kind.go len.go pipe.go reflect_wrappers.go repr.go repr_helpers.go string.go struct_map.go testutils.go NoPretty can be passed to Repr to suppress pretty-printing. EmptyList is an empty list. EmptyMap is an empty map. ErrConcatNotImplemented is a special error value used to signal that concatenation is not implemented. See Concat for how it is used. Assoc takes a container, a key and value, and returns a modified version of the container, in which the key associated with the value. It is implemented for the builtin type string, List and Map types, StructMap types, and types satisfying the Assocer interface. For other types, it returns an error. Bool converts a value to bool. It is implemented for nil, the builtin bool type, and types implementing the Booler interface. For all other values, it returns true. CanIterate returns whether the value can be iterated. If CanIterate(v) is true, calling Iterate(v, f) will not result in an error. Collect collects all elements of an iterable value into a slice. Concat concatenates two values. If both operands are strings, it returns lhs + rhs, nil. If the left operand implements Concatter, it calls lhs.Concat(rhs). If lhs doesn't implement the interface or returned ErrConcatNotImplemented, it then calls rhs.RConcat(lhs). If all attempts fail, it returns nil and an error. Dissoc takes a container and a key, and returns a modified version of the container, with the given key dissociated with any value. It is implemented for the Map type and types satisfying the Dissocer interface. For other types, it returns nil. Eq returns a tt.Matcher that matches using the Equal function. Equal returns whether two values are equal. It is implemented for the builtin types bool and string, the File, List, Map types, StructMap types, and types satisfying the Equaler interface. For other types, it uses reflect.DeepEqual to compare the two values. FromGo converts a Go value to an Elvish value. Conversion happens when the argument is int, float64 or rune (this is consistent with ScanToGo). In other cases, this function just returns the argument. HasKey returns whether a container has a key. It is implemented for the Map type, StructMap types, and types satisfying the HasKeyer interface. It falls back to iterating keys using IterateKeys, and if that fails, it falls back to calling Len and checking if key is a valid numeric or slice index. Otherwise it returns false. Hash returns the 32-bit hash of a value. It is implemented for the builtin types bool and string, the File, List, Map types, StructMap types, and types satisfying the Hasher interface. For other values, it returns 0 (which is OK in terms of correctness). Index indexes a value with the given key. It is implemented for the builtin type string, the List type, StructMap types, and types satisfying the ErrIndexer or Indexer interface (the Map type satisfies Indexer). For other types, it returns a nil value and a non-nil error. Iterate iterates the supplied value, and calls the supplied function in each of its elements. The function can return false to break the iteration. It is implemented for the builtin type string, the List type, and types satisfying the Iterator interface. For these types, it always returns a nil error. For other types, it doesn't do anything and returns an error. IterateKeys iterates the keys of the supplied value, calling the supplied function for each key. The function can return false to break the iteration. It is implemented for the Map type, StructMap types, and types satisfying the IterateKeyser interface. For these types, it always returns a nil error. For other types, it doesn't do anything and returns an error. Kind returns the "kind" of the value, a concept similar to type but not yet very well defined. It is implemented for the builtin nil, bool and string, the File, List, Map types, StructMap types, and types satisfying the Kinder interface. For other types, it returns the Go type name of the argument preceded by "!!". Len returns the length of the value, or -1 if the value does not have a well-defined length. It is implemented for the builtin type string, StructMap types, and types satisfying the Lener interface. For other types, it returns -1. MakeList creates a new List from values. MakeMap creates a map from arguments that are alternately keys and values. It panics if the number of arguments is odd. NoSuchKey returns an error indicating that a key is not found in a map-like value. Repr returns the representation for a value, a string that is preferably (but not necessarily) an Elvish expression that evaluates to the argument. If indent >= 0, the representation is pretty-printed. It is implemented for the builtin types nil, bool and string, the File, List and Map types, StructMap types, and types satisfying the Reprer interface. For other types, it uses fmt.Sprint with the format "<unknown %v>". ScanToGo converts an Elvish value to a Go value. the pointer points to. It uses the type of the pointer to determine the destination type, and puts the converted value in the location the pointer points to. Conversion only happens when the destination type is int, float64 or rune; in other cases, this function just checks that the source value is already assignable to the destination. ToString converts a Value to string. It is implemented for the builtin float64 and string types, and type satisfying the Stringer interface. It falls back to Repr(v, NoPretty). TypeOf is like reflect.TypeOf, except that when given an argument of nil, it does not return nil, but the Type for the empty interface. ValueOf is like reflect.ValueOf, except that when given an argument of nil, it does not return a zero Value, but the Value for the zero value of the empty interface. type Assocer interface { // Assoc returns a slightly modified version of the receiver with key k // associated with value v. Assoc(k, v interface{}) (interface{}, error) } Assocer wraps the Assoc method. Booler wraps the Bool method. type Concatter interface { // Concat concatenates the receiver with another value, the receiver being // the left operand. If concatenation is not supported for the given value, // the method can return the special error type ErrCatNotImplemented. Concat(v interface{}) (interface{}, error) } Concatter wraps the Concat method. See Concat for how it is used. type Dissocer interface { // Dissoc returns a slightly modified version of the receiver with key k // dissociated with any value. Dissoc(k interface{}) interface{} } Dissocer wraps the Dissoc method. type Equaler interface { // Equal compares the receiver to another value. Two equal values must have // the same hash code. Equal(other interface{}) bool } Equaler wraps the Equal method. type ErrIndexer interface { // Index retrieves one value from the receiver at the specified index. Index(k interface{}) (interface{}, error) } ErrIndexer wraps the Index method. File is an alias for *os.File. type HasKeyer interface { // HasKey returns whether the receiver has the given argument as a valid // key. HasKey(interface{}) bool } HasKeyer wraps the HasKey method. Hasher wraps the Hash method. type Indexer interface { // Index retrieves the value corresponding to the specified key in the // container. It returns the value (if any), and whether it actually exists. Index(k interface{}) (v interface{}, ok bool) } Indexer wraps the Index method. type Iterator interface { // Iterate calls the passed function with each value within the receiver. // The iteration is aborted if the function returns false. Iterate(func(v interface{}) bool) } Iterator wraps the Iterate method. type KeysIterator interface { // IterateKeys calls the passed function with each key within the receiver. // The iteration is aborted if the function returns false. IterateKeys(func(v interface{}) bool) } KeysIterator wraps the IterateKeys method. Kinder wraps the Kind method. Lener wraps the Len method. List is an alias for the underlying type used for lists in Elvish. ListIndex represents a (converted) list index. ConvertListIndex parses a list index, check whether it is valid, and returns the converted structure. ListReprBuilder helps to build Repr of list-like Values. func NewListReprBuilder(indent int) *ListReprBuilder NewListReprBuilder makes a new ListReprBuilder. func (b *ListReprBuilder) String() string String returns the representation that has been built. After it is called, the ListReprBuilder may no longer be used. func (b *ListReprBuilder) WriteElem(v string) WriteElem writes a new element. Map is an alias for the underlying type used for maps in Elvish. MapReprBuilder helps building the Repr of a Map. It is also useful for implementing other Map-like values. The zero value of a MapReprBuilder is ready to use. func NewMapReprBuilder(indent int) *MapReprBuilder NewMapReprBuilder makes a new MapReprBuilder. func (b *MapReprBuilder) String() string String returns the representation that has been built. After it is called, the MapReprBuilder should no longer be used. func (b *MapReprBuilder) WritePair(k string, indent int, v string) WritePair writes a new pair. Pipe wraps a pair of pointers to os.File that are the two ends of the same pipe. NewPipe creates a new Pipe value. Equal compares based on the equality of the two consistuent files. Hash calculates the hash based on the two consituent files. Kind returns "pipe". Repr writes an opaque representation containing the FDs of the two constituent files. RConcatter wraps the RConcat method. See Concat for how it is used. type Reprer interface { // Repr returns a string that represents a Value. The string either be a // literal of that Value that is preferably deep-equal to it (like `[a b c]` // for a list), or a string enclosed in "<>" containing the kind and // identity of the Value(like `<fn 0xdeadcafe>`). // // If indent is at least 0, it should be pretty-printed with the current // indentation level of indent; the indent of the first line has already // been written and shall not be written in Repr. The returned string // should never contain a trailing newline. Repr(indent int) string } Reprer wraps the Repr method. Scanner is implemented by types that can scan an Elvish value into itself. Stringer wraps the String method. type StructMap interface { IsStructMap(StructMapMarker) } StructMap wraps the IsStructMap method, a marker to make some Elvish operations work on structs via reflection. The operations are Kind, Equal, Hash, Repr, Len, Index, Assoc, IterateKeys and HasKey. The marker method must be implemented on the value type of a struct (not the pointer, or any other type), otherwise operations on such values may panic. The struct may not contain cyclic data, and all the fields of the struct must be exported. Elvish reuses the `json:"name" annotations of the fields as the name of the Elvish fields in the Elvish operations. StructMapMarker is used in the marker method IsStructMap. ValueTester is a helper for testing properties of a value. func TestValue(t *testing.T, v interface{}) ValueTester TestValue returns a ValueTester. func (vt ValueTester) AllKeys(wantKeys ...interface{}) ValueTester AllKeys tests that the given keys match what the result of IterateKeys on the value. NOTE: This now checks equality using reflect.DeepEqual, since all the builtin types have string keys. This can be changed in future to use Equal is the need arises. func (vt ValueTester) Assoc(key, val, wantNew interface{}) ValueTester Assoc tests that Assoc'ing the value with the given key-value pair returns the wanted new value and no error. func (vt ValueTester) AssocError(key, val interface{}, wantErr error) ValueTester AssocError tests that Assoc'ing the value with the given key-value pair returns the given error. func (vt ValueTester) Equal(others ...interface{}) ValueTester Equal tests that the value is Equal to every of the given values. func (vt ValueTester) HasKey(keys ...interface{}) ValueTester HasKey tests that the value has each of the given keys. func (vt ValueTester) HasNoKey(keys ...interface{}) ValueTester HasNoKey tests that the value does not have any of the given keys. func (vt ValueTester) Hash(wantHash uint32) ValueTester Hash tests the Hash of the value. func (vt ValueTester) Index(key, wantVal interface{}) ValueTester Index tests that Index'ing the value with the given key returns the wanted value and no error. func (vt ValueTester) IndexError(key interface{}, wantErr error) ValueTester IndexError tests that Index'ing the value with the given key returns the given error. func (vt ValueTester) Kind(wantKind string) ValueTester Kind tests the Kind of the value. func (vt ValueTester) Len(wantLen int) ValueTester Len tests the Len of the value. func (vt ValueTester) NotEqual(others ...interface{}) ValueTester NotEqual tests that the value is not Equal to any of the given values. func (vt ValueTester) Repr(wantRepr string) ValueTester Repr tests the Repr of the value. Package vals imports 16 packages (graph) and is imported by 7 packages. Updated 2020-02-22. Refresh now. Tools for package owners.
https://godoc.org/github.com/elves/elvish/pkg/eval/vals
CC-MAIN-2020-16
refinedweb
2,163
67.65
You need to sign in to do that Don't have an account? Where are PartnerConnection and Connector classes I'm trying to build a simple java client program using the partner WSDL. I built stubs from the Partner WSDL file. I downloaded the WSC .jar file and added it to my build path. I'm still getting Connector cannot be resolved and PartnerConnection cannot be resolved. I would have thought they were in the Partner WSDL file but I don't see them there. Anyone know where I should go for those or why I don't have them in my project when I have the stubs from the partner WSDL and the force-wsc-44.0.0.jar? Anyone know where I should go for those or why I don't have them in my project when I have the stubs from the partner WSDL and the force-wsc-44.0.0.jar? import com.sforce.soap.partner.*; import com.sforce.soap.partner.sobject.*; import com.sforce.ws.*; import com.sforce.ws.ConnectorConfig; class SalesforceHelper { public SalesforceHelper () { ConnectorConfig config = new ConnectorConfig(); config.setUsername("username"); config.setPassword("password"); PartnerConnection connection = Connector.newConnection(config); } } I have the force-wsc-44.0.0.jar in my build path. But I did a "jar -tf" on that to see what is in it and it doesn't have those either. Are Connector and PartnerConnection supposed to come from the Partner WSDL? Or are they in a separate jar I'm supposed to get from somehwere?
https://developer.salesforce.com/forums/?id=9060G0000005oxsQAA
CC-MAIN-2021-21
refinedweb
253
66.44
C++ Inline Functions C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the. Following is an example, which makes use of inline function to return max of two numbers: #include <iostream> using namespace std; inline int Max(int x, int y) { return (x > y)? x : y; } // Main function for the program int main( ) { cout << "Max (20,10): " << Max(20,10) << endl; cout << "Max (0,200): " << Max(0,200) << endl; cout << "Max (100,1010): " << Max(100,1010) << endl; return 0; } When the above code is compiled and executed, it produces the following result: Max (20,10): 20 Max (0,200): 200 Max (100,1010): 1010
http://www.tutorialspoint.com/cplusplus/cpp_inline_functions.htm
CC-MAIN-2015-18
refinedweb
157
59.16
Results 1 to 2 of 2 - Join Date - Jul 2009 - Location - Odense, Denmark - 73 - Thanks - 4 - Thanked 0 Times in 0 Posts Flash builder and MySQL - string comparison Okay so I watched this tutorial on how to make a simple Android App using Adobe Flash Builder (4.5). It basically fires a php-script, sending post-vars, which then does some database checks, and if everything is alright, it echoes "1", else "0". The app is then supposed to do something depending on whether it echoes 1 or 0. Here's the output-bit of the php-file: PHP Code: if($output == $password) { echo "1"; } else { echo "0"; } ) Here's the important actionscript: Code: import com.adobe.crypto.MD5; import com.adobe.crypto.SHA1; import com.adobe.crypto.SHA256; protected function button1_clickHandler(event:MouseEvent):void { var l:URLLoader = new URLLoader(); var r:URLRequest = new URLRequest("path/to/file.php"); var vars:URLVariables = new URLVariables(); vars.username = username.text; vars.password = ********password********; r.method = URLRequestMethod.POST; r.data = vars; l.addEventListener(Event.COMPLETE, lComplete); l.addEventListener(IOErrorEvent.IO_ERROR, lError); l.load(r); } protected function lComplete(event:Event):void { if(event.target.data == '1'){ navigator.pushView(views.Main); } else { trace(event.target.data); } } protected function lError(event:IOErrorEvent):void { trace('url error'); } Now, when I run the program and give it the appropriate values, it won't do the navigator.pushView(views.Main); thing. It just traces " 1 " (with spaces). And I can't figure out why. Can somebody help me with this? //Deafdigit - Join Date - Jan 2012 - Location - Columbus, Ohio, U.S.A - 41 - Thanks - 0 - Thanked 8 Times in 8 Posts Hi there, I'm new on this forum but I'll see if I can't help you out with this. since it is tracing " 1 " just like that, it may be a parse error. The quotes from php could be throwing it off(try single quotes maybe?) Otherwise, you may be able to take the substring of it like this: var one:String = event.target.data.subString(2,3); //for a quick fix... I'd start with the quote thing though and work from there. I do apologize though if none of this helps. Regular expressions might work too, but I'm no good at that yet
http://www.codingforums.com/flash-and-actionscript/248418-flash-builder-mysql-string-comparison.html?s=db00a7deba4f26a4706ce8be8f130db7
CC-MAIN-2017-43
refinedweb
379
68.97
Guide To WordPress Coding Standards - By Daniel Pataki - July 19th, 2012 - 16 Comments Whenever we set code to screen, we must follow some sort of logic. You may well be the only person who understands that logic, but you still make the effort. The reason we follow standards and practices is to adhere to a common logic, so that we find each other’s code understandable and sensible. Today, we’ll delve into the gaping maw of knowledge that is the standards and practices of WordPress coding. By the end of this article, you should be familiar with the guidelines and the underlying approach. With some practice, you will be able to adhere to the rules and make educated guesses about the less regulated corners of the specifications. Further Reading on SmashingMag: Link - Manage Events Like A Pro With WordPress2 - Writing Effective Documentation For WordPress End Users3 - How To Create An Embeddable Content Plugin For WordPress4 - Do-It-Yourself Caching Methods With WordPress5 Code Formatting Link The PHP parser doesn’t care how you format your code, so why should you? In reality, the format of your code makes a huge difference in every way imaginable. Why Code Formatting Matters Linkstatements and other blocks of code. Not crowding the code together will make an “Error on line 267” message much easier to fix. PHP in WordPress Link Line breaks WordPress’ documentation says nothing in particular about line breaks, but adding a line break after most statements is common practice. Variable definitions, if blocks, array items and so on should be on separate lines. $my_value = 'Me'; $your_value = 'You'; $their_value = 'Them'; if ( $my_value == 'You' ) { echo 'It seems like you are mixed up with me'; } Indentation Indent code to show a logical structure. The goal here is readability, so any indentation that makes the code more readable is a good practice. Use tabs at the beginning of lines, and use spaces for mid-line indentation. $arguments = array( 'mythoughts' => array( 'guitars' => 'I love guitars', 'applepie' => 'Apple Pie is awesome' ), 'yourthoughts' => array( 'guitars' => 'Meh', 'applepie' => 'Love it!' ) ); if ( have_posts() ) { while ( have_posts() ) { get_template_part( 'template', 'blogpost' ); } }. $number = (integer) $_GET['number']; if ( $number === 4 ) { echo 'You asked for a four!'; } Quotes The main rule in the WordPress Codex is to use single quotes when you are not evaluating anything inside a string. If you need to use quotes inside a string, just alternate. Escaping quotes is allowed, of course, but you should rarely need to do so. $name = 'Daniel'; $hello = "My name is '$name'"; Braces The easiest method is to always use braces. The standards allow for the omission of braces for single-line if statements but only if there are no multi-line blocks in the same logical structure. Omitting braces is not allowed for single-line loops, though. I find this standard too convoluted — just always requiring braces would be much simpler. In addition, the standards dictate that an opening brace should be put on the same line as the initial statement, not on the line below (as specified in the PHP documentation). // The usual style if ( have_posts() ) { the_post(); the_content(); } else { echo 'Steal ALL the posts!'; } // Leaving out braces in this case is allowed. if ( ! has_post_thumbnail() ) echo 'This post does not have a featured image'; // But putting them in looks nicer and is more consistent. if ( has_post_thumbnail() ) { the_post_thumbnail(); } Formatting SQL queries SQL query keywords must be capitalized, and complex queries should be broken into multiple lines. One must know a lot about queries before using them, especially regarding their security; we’ll cover them further down. $simple_query = "SELECT * FROM $wpdb->posts WHERE comment_count > 3 LIMIT 0, 10"; $complex_query = " SELECT * FROM $wpdb->posts WHERE post_status = publish AND comment_count > 5 AND post_type = 'post' AND ID IN ( SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = 4 ) "; Naming conventions Never use CamelCase for names in WordPress code. Functions may contain only lowercase characters, separated by underscores if needed. Capitalize the first letter of each word in a class name, and separate words with underscores. File names should all be lowercase, with hyphens separating the parts of the name. If a file contains a single class, then name it after the class, prefixed by class-. Use string values for function arguments instead of booleans to make your code more obvious. $event = new My_Event(); $event->save_event_to_file( 'event-file.txt', 'noformatting' ); By far the most important rule is to make names self-explanatory. Remember that you are in a collaborative environment, and one of your goals is to help everyone understand what your code is doing. Comparison Statements One great practice, and not just for WordPress, is to always write a variable in a comparison on the right side. Thus, if you forget an equal sign, the parser will throw an error instead of evaluating to true. if ( 3 == $my_number ) { echo 'BINGO!'; } If you prefer to use ternary operators, the standards allow you to do so but advise that you always check for truth to make things clearer. One exception mentioned is when checking for nonempty variables, ! empty(). Overview The main takeaway from this section is to favor clarity and readability over brevity and cleverness. If you forget to follow some spacing rules or you are bent on inserting line breaks before opening braces, you’ll be fine as long as the code is easily understandable. Formatting HTML Link The WordPress Codex states that all HTML code must be validated using the W3C Validator6. Take care, because valid code isn’t necessarily good code, although there is a definite correlation. Doctype WordPress is based on the XHTML 1.0 specification, which the W3C recommended way back in 2000. A quick look at the Twenty Eleven theme shows that, despite the W3C’s recommendation, WordPress uses HTML5 for this default theme. There seems to be a conflict here, but in reality there is none. HTML5 includes a section on XML serialization, which effectively means that “XHTML5” can be used. Using quotes Quotes are mostly used when placing attributes and their values. You are free to use single or double quotes. Be consistent, though. While I prefer the look of double quotes (although I have no idea why), I use single quotes where possible in HTML. My reasoning is that because single quotes are required in PHP, I might as well follow suit in HTML. By following this methodology, I am able to see whether something “special” is going on in a line just by looking at the quotes. Closing tags The XHTML specification requires that you close all tags. Void (or self-closing) elements must be closed by adding a forward slash just before the last angled bracket. Take care because exactly one space must precede the forward slash, according to the official specification. Indentation The rules for indenting HTML match the rules for indenting PHP. Strive for a logical structure with your indentation. When mixing PHP and HTML, the blocks of PHP should be indented according to the normal flow of indentation. <div class='<?php post_class() ?>'> <h1><?php the_title() ?></h1> <?php if ( has_post_thumbnail() ) : ?> <strong>Featured Image</strong> <?php the_post_thumbnail() ?> <?php endif ?> </div> Formatting CSS Link7”. Indentation and structure Your CSS should follow this rough schema: CSSselector { property: value; property: value; } selector, selector, selector { property: value; property: value; } Write each selector on a separate line, even if you are listing multiple selectors for a ruleset. Also, each property-value pair should sit on its own line. Put the opening brace on the selector’s line, and put the closing brace on a separate line with the same indentation as the opening selector’s. Naming conventions - Use lowercase characters only. - Separate words within a selector with a hyphen. - Give your selectors human-readable names. Properties and values There are quite a few rules for writing properties and values. It can seem a bit over the top, but you get used to it very quickly, and it really does help everyone understand each other’s code. - Use shorthand versions of properties wherever possible, except when overwriting a previously defined property. - Use lowercase HEX code for colors wherever possible. If appropriate, use the shorter version. - Insert a space after the colon following a property. - Always use lowercase characters, except when an uppercase character is required, such as with font names and vendor-specific properties. - Organize CSS properties alphabetically, with the exception vendor-specific properties, which should always precede their general counterpart, and dimensional properties, which should be grouped together. If width and height are specified, write the width first. .button { background: #34c1ff; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; color: #fff; margin: 11px; position:relative; left:5px; top: 5px; width:120px; height:22px; } Commenting CSS supports only one type of commenting — block style; it does not have a separate notation for inline comments. Write short comments on one line, without a line break below. For comments that span multiple lines, insert a line break just after the opening syntax and a line break just before the closing syntax. /* Default link style /* a { color: #ff9900; } /* Some other quick link styles so that users can easily use whatever they need */ a.prominent {… If you use comments to delineate sections of the code, then use the following notation: a { background: #efefef; } */ Post Content Styling --------------------------------------------------- */ .post-content { padding: 22px; } Using CSS preprocessors Using CSS preprocessors such as SASS8 and Less9 makes our lives as developers a lot easier, but they are not without drawbacks. The code produced by these tools is usually valid but cannot be said to be very clean. A style sheet produced manually (and thoughtfully) will be much more readable than one produced automatically by Less. It depends on what you’re doing. If your product is commercial, then the ultimate goal is a good user experience, with valid and optimized code. In this case, use the output of the preprocessor as the main CSS, but include the original file for developers. While your CSS will not conform to WordPress’ standards, including the original file bridges the gap somewhat until WordPress takes an official position. Sacrificing CSS coding standards in order to simplify the development process (with the goal of a better user experience) is OK. Sacrificing the validity of code is not. Other languages There is no official documentation for dealing with other languages, but spotting a pattern here isn’t difficult. Aim for legible, well-structured and clear code. Look to the official documentation and community best practices for the given language. When WordPress takes a position, they will most likely do the same. General Development Guidelines Link Your WordPress product, whether a theme or plugin, must be coded in a certain way if you intend to publish it. In this chapter, we’ll look at some requirements of themes and plugins without which you wouldn’t be able to create a quality product. Information and Documentation Link Themes and plugins alike come with a bunch of information. A project usually contains four types of information: - Information about the theme or plugin itself; - Additional information that the author wants to share about the project or themselves; - Inline code documentation (the Codex has a guide for this10); - Separate documentation for end users. Using Hooks Link The backbone of WordPress development is the hooks API. This great method of programming not only allows for WordPress to be easily extended but ensures that developers don’t have to touch the core code. Using hooks as much as possible instead of writing custom code promotes modularity and simplicity, while decreasing code duplication. More often than not, achieving something in WordPress feels harder than it should be. Want to change the length of the excerpt? Look at the excerpt_more hook. Want to modify the content of the email that users get when they forget their password? Check out the retrieve_password_message hook. Whenever you’re working on something, do a quick Google search or scan Adam Brown’s hooks database11 for the relevant hook. If your product is fairly complex, try creating hooks of your own. These would enable others to easily extend your product, and you could use them yourself to make the product more modular. For an extensive overview, look at our “Complete Guide to WordPress Hooks12.” And in the section on plugins and themes further below, we’ll cover some more tips on particular hooks. Security Link It goes without saying that your product should take advantage of all of the security features of WordPress. This includes (but is not limited to) the following: - Use nonces to verify user identity and intent. - Escape and prepare SQL statements. - Sanitize and validate user input. - Use roles and capabilities to make sure users may do what they are doing. - Funnel AJAX requests to ajax-admin.php, and use hooks to handle these requests. To learn more about WordPress security in general, look at “Securing Your WordPress Website13.” To learn more about database security and about making your SQL queries airtight, give “Interacting With the WordPress Database14” a read. Privacy Link Always respect the privacy of your users. WordPress does not allow you to create extensions that “phone home.” If you do want to collect user information, then you must use an opt-in method whereby users are made aware of what is happening and explicitly give you permission. The guidelines don’t allow for any hotlinking of bundled resources. Any resource you use must be bundled with your product. API type calls are acceptable, though. Playing Nice With Others Link Too often do I see two plugins that are incompatible (i.e. completely unrelated in their function) or plugins that are incompatible with themes. While this is sometimes unavoidable, in many cases it can be chalked up to bad development. One way to maximize the compatibility of your product is to use as many WordPress defaults and options as possible. Don’t write your own pagination code; WordPress has perfectly good functionality available in paginate_links()15. Don’t use a separate or bleeding-edge version of jQuery when one is already available in WordPress by enqueueing it with wp_enqueue_script()16. Testing Link The robustness of your product is your responsibility. Your code should undergo rigorous testing by at least yourself (the more, the merrier, though). Many developers follow test-driven development (TDD), which aims to minimize the number of errors that pop up. Look at “Writing Unit Tests for WordPress Plugins17” for a detailed tutorial on how to start. Maintenance Link If you build something for the WordPress community, you should also maintain it. This does not have to tie you down for eight hours a day. If you feel that you don’t want to work on your project anymore, then try to hand it over to someone, or simply state that the product is no longer being maintained. As long as you don’t keep users in the dark, you should be fine. If you are actively working on it, then include changelogs and development information with the product. This will help users keep up with the changes, and it will be a good reference for you as well. Licensing Link The license you are required to use depends on the type of product you are developing. To submit your theme or plugin to the WordPress repository, you must use a GPL-compatible license18. This effectively means that your work must be free because all non-free licenses are automatically not GPL. Be sure to state the license clearly in your product. If your product is commercial, then you may use any software license you wish. If you are selling through a marketplace, then read its documentation to see what licenses it accepts. You may not, of course, use any resources that you do not own or do not have permission to use. If you are using a free resource under an attribution license, then you must include the attribution in your work. If you are looking for some GPL-compatable icon sets, the “Theme Review” document19 links to a fair number of them. Theme Development Best Practices Link There is a long list of rules, guidelines and best practices that you need to adhere to when developing a WordPress theme. Most of them are logical, and all serve a purpose. We’ll cover the most important bits below, and a complete list can be found in the “Theme Review” document20. You can evaluate your theme’s adherence to most of these rules with the Theme Check21 plugin. Errors and Functionality Link Your theme must pass five levels of rules and guidelines: - Your theme may not generate any PHP warnings, errors, notices or validation errors for HTML, CSS or JavaScript. - Your theme may not generate any WordPress-generated errors or notices. - All required WordPress features, functions and code elements must be built in, and your theme must support WordPress’ default implementation of these features. - If implemented, the recommended features must work according to the specification. - Optional functionality must work according to the specification. Included Features Link As mentioned, some features are required, some are recommended and some are optional. The current “Theme Review” document breaks them down as follows. Required features: - Automatic feed links - Widgets Recommended features: - Navigation menus - Post thumbnails - Custom header - Custom background - Custom visual editor style Optional features: - Internationalization Each feature above has one or more functions that your theme must contain. To view the complete list, see the relevant section in “Theme Review.”22 Hooks and Template Tags Link Whether required or not, any template tag or hook you use must be implemented properly. The following eight items are currently required for each and every theme you make: wp_head() body_class() $content_width post_class() wp_link_pages() paginate_comments_linkor previous_comments_link()and next_comments_link() posts_nav_link()or previous_posts_link()and next_posts_link()or paginate_link() wp_footer() In about 90% of the cases I’ve seen, a plugin won’t work with a theme because the theme is missing the wp_head() or wp_footer() hook. Including Files and Resources Link If a function exists to include a template file, then you are required to use that function, instead of including the file another way. The following templates may be called with the corresponding functions: - Call header.phpwith get_header() - Call footer.phpwith get_footer() - Call sidebar.phpwith get_sidebar() - Call - Call get_search_form() If you create additional templates for your theme, then you must call them using the get_template_part() or locate_template() functions (the latter is best used with child themes). When including styles and scripts, you must use wp_enqueue_style() and wp_enqueue_script(), instead of hard-coding them. The only exception is the theme’s style sheet, style.css, which may be added to the head of the document. WordPress-Defined CSS Classes Link Whenever a page, comment, post or almost any other element is generated, WordPress attaches classes to it so that it can be identified and manipulated. Your style sheet must support some of these classes. Alignment classes: .alignleft .alignright .aligncenter Caption classes: .wp-caption .wp-caption-text .gallery-caption Post classes: .sticky Comment classes: .bypostauthor If you do not intend to style them differently, then the .sticky and .bypostauthor classes may be left empty, but they must exist in the style sheet nonetheless. This list will probably fatten up over time to account for evolving requirements. Learning about all of the other classes that WordPress applies23 to various elements is a good idea. This will enable you to create flexible style sheets that you can reuse from project to project. Theme Files Link The number of files in your theme can vary greatly, depending on how complex the theme is. It could also operate perfectly with just a simple index.php file. The choice is yours. “Theme Review” offers the following guidelines. Required files: index.php screenshot.png style.css Recommended files: 404.php archive.php page.php search.php header.php footer.php sidebar.php Optional files: attachment.php author.php category.php date.php editor-style.php image.php tag.php Remember that you can also create any arbitrary file in your theme’s directory, as well as create your own templates. Give these files names that don’t clash with WordPress’ template hierarchy24. For example, don’t create a page-about.php file to include somewhere because, with the way templates are handled, if the user creates a page named “About,” then page-about.php will be used to display it. Theme Options Link Creating a theme options page is a great way to give users powerful options. WordPress requires that you plan and code this carefully, rather then copying and pasting from a tutorial. You’ll need to follow a number of specific requirements: - Always add a theme options page with the add_theme_page()function. - Always base permissions on the edit_theme_optionscapability, rather than on a role or something else. - Save all options in a single array; don’t save them as separate key-value pairs in the database. Theme Names Link Quite a few rules regulate how you may name a theme. This is understandable because we want to avoid sensationalism and keyword spam. Your theme’s name may not contain any of the following: - The word “WordPress”; - The word “theme,” or any related word such as “blog,” “template” or “skin”; - Version- or markup-related terms (HTML5, CSS3 and so on); - Credit to a contributor; - Any keyword spam. Theme Credits Link We all want to see our name written in huge bold text in the header of a website, but this (thankfully) is not how WordPress or the open-source community works. Credit may be given, of course. Here’s what you may do: - You may use the authorURI row in your style.cssfile to link to your personal or professional website. - You may use the themeURI row in your style.cssfile to link to a demonstration of the theme. - You may include one link in the theme’s footer. This must be either the author URI or the theme URI that you defined in the style.cssfile. - You may also have a more elaborate section or module for self-promotion, but this must be opt-in. - You may not forbid users from removing these links. - Above all else, you may not use any of these for spam or for self-promotion unrelated to the given product. Documentation Link There are different ways to handle this, but your theme must have some sort of documentation. The recommended method is to include a readme.txt file in your theme that covers all of the information that a user would need to know. It should be in the Markdown format25 that readme.txt files for plugins use. I also recommend creating more user-friendly documentation in the form of a website, PDF file or the like. I prefer self-contained documentation such as a PDF file because it will remain available to the user no matter what. For a great tutorial, read “How to Improve Your WordPress Plugin’s Readme.txt26.” The article applies to plugins, but the Markdown format and general idea are the same for themes. Plugin Development Best Practices Link WordPress plugins tend to be a bit more complex than themes — not always, of course, but because plugins need to supersede themes, a much broader breadth of knowledge is needed to build a 100% standards-compliant plugin. In addition, plugins span a wider range of themes and skills. From adding different types of avatars to implementing a full-blown event management system, the spectrum is pretty wide. Because of this, the standards and best practices for plugins are dispersed over many pages of the WordPress Codex and the websites of developers. A good place to start is “Plugin Resources5027,” where you will find information for the most common cases and a few uncommon ones. Plugin Naming Link Plugins may be named whatever you’d like, but obviously it should bear some relevance to what the plugin does. Try to choose a unique name (search the plugin repository beforehand). While not explicitly stated, the WordPress team would probably want you to follow the same rules for naming plugins as for naming themes (refer to the section on themes above). Plugin Files Link Your plugin requires at least a main file with a unique name (i.e. unique across the plugin repository), related to the plugin’s function. A readme.txt file is also required, formatted according to a specific set of rules28. Information About Your Plugin Link A bit of information about your plugin is needed. Without it, your plugin wouldn’t be detected in the administration section. While only the “Plugin Name” field needs to be filled in, filling in the other fields will make your plugin look nicer and more complete. /* Plugin Name: The Missing Task Manager Plugin URI: Description: A simple task manager for your WordPress website Version: 1.2 Author: Good Guy Greg Author URI: License: GPL2 */ Authors usually include an extra block in their plugin’s main file about the copyright. This is not required but is recommended for clarity’s sake. Using Hooks Link We’ve already looked briefly at hooks. Without them, your plugin would be pretty much useless. Use hooks properly and as much as possible, instead of hard-coding things. The rules for themes apply here as well, but need to be taken even more seriously with plugins. The whole purpose of plugins is to work in across themes and across installations; therefore, hard-coding is not acceptable. Also, find the right tag to hook into. Always look in the Codex to determine where to hook your functions. An incorrect hook can wreak havoc. Developers tend to overlook three hooks in particular that would allow them to add great functionality to their plugin. Here they are below. Activation hook Your plugin might need to perform a number of tasks when activated. You might need to add some options, create a database table or do something similar. An easy way to accomplish this is to use the register_activation_hook() function. Deactivation hook The register_deactivation_hook() hook is similar to the activation hook. It runs when a plugin is deactivated and allows you to do some clean-up before the plugin is deactivated. Uninstall hook When a plugin is uninstalled, the register_uninstall_hook() hook can be used to complete some tasks. You should do a thorough clean-up after your plugin has been uninstalled; don’t burden the user with unnecessary data. Stack Exchange has a great tutorial on creating a class that handles all three functions29. For more information about hooks, check out the previously mentioned “WordPress Essentials: The Definitive Guide to WordPress Hooks30” here on Smashing Magazine. Handling Data Link There are three methods of storing and retrieving data in a plugin: - Store website-specific data via the options mechanism; - Store post-specific data using the post meta mechanism (i.e. custom fields); - Store data not associated directly with the installation or with individual posts in a separate database table. The Options mechanism and Settings API The options mechanism is an easy way to store named pieces of data in the database. This can be used for website-wide options and other relatively static data. The Settings API31 was introduced in WordPress 2.7 and is basically an evolved version of the options mechanism. Because use of the Settings API will eventually be required, using it instead of the options mechanism is a good idea. Familiarize yourself with all of the options in the Settings API because it provides not only database-interaction wrappers, but also HTML-generating functions to help you automatically manage your settings fields. The post meta mechanism The post meta mechanism32 provides a convenient way to store data that pertains to a particular post. Its functionality is very similar to that of the options mechanism. It allows you to add, update, delete or get custom fields. Read the Codex for the nuances of usage, but mastering this one should be pretty easy. Creating new database tables This method is definitely suited to more elaborate plugins and more experienced developers. Adding tables and the functionality they usually support brings with it many new hurdles to jump. Make sure to secure the queries to this table just as you do with regular queries. Use the $wpdb class and the functions that it makes available. Refer to the general section on safety above for more information on database security. Internationalization Link Internationalization is not required but is a good idea if you want to add your plugin to the repository or to sell it. It enables users and developers to add translations to your plugin very easily. Preparing your plugin for internationalization takes some time if you’ve never done it before; it requires third-party tools and edits to the code to accommodate the translatable strings. Your best friend in this venture will be i18n for WordPress Developers33. Overview Link As you can see, the standards and practices for plugins are much vaguer than the ones for themes. Adapt any standards for themes to your plugin as appropriate. More concrete guidelines will be formulated eventually, so you might as well be prepared. Straying From The Standards Link In theory, you must follow these standards only if you want to submit your theme or plugin to the WordPress repository. In reality, though, you’re best off following these rules anyway. Any serious marketplace will force a lot of them down your throat anyway, and any serious WordPress developer will frown on code that isn’t standards-compliant. The most important reason to follow the standards is to ensure the health of your project. By following the guidelines laid down in the official documentation, you will ensure that your product is as future-proof as possible and that anyone else who comes onboard to help will understand it immediately. Bending the Rules Link In some scenarios, bending or breaking the rules is appropriate. Many developers who create commercial themes for large marketplaces, for example, include plugin functionality in their themes. This is a no-no according to the standards, but it makes sense from a business point of view. Enabling the user to get a great-looking customizable website, complete with e-commerce functionality and mailing-list integration, in one simple download (instead of having to download a theme and two different plugins) is a huge plus. If you’re planning to release a Web app, coding it from scratch might take a while, but you could put up a test version based on WordPress quite quickly. In this case, bending a few rules (such as the one about keeping plugins and themes distinct) is acceptable. Many great things have been created by bending the rules; the trick is knowing when to do so. If you have good reason and you document along the way, you should be safe. The key is communication: making sure other developers (and you, later on) understand the reasons for what you’ve done. Conclusion Link Admittedly, this has been a mouthful, so consider yourself awesome and have a slice of pie. If you’ve made it this far, then you know where to look for information on standards, and you understand the logic behind them. There is a lot more to know about WordPress development, so below is a bunch of links to help you on your path to enlightenment. As with any community-based project, being nice will get you a mile further than acting like a pompous know-it-all. Community members will value your efforts and help out for sure. Further Reading Link General guides: - “WordPress Coding Standards34,” WordPress Codex - “Inline Documentation35,” WordPress Codex - “Settings API Tutorial36,” Otto on WordPress - “A Guide to Nonces37,” Mark Jaquith - “Know Your Sources38,” WordPress CodexA lot of general development links here. - “Template Tags39,” WordPress Codex - “Function Reference40,” WordPress Codex - “Data Validation41,” WordPress Codex - “Database Description42,” WordPress Codex - “Creating Options Pages43,” WordPress Codex Theme-related guides: - “Theme Review44,” WordPress Codex - “Theme Unit Test45,” WordPress Codex - “WordPress Theme Development46,” WordPress Codex - “Template Hierarchy47,” WordPress Codex - “WordPress Generated CSS Classes48,” WordPress Codex Plugin-related guides - “Writing a Plugin49,” WordPress Codex - “Plugin Resources5027,” WordPress Codex - “Sample readme.txt File51,” WordPress - “Plugin Development Book52,” Vladimir Prevolac - “WordPress Hooks Reference53,” Adam Brown - “Plugin API54,” WordPress Codex - “Plugin Submission and Promotion55,” WordPress Codex - “AJAX in Plugins56,” WordPress Codex
https://www.smashingmagazine.com/2012/07/guide-wordpress-coding-standards/
CC-MAIN-2017-26
refinedweb
5,376
54.63
Python provides the datetime module in order to work with date and time information. This module provides a lot of different methods where one of them is getting the current time. In this tutorial, we will learn how to get the current time in Python. Get Current Time with datetime.now() Method The most popular method to get current time is using the now() method from the datetime module. First, we will import the datetime module and then call the now() method. It will return the time object which contains current time information. from datetime import datetime #Get current time now = datetime.now() #Print current time print("Current Time is: ",now) #Format current time print("Current Time is: ",now.strftime("%H:%M:%S")) The output will be like below where the first print will print complete date and time with year, month, day, hour, minute, second information. The second print will provide only the hour, minute and second information by using the strftime() method with the “%H:%M:%S” format. Current Time is: 2020-11-28 11:12:01.561611 Current Time is: 11:12:01 Get Current Time with time.localtime() Method Python also provides a separate module named time which also provides the localtime() method which will return the current localtime information as localtime object. import time #Get current time now = time.localtime() #Print current time print("Current Time is: ",now) #Format current time print("Current Time is: ",time.strftime("%H:%M:%S",now)) The output will be like below. The localtime() can be printed with print() method which will print the struct_time object and provides the time as parameters like below. The strftime() method can be called via the time module and the current time object now should be provided like time.strftime(“%H:%M:%S”,now) . Current Time is: time.struct_time(tm_year=2020, tm_mon=11, tm_mday=28, tm_hour=11, tm_min=16, tm_sec=57, tm_wday=5, tm_yday=333, tm_isdst=0) Current Time is: 11:16:57 Get Current Time For Specified TimeZone The pytz is a 3rd party Python module which uses the Olson tz or timezone data in order to return time for specified timezone. The current time can be returned with the pytz timezone method and using datetime.now() method by providin the timzone object as parameter. from datetime import datetime import pytz tz_istanbul = pytz.timezone("Europe/Istanbul") now = datetime.now(tz_istanbul) print("Istanbul Time:",now.strftime("%H:%M:%S")) Change Format of Current Time As we can see in previous examples the format of the current time can be changed by using the strftime() method. This method is provided with the datetime module or with the time object. Using the time object strftime() method is easier. The format should be provided as string like “%H:%M:%S”. from datetime import datetime #Get current time now = datetime.now() #Format current time print("Current Time is: ",now.strftime("%H:%M:%S")) print("Current Time is: ",now.strftime("%H:%M")) print("Current Time is: ",now.strftime("%H-%M-%S")) print("Current Time is: ",now.strftime("%H-%M")) The output will be like below. Current Time is: 11:32:16 Current Time is: 11:32 Current Time is: 11-32-16 Current Time is: 11-32
https://pythontect.com/get-current-time-in-python/
CC-MAIN-2022-21
refinedweb
538
67.45
Created on 2019-03-16 02:07 by Allie Fitter, last changed 2020-11-09 22:55 by BTaskaya. This issue is now closed. pygettext can't see gettext functions calls when they're inside of an fstring: foo.py from gettext import gettext as _ foo = f'{_("foo bar baz")}' Running `pygettext3.7 -kgt -d message -D -v -o locales/message.pot foo.py` results in: locale/message.pot # SOME DESCRIPTIVE TITLE. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2019-03-15 21:02" Change foo.py to: from gettext import gettext as _ foo = f'' + _("foo bar baz") + '' Results in: # SOME DESCRIPTIVE TITLE. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2019-03-15 21:05" #: foo.py:3 msgid "foo bar baz" msgstr "" Running on Ubuntu 18.04. Eric, I'm CC'ing you on this issue because I'm not sure if you've considered f-strings and gettext and figured out a way to make them work together. If you have, I can look into adding support for extracting the strings to pygettext but at the moment, I'm not sure if it's a style that we want to propogate or not. The heart of the problem is that the gettext function has to run before string interpolation occurs. With .format() and the other formatting methods in Python, this is achievable rather naturally. For instance: from gettext import gettext as _ first = "foo" last = "baz" foo = _("{first}, bar, and {last}").format(**globals()) will lead to the string first being gettext substituted like: "{first}, bar, y {last}" and then interpolated: "foo, bar, y baz" However, trying to do the same with f-strings translates more like this: foo = _(f"{first}, bar, and {last}") foo = _("{first}, bar, and {last}".format(**globals())) # This is the equivalent of the f-string So the interpolation happens first: "foo, bar, and baz" Then, when gettext substitution is tried, it won't be able to find the string it knows to look for ("{first}, bar, and {last}") so no translation will occur. Allie Fitter's code corrects this ordering problem but introduces other issues. Taking the sample string: foo = f'{_("{first}, bar, and {last}")} f-string interpolation runs first, but it sees that it has to invoke the _() function so the f-string machinery itself runs gettext: f'{"{first}, bar, y {last}"}' The machinery then simply returns that string so we end up with: '{first}, bar, y {last}' which is not quite right but can be fixed by nesting f-strings: foo = f'{_(f"{first}, bar, and {last}")} which results in: f'{f"{first}, bar, y {last}"} which results in: f'{"foo, bar, y baz"}' And finally: "foo, bar, y baz" So, that recipe works but is that what we want to tell people to do? It seems quite messy that we have to run the gettext function within the command and use nested f-strings so is there/should there be a different way to make this work? Thanks for adding me, Toshio. foo = f'{_(f"{first}, bar, and {last}")}' Wow, that's extremely creative. I agree that this isn't the best we can do. PEP 501 has some ideas, but it might be too general purpose and powerful for this. Let me think about the nested f-string above and see if I can't think of a better way. As an aside, this code: foo = _("{first}, bar, and {last}").format(**globals()) Is better written with format_map(): foo = _("{first}, bar, and {last}").format_map(globals()) It does not create a new dict like the ** version does. Just as context, my use case for this is interpolating translated strings into HTML. html = f'''\ <h1>{_("Some Title")}</h1> <p>{_("Some longer text")}</p> ''' I was going to say "use eval()", but maybe we need some sort of "eval_fstring()" that basically only understood f-strings and produced a callable that captured all of the variables (like a closure), maybe that would help. Of course, this wouldn't be any safer than eval'ing arbitrary user provided code. I've put some more thought in to this, and this is the best I can come up with, using today's Python. The basic idea is that you have a function _f(), which takes a normal (non-f) string. It does a lookup to find the translated string (again, a non-fstring), turns that into an f-string, then compiles it and returns the code object. Then the caller evals the returned code object to convert it to a string. The ugly part, of course, is the eval. You can't just say: _f("{val}") you have to say: eval(_f("{val}")) You can't reduce this to a single function call: the eval() has to take place right here. It is possible to play games with stack frames, but that doesn't always work (see PEP 498 for details, where it talks about locals() and globals(), which is part of the same problem). But I don't see much choice. Since a translated f-string can do anything (like f'{subprocess.run("script to rm all files")'), I'm not sure it's the eval that's the worst thing here. The translated text absolutely has to be trusted: that's the worst thing. Even an eval_fstring(), that only understood how to exec code objects that are f-strings, would still be exposed to arbitrary expressions and side effects in the translated strings. The advantage of compiling it and caching is that you get most of the performance advantages of f-strings, after the first time a string is used. The code generation still has to happen, though. It's just the parsing that's being saved. I can't say how significant that is. See the sample code in the attached file. New changeset bfc6b63102d37ccb58a71711e2342143cd9f4d86 by jack1142 in branch 'master': bpo-36310: Allow pygettext.py to detect calls to gettext in f-strings. (GH-19875)
https://bugs.python.org/issue36310
CC-MAIN-2021-43
refinedweb
1,023
71.14
* classloader sri jaisi Greenhorn Joined: Sep 02, 2006 Posts: 23 posted Oct 28, 2006 05:00:00 0 java myclass.java; whatz actually happening when we run a class;i knew that main method is the entry point for execution and classloader is responsible for loading the class when it sees some line like new myclass();but my question is even to get to the main method the class has to be already loaded; thankz sri Henry Wong author Sheriff Joined: Sep 28, 2004 Posts: 17943 37 I like... posted Oct 28, 2006 06:00:00 0 The main() method is the "entry point for execution" for your java program. The starting point for the JVM is something else. This starting point call code that parses the parameters, setups tons of internal stuff, loads and configure the class loader, load your class specified in the parameters (with the class loader), and then call your main() method. Henry Books: Java Threads, 3rd Edition , Jini in a Nutshell , and Java Gems (contributor) Cameron Wallace McKenzie author and cow tipper Saloon Keeper Joined: Aug 26, 2006 Posts: 4968 I like... posted Oct 28, 2006 08:05:00 0 Heh...Who cops the cops is what you're asking...Who loads the first classloader? I wrote a number of articles on classloaders. Here's a segment of one of them on the null classloader. I hope you enjoy. You can read the rest of the arcticle here if you please. It's a little WebSphere specific: Everything You Want to Know About WebSphere and J2EE Classloaders�s. sri jaisi Greenhorn Joined: Sep 02, 2006 Posts: 23 posted Oct 28, 2006 11:25:00 0 thankz henry and thankz kameron kameron i read your article and i still got some doubts and please can you explain them in little more detail let me start again with a simple example: java myclass.java;now null classloader instantiates system classloader (as classloaders are hierarchial and as they follow delegation module extension loader ,bootstrap loader will try to load myclass.class file when it come across the line new myclass()); am i correct here?(or else bootstrap loader loads java.* classes and extension loader loads javax.*,and system class loader is the one responsible to load user defined classes in my case i.e.myclass.class) 2.if iam having one public class and two are more non public classes within the same file and if iam instantiating them means eg;new a();new b();new c();then wil three insances of system class loader will be created and each instance will try to find the corresponding .class file; am i correct here thankz for reading sri Ernest Friedman-Hill author and iconoclast Marshal Joined: Jul 08, 2003 Posts: 24165 30 I like... posted Oct 28, 2006 12:32:00 0 Note that much of what K/Cameron is saying is implementation-dependent and undocumented -- not stuff you need to know. The important points are that the JVM itself starts up, and a specific class loader is created for the purpose of loading application classes. The Java application launcher (i.e., java.exe) then uses this class loader, along with the class name you specify on the command line and the Class.forName() function, to load the class in which main() is expected to appear. main() is then invoked using reflection (or equivalent magic.) There's just a single application class loader; Java won't create any more class loaders once it starts loading your application classes. [Jess in Action] [AskingGoodQuestions] I agree. Here's the link: subject: classloader Similar Threads Classloader issues classloader Programatically unloading a class ... Reading and loading sql queries from properties file class loader for loading singleton classes All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/381300/java/java/classloader
CC-MAIN-2014-10
refinedweb
641
60.95
02 October 2008 13:09 [Source: ICIS news] By Linda Naylor LONDON (ICIS news)--Polyethylene (PE) prices into Europe are falling sharply as sellers seek to find buyers for material in a lacklustre market and imported volumes become more freely available, sources said on Thursday. September low density PE (LDPE) fell €80-100/tonne, leaving gross prices at €1,480/tonne FD (free delivered) NWE (northwest Europe) at the end of the month. Early indications for October LDPE business were already at €1,400-1,420/tonne FD NWE on a gross basis, and spot net levels were still under pressure. PE price erosion began in September, even before the settlement of fourth-quarter ethylene at a reduction of €108/tonne ($150/tonne). August PE demand was the lowest on record, and producers’ inventories had built up in spite of improved volumes in September. “We are facing competition in ?xml:namespace> This was barely above the fourth-quarter ethylene level of €1,120/tonne FD NWE. Spot LDPE levels in western Europe were more widely considered to be higher, above €1,200/tonne FD NWE, on a net basis. Imported volumes were on offer on a more widespread basis, as PE demand slumped globally and export opportunties were limited, market players said. Vessels of PE were said to be arriving in Europe from the One major PE producer admitted that October PE prices were affected by imports, saying: “The tsunami has started.” High density PE (HDPE) was not exempt from downward pressure, with much of the imported material thought to be HDPE. There were several new capacities due on stream in the Arya Sasol Polymer Co expected to start on-spec production at its much-delayed HDPE/medium density PE (MDPE) swing plant at Assaluyeh in Arya Sasol began trial production at the two plants, which each have a nameplate capacity of 300,000 tonnes/year, in early April. The start-up of the units, originally scheduled for the second half of 2007, was deferred several times due to a shortage of technical personnel. Saudi Ethylene & Polyethylene Co (SEPC) expected to begin commercial production at its 1m tonne/year cracker and 400,000 tonne/year HDPE plant in A 400,000 tonne/year low density PE (LDPE) plant at the same complex will start-up by mid-November. SABIC also had a 400,000 tonne/year LDPE unit planned for the first quarter of 2009 at Market sources said that Saudi Aramco/Sumitomo Chemical joint venture PetroRabigh planned to start up its 900,000 tonne/year PE plant at The facility will include LDPE, LLDPE and HDPE lines. PE producers in ($1 = €0.71) Click here to find out more on the European margin report
http://www.icis.com/Articles/2008/10/02/9160276/europe-pe-plummets-on-imports-surge.html
CC-MAIN-2015-11
refinedweb
455
55.07
Response handlers are used by Controllers to transform the return value from an action (such as a string, int, etc.) into a suitable webapp2.Response. They provide the convenience of not having to repeat the same code over and over. Ferris provides a couple of built-in response handlers and allows you to register your own. Simply return a value from a controller’s action: @route def test(self): return "Hello!" By returning a string Ferris skips the view and uses whichever response handler is defined for that particular type. Simply makes the string the body of the response. Returns a response with the specified http status code, for example: return 404 Will cause a 404 Not Found error response. Returns a Message in JSON format It’s possible to create new response handlers to handle any type. Simply subclass ResponseHandler like so: from ferris.core.response_handlers import ResponseHandler from webapp2 import Response class WidgetResponseHandler(ResponseHandler): type = Widget # The class that this response handler will deal with. # This function is responsible for returning a webapp2.Response def process(self, controller, result): response = Response() response.body = result.info return response Be sure to import this in your controller or in one of the bootstrapping scripts (app/routes.py or app/listeners.py) to make sure they’re picked up by Ferris. If you want to preserve the existing response then modify controller.response instead of creating a new one. This preserves headers and other stuff (such as client side caching): controller._clear_redirect() controller.response.body = result.info return controller.response
http://ferris-framework.appspot.com/docs21/users_guide/response_handlers.html
CC-MAIN-2017-13
refinedweb
259
51.04
ControlTemplates have been introduced into the 2.1.0 branch, and have been included on the following types: ContentPage ContentView TemplatedPage TemplatedView TemplatedPage and TemplatedView now serve as the base class for ContentPage and ContentView. ControlTemplates can be used to define the visual appearance of a Control or Page while providing a clean separation from the visual hierarchy and the Content itself. ControlTemplates can be applied via Style to greatly expand themeability in Xamarin.Forms. Along with ControlTemplates the concept of TemplateBindings has been introduced. TemplateBindings work identically to normal Bindings however their Source is automatically set to the parent of the target view which owns the ControlTemplate. Usage of a TemplateBinding outside of a ControlTemplate is not supported. For more details on how to use ControlTemplates see here: IDataTemplateSelectors allow the selection of a DataTemplate at runtime per item in a ListView.ItemsSource. Usage: class MyDataTemplateSelector : DataTemplateSelector { public MyDataTemplateSelector () { // Retain instances! this.templateOne = new DataTemplate (typeof (ViewA)); this.templateTwo = new DataTemplate (typeof (ViewB)); } protected override DataTemplate OnSelectTemplate (object item, BindableObject container) { if (item is double) return this.templateOne; return this.templateTwo; } private readonly DataTemplate templateOne; private readonly DataTemplate templateTwo; } <ListView ItemTemplate=local:MyDataTemplateSelector /> DataTemplateSelectors have the following limitations: Effects provide an easy way to customize the native look and feel of controls without having to resort to a complete Custom Renderer. You can use these to customize the native controls, for example, the following Effect shows how to create a Border effect on iOS that will set a 2 pixel purple outline on the control: // located inside iOS specific codebase public class BorderEffect : PlatformEffect { protected override void OnAttached () { Control.Layer.BorderColor = UIColor.Purple.CGColor; Control.Layer.BorderWidth = 2; } protected override void OnDetached () { Control.Layer.BorderWidth = 0; } } To apply this effect, all you have to do is attached it via the IList<Effect> Effects collection on Element. This is a much simpler way of fine tuning your user interface with native touches. Nice to see ControlTemplates. Thanks. <ListView DataTemplate=local:MyDataTemplateSelector /> I'd like to point out that this line of XAML is incorrect. The property should be ItemTemplate(or HeaderTemplateor FooterTemplate), not DataTemplate. on CustomRenderers we export our renderer with [assembly: ExportRenderer (typeof (BaseEntry), typeof (BaseEntryRenderer))] Do the effects use ExportEffect or something else? @JoeManke fixed @ShanePope yes I am writing up a demo now WHAT?!?!?!? ControlTemplates? TemplatedBindings? Effects? !?!?!? BE STILL MY BEATING HEART! I am in love with this update! Best one by FARRRR!!! Cant wait to change up my entire control library. THANK YOU THANK YOU!!!! Edit: Thanks again if I wasnt clear. Oh what a release. Templates and Effects.... Wow... Testing out the DataTemplateSelector, came across a bug. We have a grouped ListView. We were previously using a DataTemplateSelector we wrote ourselves for the ItemTemplate, I'm testing out using the new official one. The ListView also has a GroupHeaderTemplate. OnSelectHeader()of the selector is being called for a group header cell. Even after modifying my selector to handle the group headers, and removing the GroupHeaderTemplate from the ListView, I am now getting an ArgumentOutOfRangeExceptionwhen trying to render this list, with the following stacktrace: are you able to get a breakpoint in there and see what values are being passed to OnLayout? Really like the Effects idea. Should be able to get rid of lots of custom renderers whose only purpose in life was to embellish the stock controls just ever so slightly. Thankyou for DataTemplateSelector What about Xamarin.Forms.Maps? Has it googleplayServices 27 as dependency? In the nuspec file it is written googleplayservices = 26 I hope that is a mistake by you!!! Bumping GPS is something we are currently evaluating, every time we do it it has the potential to break LARGE amounts of community code so its not something we do just because a new version came out. I saw you downgrade the googleplayservices in Xamarin.Forms. So I don't need the 27. I can downgrade my library and my app as well to 26. Thanks for that @TheRealJasonSmith Looks like a great release - thanks! Does this mean I can create a listview and fill the items with varying lengths of text and different sized images images (and now datatemplates!) and it'll resize each cell to fit automagically? Or is there still some calculation needed by the app as well as the framework? It means that if you do ListView.HasUnevenRows = true you can now call ForceUpdateSize on your cell which will force the cell to dynamically resize, even if it is currently visible. On some platforms this operation can be extremely expensive, so it is not dont automatically, but if you wanted to do so you could hook the MeasureInvalidated event on the Content of your ViewCell and call ForceUpdateSize in there. Again this can be extremely expensive. I like the Effects philosophy too! I'm not sure I understand what ControlTemplates are for though, what are the use-cases/possibilities with it? I believe hell may have frozen over: ListView Virtualization is now supported on Windows And those Windows bugs fixes, love it (cough still have 9 outstanding) And good work with that little side note "template / effects" update thingy you did. Please be aware that the windows support is still in a partial state. While visualization is improved we are still working to further improve memory usage. @ThibaultD ControlTemplates and TemplatedBindings are ideas that were used in Sivlerlight & WPF. They let you build true custom controls using just Xamarin Forms. Its a MASSIVE deal! If you would like more info on it really just look up custom control building for Silverlight/WPF. That will give you an idea of how powerful they can be. Also being able to knock a property with Content will be great instead of having developers right XAML like <CustomControl.Body> ... </> to simply fill in the content area because the Content property was already taken by the ContentView. Also YAYYYY to no more a thousand .SetBindings in the code behind!!! We can now set them in the template and the template can be overridden by the developer if they want to change up the control without effecting the purpose of the control. Exists doc for Effect and PanGesture? @TheRealJasonSmith These are the parameters being passed to OnLayout of the ListViewRenderer: changed = True, l = 24, t = 24, r = 1056, b = 1653 Looking at my debug output, I'm seeing another stacktrace which I figure is where the exception is really happening: My labels in a StackLayout are no longer expanding vertically when there is more text in them. @BradChase.2654 you mean like doing Inside of your ControlTemplate which binds up to the Body View on your custom class? Because you can. I'll demo it later. @RyanHerman.9335 can you show me? What are they packed in? Need more context @AlessandroCaliaro full docs are being worked on and will be available for stable release. I did blog about Effects if you care to go find that. @TheRealJasonSmith I thought it was fixed till I readded all the stackpanels to my layouts. If I just have one or two, it is fine, but I think it struggles w/ multiple expansions. Basically all the ServerResponse StackLayouts with the Label. @RyanHerman.9335 think you could boil that down to just the parts that matter OR hop on skype with me and go over this live? @TheRealJasonSmith Lets do Skype? How should I contact you? @TheRealJasonSmith I found another place where the Label does not expand to the next line. I am thinking it is a problem with the label text going to the next lines. Yup!!! Woooooo excited! Can't say that enough! I felt like I was ugly hacking away there at controls hoping this would come! I got the same issues with expanding labels. My text gets cut off. My labels are sitting next to a slider, which changes the content of the label. This works fine in the just recent official release but not in the pre release. we're trying to track it down now Which platform are you seeing this behavior on? All? Edit: so it turns out UITest doesn't really work to pick up this kind of failure the way we coded the test, woops. Edit2: Okay the problem was caused by the change we made to fix this: We are reverting the change until we can evaluate a different method of fixing it or if we want to simply codify that behavior as expected. @TheRealJasonSmith @JoeManke I'm seeing exact the same bug when changing our grouped ListView to use the new DataTemplateSelectors: @BastiBrauning we're digging into it, are you using the DTS on the ItemTemplate or the HeaderTemplate? Thanks for the fast response! Tried using it on ItemTemplate and GroupHeaderTemplate. (Using it signly on ItemTemplate the same crash occurs). Basically this is my ListView: Attached small sample project to reproduce issue. Big huge thanks for the ControlTemplates addition, this is such a game changer in building re-usable custom controls framework. I can now re-implement every control I made so far but I am really excited about it !!! Thanks again !!! @TheRealJasonSmith quick question: does the ControlTemplate mechanism adds performance degradation compared to building the same screen without ControlTemplate ? Nothing beyond what you expect in terms of "it has to inflate the template" and "whatever I put in the template is in the visual hierarchy" I also experience a lot of "Java.Lang.ArrayIndexOutOfBoundsException" on Android while fastly scrolling a ListView up/down (Recycling). I sadly can't track it exactly down to make a sample reproducement.
https://forums.xamarin.com/discussion/59503/xamarin-forms-2-1-0-pre5-released
CC-MAIN-2020-16
refinedweb
1,600
56.55
Early 4.4 and dotPeek 1.5. Below is a quick overview of what this update has to offer today. ReSharper 9.2 EAP The initial build of ReSharper 9.2 EAP is mostly about bug fixes in TypeScript support, IntelliSense and C# code analysis. - TypeScript support has received a respectable bunch of fixes. For example, renaming and moving TypeScript code is now expected to be faster in most cases as search for dynamic references is disabled by default (RSRP-427718, RSRP-432856). In other news, ReSharper now draws the line between user code and included libraries/modules, which should positively impact code analysis, navigation and refactorings in multiple scenarios (RSRP-428775). More bug fixes cover the way how features such as Go to Type Declaration and Generate Missing Members handle TypeScript code. In addition to bug fixing, there’s an ongoing effort to provide final support for TypeScript 1.5, and the initial ReSharper 9.2 EAP build comes with support for TypeScript decorators (RSRP-435162). - In terms of code analysis, a set of false positives related to PCL usage with .NET Framework 4.5, with or without Xamarin, has been removed (RSRP-394695, RSRP-427743), in addition to several memory usage and performance optimizations (RSRP-437348, RSRP-436891, RSRP-428652). A number of fixes improve code analysis of string interpolation in C# 6 (RSRP-437019), as well as regular expressions (RSRP-440290, RSRP-439698, RSRP-441299). - Code completion is now properly case-sensitive again (RSRP-428005) and works a lot faster on extension methods (RSRP-434561) - Another notable set of changes is a usability boost to Go to Usages: a non-modal version of Find Usages. The Go to Usages pop-up now includes context of discovered usages, as well as a progress bar, which is handy when you’re looking at heavily used symbols (RSRP-420796). See the entire list of fixes included in ReSharper 9.2 EAP build 1. ReSharper C++ 1.1 EAP ReSharper C++ 1.1 EAP is definitely more feature-packed than ReSharper 9.2. First and foremost, it introduces a unit test runner for Google Test. This lets you invoke tests and test cases contextually from the text editor: Similar to how the mainline ReSharper supports other unit testing frameworks, you have Unit Test Explorer and Unit Test Sessions tool windows to view, group, filter and run unit tests, as well as to create and manage unit test sessions. At this point you can’t debug unit tests with ReSharper C++ but expect this to change soon. In other news, ReSharper C++ 1.1 introduces a new refactoring, Introduce namespace alias, available via its Refactor This menu: As soon as you invoke the refactoring, it suggests defining a scope that you want to introduce a namespace alias for: Rounding up a feature set for ReSharper C++ 1.1 is a new hierarchy view called Includes Hierarchy which, quite naturally, helps you visualize and figure out your #include dependencies: Finally, ReSharper C++ 1.1 brings a whole set of bug and performance fixes in numerous subsystems, from code inspections to formatting, from quick-fixes to live templates: here’s the entire list of fixes included in ReSharper C++ 1.1 EAP build 1. dotTrace 6.2 EAP dotTrace 6.2 EAP introduces a new Incoming HTTP Requests event in Timeline mode that helps you indicate time intervals where your web application processes incoming HTTP requests. This includes the time between receiving a request by the server and sending a response. When the Incoming HTTP Requests event is selected, the Filters window contains two sub-filters: URL to determine how much time does a request to a particular URL take, and Method to check the distribution of time between requests with particular methods. You are encouraged to provide your feedback on this feature right here on the blog or in comments under feature request DTRC-10192. See the entire list of fixes included in dotTrace 6.2 EAP build 1. dotMemory, dotCover, dotPeek and SDK EAP builds of dotMemory, dotCover and dotPeek haven’t received any notable updates so far but we expect this to change as the EAP progresses. ReSharper SDK will be published later, along with one of the upcoming ReSharper EAP builds. Download them! Feel free to download EAP builds and let us know how this update is working for you. Early Access is a great time for you to provide your feedback, so please feel free to submit any issues with EAP builds to issue trackers for ReSharper, ReSharper C++ and dotTrace. What’s next? Stay tuned for more EAP builds in coming weeks. Considering that Microsoft has just set Visual Studio 2015 release date to July 20th, we’ll be looking to wrap up this Early Access Program within a month and come up with ReSharper 9.2 RTM in August, as announced earlier. 11 Responses to Early Access to ReSharper 9.2, ReSharper C++ 1.1, dotTrace 6.2 Anton Lobov says:June 29, 2015 JavaScript users, also don’t forget to check one of the interesting highlights of 9.2: support for regular expressions in JavaScript. Syntax highlighting and code completion are here for them. And ECMAScript 6 classes are now fully supported. (Support for ES6 modules is still on the way, though.) TypeScript users are welcome to try import-completion and “go to type of symbol” features. And those risky who already try TypeScript 1.6 now will find support for generators, type predicates and generic type aliases already in 9.2. 🙂 HamRusTal says:June 29, 2015 From the R# C++ POV, the 9.2 EAP1 installer is totally broken: 1. The R# C++ version is labelled as “1.0.1 EAP1” which is supposed to be earlier than the current stock “1.0.1”. 2. Once I install R# C++ *only* (chosen “Skip” for regular R# in the installer, as usual), I get NO R# features in MSVC 2013 at all. As a result, I’ve downgraded to the RTM 1.0.1. Jura Gorohovsky says:June 29, 2015 Thanks for noticing and sorry for the silly bug (RSCPP-14255). Will fix ASAP. Jura Gorohovsky says:June 30, 2015 BTW for those reading about this bug, please note that it only displays when only ReSharper C++ 1.1 EAP is installed. A workaround is to install ReSharper 9.2 EAP as well. Anyway, this will be fixed in the next EAP build. Laurence says:June 30, 2015 Yay all the false errors from my PCL usage are gone! 🙂 Øystein Krog says:June 30, 2015 I wish you had a more stable API for extensions, as it is now every release means every extension has to be updated, which does not always happen or it takes a while:/ Dew Drop – June 30, 2015 (#2045) | Morning Dew says:June 30, 2015 […] Early Access to ReSharper 9.2, ReSharper C++ 1.1, dotTrace 6.2 (Jura Gorohovsky) […] Richard says:June 30, 2015 No sign of a fix for RSRP-437980? 🙁 Jura Gorohovsky says:June 30, 2015 Not yet, apologies. Hoping to fix this in the scope of 9.2 though. IzzyCoding says:July 16, 2015 ReSharper c++ 1.1 sounds awesome. Just one question about the test runners… Does it support the Catch testing framework? Is it possible to add my own custom runners? Jura Gorohovsky says:July 16, 2015 As of 1.1, the unit test runner only supports Google Test. In future versions, we might support more frameworks although we’re yet to sort out which of them have the largest user base and outreach. For now, we have feature requests to support Catch and boost::unit. Everyone is encouraged to vote up their frameworks of choice to help us prioritize. As to adding custom runners, this would require extending ReSharper C++, which is in principle possible with the ReSharper SDK but frankly, the SDK hasn’t been polished and tested enough to support extending ReSharper C++. That said, provided there’s a strong interest in writing a particular extension, the product team can advise on safest ways to proceed.
https://blog.jetbrains.com/dotnet/2015/06/29/early-access-to-resharper-9-2-resharper-c-1-1-dottrace-6-2/
CC-MAIN-2021-10
refinedweb
1,354
65.01
Excessive type safety warnings ...Elias Ross May 23, 2007 2:19 PM Eclipse lists over 4000 warnings for JBossCache, mostly to do with type safety. I started trying to fix some of the type safety warnings by adding type parameters to declarations of Cache, Node, etc. The problem is, is that classes such as NodeListener, NodeData, StateTransferGenerator, etc. do not have type parameters. To get everything to work right will require adding some type parameters. But for some of those classes, it doesn't really seem appropriate to have type parameters like <K, V> tied into their implementation. Thoughts? Or are you going to live with all those warnings ... 1. Re: Excessive type safety warnings ...Manik Surtani May 24, 2007 6:52 AM (in response to Elias Ross) But for some of those classes, it doesn't really seem appropriate to have type parameters like <K, V> tied into their implementation. Which classes are you referring to? I agree that the number of warnngs generated due to genericised interfaces may be a bit much. 2. Re: Excessive type safety warnings ...Elias Ross May 24, 2007 2:37 PM (in response to Elias Ross) The state transfer classes, notification classes, marshaling, cache loaders, interceptors which use Fqn and Node need some sort of parameters... Or perhaps maybe wildcards or something. So, for example, you have a CacheStoreInterceptor: public class CacheLoaderInterceptor extends BaseCacheLoaderInterceptor implements CacheStoreInterceptorMBean parameterized, needs to be something like: public class CacheLoaderInterceptor<K, V, F> extends BaseCacheLoaderInterceptor<K, V, F> implements CacheStoreInterceptorMBean Where K and V are the Node key and value, and you have to include the Fqn type as well. Actually, I'm not really any sort of generics expert. There might be some way to use wildcards or something to hide all this. 3. Re: Excessive type safety warnings ...Manik Surtani May 25, 2007 6:50 AM (in response to Elias Ross) Yeah I agree, should be able to reduce those warnings. JBCACHE-1074
https://developer.jboss.org/thread/97205
CC-MAIN-2019-09
refinedweb
327
55.34
view raw Ok I do have the following code def update_state_actions states.each do |state| @state_turns[state.id] -= 1 if @state_turns[state.id] > 0 && state.auto_removal_timing == 1 end end @state_turns[state.id] -= 1 if @state_turns[state.id] > 0 && state.auto_removal_timing == 1 in 'block update_state_actions' : Undefined method '>' for nil:NilClass <NoMethodError> > how come > is considered as a method but it is a logical operator? There is no problem with that. In Ruby, when you write an expression like 1 + 2, internally it is understood as 1.+( 2 ): Calling method #+ on the receiver 1 with 2 as a single argument. Another way to understand the same is, that you are sending the message [ :+, 2 ] to the object 1. what is the cause of the error? Now in your case, @state_turns[ state.id ] returns nil for some reason. So the expression @state_turns[state.id] > 0 becomes nil > 0, which, as I said earlier, is understood as calling #> method on nil. But you can check that NilClass, to which nil belongs, has no instance method #> defined on it: NilClass.instance_methods.include? :> # => false nil.respond_to? :> # => false The NoMethodError exception is therefore a legitimate error. By raising this error, Ruby protects you: It tells you early that your @state_turns[ state.id ] is not what you assume it to be. That way, you can correct your errors earlier, and be a more efficient programmer. Also, Ruby exceptions can be rescued with begin ... rescue ... end statement. Ruby exceptions are generally very friendly and useful objects, and you should learn how to define your custom exceptions in your software projects. To extend this discussion a bit more, let's look at from where your error is coming. When you write an expression like nil > 10, which is actually nil.>( 10 ), Ruby starts searching for #> method in the lookup chain of nil. You can see the lookup chain by typing: nil.singleton_class.ancestors #=> [NilClass, Object, Kernel, BasicObject] The method will be searched in each module of the ancestor chain: First, Ruby will check whether #> is defined on NilClass, then on Object, then Kernel, and finally, BasicObject. If #> is not found in any of them, Ruby will continue by trying method_missing methods, again in order on all the modules of the lookup chain. If even method_missing does not handle the NoMethodError exception will be raised. To demonstrate, let's define #method_missing method in Object by inserting a custom message, that will appear instead of NoMethodError: class Object def method_missing( name, *args ) puts "There is no method '##{name}' defined on #{self.class}, you dummy!" end end [ 1, 2, 3 ][ 3 ] > 2 #=> There is no method '#>' defined on NilClass, you dummy! Why doesn't it says like NullPointerException There is no such exception in Ruby. Check the Ruby's Exception class.
https://codedump.io/share/qohYwdwwC0ab/1/undefined-method-39gt39-for-nilnilclass-ltnomethoderrorgt
CC-MAIN-2017-22
refinedweb
458
67.76
Hello, I am using vectors for my Sprite class. I was wondering how to implement sorting so that I could order my sprites using ZOrder attribute that I have given it? Thanks,Mariusz Overload the < operator on that class. Then you can use STL's regular sort algorithm. _________________________________________________"God speed, my lonely angel."Bitcoin | Bitcoin Ponzi Scheme Mariuz:overload with this: bool operator<(const CSprite &a, const CSprite &b) { return a.m_ZOrder < b.m_ZOrder; } and sort with this: vector<CSprite> sprites; sort(sprites.begin(), sprites.end()); it might be squirly because m_ZOrder is protected. -----I was about to post a very similar question, but more about the nature of overloading: this is my code that does not compile: for some reason it doesn't like that I'm using a function (get_laugh()) to compare the two objects, and I get the errors: main.cpp: In function `bool operator<(const time_stamp_object&, const time_stamp_object&)': main.cpp:108: error: passing `const time_stamp_object' as `this' argument of `int time_stamp_object::get_length()' discards qualifiers main.cpp:108: error: passing `const time_stamp_object' as `this' argument of `int time_stamp_object::get_length()' discards qualifiers what am I doing wrong? --Royalty Free Music • Web Design • A Past Life Mark: get_length needs to be declared const, otherwise the compiler is unsure if get_length will modify the object, therefore possibly violating the const in operator<'s parameters. Thanks for your quick response. Well it has been ages since I have worked with operators. It apears that I have to put this outside my CSprite class, which then like you said my m_ZOrder would not be accessible, unless I make it public. Is there another way to make this operator part of my class? Right now If I make < part of CSprite I get:error C2804: binary 'operator <' has too many parameters Thanks,Mariusz Because it should only be one parameter, and you'd dothis->m_ZOrder < other_thing.m_ZOrder I'm not sure if it'll still complain about protected, though. If it does you'll need to create a function that returns m_ZOrder, or just move m_ZOrder to public. EDIT: bool operator<(const CSprite &b) { return this->m_ZOrder < b.m_ZOrder; } William: I tried adding const in front of the function but didn't work ... ?? Thats right now I remember. Thanks a lot You don't need to overload anything if you don't want to. You can just write something like: struct sprite_sorter { bool operator()(const CSprite &a, const CSprite &b) { return a.m_ZOrder < b.m_ZOrder; } }; /* And then */ std::sort(sprites.begin(), sprites.end(), sprite_sorter); --- Bob [ Webpage | Allegro FAQ | Coding Tricks ]"Oh, you want to do actual work. In that case, avoid the GameCube at all costs!" - Me Thats cool, but I have just implemented William's suggestion and it seems that everything is working just fine. Anyhow, I really appreciate your input, it helps me to refresh my rusty C/C++ stuff. All the best,Mariusz -----------------------------------------------------------------------------------Few minutes later...... Wow, now I am confused. The sorting works just fine when I use QuickWatch everything is sorted as it should, but my Render function draws somehow different. I have BG with zOrder of 1000 (background with size of full screen).I have two sprites zOrder 1 and 1005 My Render function looks like this: I would expect fro one sprite to be hidden behind my Background according to its ZOrder. Any suggestions? (oops wrong thread) Mark: Hmm, learn something new everyday. You need to put it after the () of the function."const int some_function" apparently means that the result is constant, while"int some_function() const" means that the function will not modify *this. ah, thanks. I'd give a cookie if I could. struct sprite_sorter { bool operator()(const CSprite &a, const CSprite &b) { return a.m_ZOrder < b.m_ZOrder; }}; /* And then */std::sort(sprites.begin(), sprites.end(), sprite_sorter); Why bother with the struct? #include <algorithm> static bool comp(const CSprite &a, const CSprite &b) { return a.m_ZOrder < b.m_ZOrder; } std::sort(sprites.begin(), sprites.end(), comp); [edit] Right now If I make < part of CSprite I get:error C2804: binary 'operator <' has too many parameters Make the operator < take only one argument and compare whether *this < the parameter. How is my posting? - Order Hero - SF Bike Rentals - Mouse Mash - Got Tod? - Taco Roco[The Musings of a Lost Programmer] todo Thing Library 1.0 Punchcard Metrics I would probably go with overloaded operator< if maximum speed is necessary. I'm not sure if functors can get inlined. // should be inside class definition bool operator<(const CSprite &a) const { return m_ZOrder < a.m_ZOrder; } //Somewhere in code std::sort(sprites.begin(), sprites.end()); If I was Mark I'd use this kind of code: If all this code is in headers those functions should get inlined. _________ #include <algorithm> inline bool comp(const CSprite &a, const CSprite &b) { return a.m_ZOrder < b.m_ZOrder; } std::sort(sprites.begin(), sprites.end(), comp); Any speed boost you're getting from using operator < is imagined. What HoHo said. The overloaded operator should be a member func. That's why the compiler complains about the "this" argument. ---Me make music: Triofobie---"We need Tobias and his awesome trombone, too." - Johan Halmén What HoHo said. The overloaded operator should be a member func. That's why the compiler complains about the "this" argument. No, thats wrong. A standard conforming compiler accepts both ways, one takes 2 parameters and the other only takes 1. Hi, I have a question in regards to STL list sorting. This is a snap of my code that I use: Problem I am having is that Alien sprite is hidden behind Background and unless I add sprites in order Background, player, alien I have alien sprite hidden. It appears that the sort function is not working for me. Any suggestions would be appreciated. This is a guess, but I think you are sorting pointers, instead of objects (it's a vector of pointers to CSprite, instead of an vector of CSprite). Try adding some logging to the operator< member function to see if it is actually called. You could create a custom compare function that compares pointers to CSprite and use that as an argument to the sort algorithm. See Bob's message above. Well, I am not exactly sure where to place Bobs code. Is the structure a part of Sprite Class, or a shared function? Where do I call sort from, so far I get an error telling me that sort is not a member of std namespace. error C2039: 'sort' : is not a member of 'std'error C2275: 'sprite_sorter' : illegal use of this type as an expression f:\Dev\App\Galaxy\Game.cpp(9) : see declaration of 'sprite_sorter'error C3861: 'sort': identifier not found, even with argument-dependent lookupGalaxy.cpp Thanks,M. You probably forgot to #include <algorithm>. I have made a small example: Thank you, I will check this as soon I have a chance. M.
http://www.allegro.cc/forums/thread/569405/571547#target
crawl-003
refinedweb
1,152
66.23
Tkinter Geometry Managers Note: this is a work in progress Introduction As we’ve seen, creating a new widget doesn’t mean that it appears on the screen. To display it, you need to call a special method: either grid, pack (which we’ve used in all examples this far), or place. The pack method doesn’t really display the widget; it adds the widget to a list of widgets managed by the parent widget. An idle task [TERM?] will take care of the rest as soon as Tkinter has nothing better to do. Here’s a simple example: from Tkinter import * root = Tk() label = Label(root, text="Message") label.pack() button = Button(root, text="Quit", command=root.destroy) button.pack() mainloop() The first call to pack simply adds the label widget to the list of widgets managed by the root window (which behaves pretty much like any other Toplevel widget). It also schedules an idle task [TERM?] which will call the geometry manager at a later time. The second call adds the button widget to the root list. The idle task has still not run, so this method doesn’t add a new one. Finally, the mainloop will sooner or later get around to call the idle task. The geometry manager then loops over all it’s children in one go, calculates the appropriate size for each of them based on their “natural” size [TERM?], displays them, and finally asks the root window to resize itself. Note that the use of an idle task means that the geometry manager isn’t directly involved by the call to pack. This allows you to pack a whole bunch of widgets, and have them all managed in a single pass by the manager’s geometry algorithms. Now, let’s take a closer look at the different geometry managers provided by Tkinter. The Grid Manager As the sound implies, this manager organizes its children in a grid. The master widget is split into a number of rows and columns, and each “cell” in this grid can hold a single widget. [image goes here] To use the grid manager for a widget, use the grid method: grid(row=index, column=index, options…). This method places the widget in the given cell. The grid manager will make sure that both the row and the column is large enough to display the entire widget, and position it correctly. If you leave out the row option, the widget is placed in the first empty row. If you leave out the column option, the widget is placed in the leftmost column (index 0). # Example: File: grid-example-1.py from Tkinter import * root = Tk() w = Label(root, text="Additive:") w.grid(sticky=E) w = Label(root, text="Subtractive:") w.grid(sticky=E) w = Label(root, text="Cyan", bg="cyan", height=2) w.grid(row=1, column=1) w = Label(root, text="Magenta", bg="magenta", fg="white") w.grid(row=1, column=2) w = Label(root, text="Yellow", bg="yellow", height=2) w.grid(row=1, column=3) w = Label(root, text="Red", bg="red", fg="white", height=2) w.grid(row=0, column=1) w = Label(root, text="Green", bg="green", height=3) w.grid(row=0, column=2) w = Label(root, text="Blue", bg="blue", fg="white") w.grid(row=0, column=3) mainloop() Things to Notice Rows and columns are made large enough to fit the largest widget. The labels have different widths, and I’ve used the height option to vary their height. Note how each row and column are made wide enough to show all widgets, and that the widgets are centered in the resulting cells. You can use options to change this in different ways; see the next section for details. Using default values for row and column. The first two labels use default values for the row and column options. As a result, they are both placed in column 0, in the rows 0 and 1. You can place the widgets into the grid in any order. It’s only the row and column numbers that count when the grid manager lays the widgets out. Although it’s not shown here, you can also leave empty rows and columns if that makes your code simpler. Rows, Columns, and Cells [minsize] [pad] The grid_size method returns the number of columns and rows allocated by the grid manager. You can use this function to add new rows (or columns) to a grid: def add_entry(master, text): column, row = master.grid_size() label = Label(master, text=text) label.grid(row=row, column=0, sticky=E, padx=2) entry = Entry(master) entry.grid(row=row, column=1, sticky=E+W) return entry [grid_location] Expanding and Filling By default, the grid manager. [ILLUSTRATION] The option value is a string, which can contain one or more of the characters “n” (north), “s” (south), “w” (west), and “e” (east). For example, “n” centers the widget along the upper cell border. “se” moves the widget to the lower right corner. If you attach the widget to two opposite borders, it’s resized as necessary. For example, “ns” stretches the widget vertically, while “we” stretches it horizontally. Finally, “nswe” makes the widget fill the entire cell. Instead of string values, you can use the builtin constants N, S, E, W, NE, NW, SE, and SW. To combine these, use the “+” operator. [grid_columnconfigure grid_rowconfigure weight] [padding] Spans Usually, widgets occupy a single cell in the grid. You can use the columnspan and rowspan options to change this for any given widget. The columnspan option tells the geometry manager that a widget should occupy not only its original cell, but also one or more extra cells to the right. The option value is the total number of cells to occupy. The rowspan option is similar, but it tells the manager to occupy extra cells under the original. [example] Geometry Propagation [grid_propagate] [example] [note: continues in ch09b.txt] The Pack Manager The pack manager places its children on top of each other in columns, or side by side in rows. This manager is a quite elaborate piece of code. Too elaborate to fully understand in one sitting, perhaps, so I’m not going to tell you the full story until later. Let’s start with a simplified version of the story. “The Pack Geometry Manager For Dummies” This far, we’ve learned two things: - To make a widget visible, use a geometry manager - The grid geometry manager is a geometry manager Sounds like all we need to know, doesn’t it? Why learn another geometry manager? Well, there is a reason why I used the pack manager in all examples leading up to this chapter. The pack manager is much easier to use in a few, but quite common situations: - Put a widget inside a frame (or any other container widget), and have it fill the entire frame - Place a number of widgets on top of each other - Place a number of widgets side by side Filling a Frame (Or Any Other Container Widget) A common situation is when you want to place a widget inside a container widget, and have it fill the entire parent. Here’s a simple example: a listbox placed in the root window: # Example: File: pack-listbox-1.py from Tkinter import * root = Tk() listbox = Listbox(root) listbox.pack() for i in range(20): listbox.insert(END, str(i)) mainloop() By default, the listbox is made large enough to show 10 items. But this listbox contains twice as many. Wouldn’t it be reasonable if we could show them all simply by increasing the size the root window? Of course, it isn’t that easy. The listbox [FIXME] Packing Things On Top Of Each Other To put a number of widgets in a column, use the pack method without any options: pack(). This method centers the widget along the top border of the parent widget. If other widgets are packed in the same parent, this widget is placed just under them. # Example: File: pack-example-1.py from Tkinter import * root = Tk() w = Label(root, text="Red", bg="red", fg="white") w.pack() w = Label(root, text="Green", bg="green", fg="black") w.pack() w = Label(root, text="Blue", bg="blue", fg="white") w.pack() mainloop() You can use the fill=X option to make all widgets as wide as the parent widget: # Example: File: pack-example-2.py from Tkinter import * root = Tk() w = Label(root, text="Red", bg="red", fg="white") w.pack(fill=X) w = Label(root, text="Green", bg="green", fg="black") w.pack(fill=X) w = Label(root, text="Blue", bg="blue", fg="white") w.pack(fill=X) mainloop() Packing Widgets Side By Side To pack widgets side by side, use the side option. If you wish to make the widgets as high as the parent, use the fill=Y option too: # Example: File: pack-example-3.py from Tkinter import * root = Tk() w = Label(root, text="Red", bg="red", fg="white") w.pack(side=LEFT) w = Label(root, text="Green", bg="green", fg="black") w.pack(side=LEFT) w = Label(root, text="Blue", bg="blue", fg="white") w.pack(side=LEFT) mainloop() If you need to create more complex layouts, the standard answer is to use the grid manager instead, or to use nested Frame widgets. For example, here’s a simple entry form using frames within frames: # Example: File: pack-entry-form-1.py from Tkinter import * root = Tk() def add_entry(master, text): frame = Frame(master) label = Label(frame, text=text) label.pack(side=LEFT) entry = Entry(frame) entry.pack(side=LEFT) frame.pack() add_entry(root, "First") add_entry(root, "Second") add_entry(root, "Third") mainloop() It might be simple, but it’s no simpler than the corresponding grid code, and the result is much worse. The main problem is that since the labels have different widths, the entry fields don’t line up. You could use the width option to make all the labels equally wide: # Example: From file: pack-entry-form-2.py def add_entry(master, text): frame = Frame(master) label = Label(frame, text=text, width=10) label.pack(side=LEFT) entry = Entry(frame) entry.pack(side=LEFT) frame.pack() This has some drawbacks, including the problem of picking an appropriate width. If width is too small, the Label widget will not display the entire label. A less obvious way is to tweak the packer options a little. First, use the fill option to make all frames as wide as the parent widget, and then pack the entry field towards the right border: # Example: From file: pack-entry-form-3.py (portions) def add_entry(master, text): frame = Frame(master) label = Label(frame, text=text) label.pack(side=LEFT) entry = Entry(frame) entry.pack(side=RIGHT) frame.pack(fill=X) Much better, but the labels are still left justified. What if we want them to be right justified, like in the grid examples? Well, nothing is impossible. Just pack the labels after the entry widget, and pack them against the right border. This way, they will end up just to the left of the entry fields: def add_entry(master, text): frame = Frame(master) entry = Entry(frame) entry.pack(side=RIGHT) label = Label(frame, text=text) label.pack(side=RIGHT) frame.pack(fill=X) That’s more like it. But given that this is not very obvious, and no shorter than the corresponding grid code, it’s probably a good idea to use the grid manager for cases like this. How Things Really Work [FIXME] By default, the areas used by the pack manager is similar to the cells used by the grid managers. If at all possible, the area is made large enough to hold the widget, However, some of the details are a bit less obvious in this case. If you pack a widget along the top or bottom side, the area allocated to that widget is high enough to display the entire widget, but as wide as the entire parent widget. Likewise, if you pack a widget along the left or right side, the area is as wide as the widget, but as high as the entire parent widget. FIXME. Geometry Propagation The Place Manager FIXME The Notebook Component FIXME Rolling Your Own Geometry Manager FIXME
http://www.effbot.org/zone/tkinter-geometry.htm
CC-MAIN-2014-15
refinedweb
2,054
65.01
=== is almost never seen in Ruby. It's nothing like the JavaScript version of the operator. It is up to the class in question as to what it means. Here are a few examples: Regexes /^zzz/ == 'zzzbb' # => false /^zzz/ === 'zzzbb' # => true Case Statements Case statements use === This can be really useful for something like the following: def tracking_service(num) case num when /^.Z/ then :ups when /^Q/ then :dhl when /^96.{20}$/ then :fedex when /^[HK].{10}$/ then :ups end end tracking_service('zZ') # => :ups tracking_service('Qlksjdflk') # => :dhl tracking_service('H2828282822') # => :ups Array.grep Arrays have a method called grep that uses === ["apple juice", "carrot juice", "coca-cola"].grep /juice/ # => ["apple juice", "carrot juice"] Ranges === checks to see if a number is contained. (2..4) == 3 # => false (2..4) === 3 # => true (2..4) === 6 # => false Lambdas Lambdas evaluate under === is_even = -> (x) { x % 2 == 0 } is_even == 4 # => false is_even === 4 # => true is_even === 5 # => false From the (unofficial) Ruby Style Guide: Avoid explicit use of the case equality operator ===. As it name implies it's meant to be used implicitly by case expressions and outside of them it yields some pretty confusing code. Credit to for explaining some of these concepts on StackOverflow Class objects implement === as "is_a?". Which is kind of neat for case statements, but also has a couple of gotchas: Thanks, thenickperson. I'd follow that recommendation. Add a comment
https://coderwall.com/p/53xawg/the-rarely-used-in-ruby
CC-MAIN-2015-32
refinedweb
229
75.61
Well as you might have figured out, if I hadn't explicitly said it earlier, doing JSPs with the old style <% %> style tags is, well just that, old school. Now don't get me wrong, a lot of code out there in the world still uses this syntax. Of course, a lot of business code out there also uses COBOL. At some point in the long history of Java EE, JSP version 1 was just a pain to use. To clean things up a bit, the Java people came up with the idea (not really came up with) to use tags as opposed to marked up code. Basically, you could put some code behind the scene and wire it into the page via a tag. This allowed Java coders to think about Java and web developers to think about web developing. So we are going to up the ante here and play both roles for the time being. Basically we are going to create a simple Java class and use POJO (Plain Old Java Object, you hear POJO tossed around A LOT in Java circles) in our pages by using markup tags. Our Java class will pick a number randomly and display it when you hit the page. At the same time, we are going to say Hello, World again and display our Date/Time that we've come to know so much. We will be using the outline pane (the one on the right) a lot here to add prebuilt methods to the class. Also, we will be using the auto-completion feature of Eclipse a bit as well in the JSP page. To activate the auto-complete function just press CTRL+Space and a small little box should call up. So let's begin with our Java code. Basically we want to expose three things here and those things are going to be read-only. - Current Date/Time - Random number - Message: "Hello, World!" So let's begin by creating a new Java class. Right mouse click on the Java resources in the project explorer (left pane) under your project and select new class: New → Class We want to keep thing organized, so our Java classes that are not servlets we will put into a package called, com.blogger.beans. We will call this class HelloBean. While you are at the dialog, go ahead and check the generate constructor from superclass. That will give us a default no argument constructor for our new class. Now we need to create what the Java people like to call fields. In the C++ world we call them members. Basically, these are variable that are private to the class. We are going to create three, each to hold a bit of information that I enumerated earlier. So click in your generated class file just between the public class statement and the constructor, this is usually where I like to put fields. Here go ahead and start typing: private Date currentDate; private Integer randomNumber; private String someMessage; You'll notice the word Date is underlined. That's because the "java.util" package has not been imported. Click on the underlined word and the quick fix box shows up. Go ahead and select the quick fix to import "java.util.Date". This will fire up yet another Eclipse wizard (at this point I'm just going to stop calling the wizards by name). This wizard allows you to quickly generate the standard get and set names for each field in your class. Since we are making our fields "read-only" we are only going to generate the "getters" and not the "setters". (Hint: In C++ the Java "getters" are called accessor, and the Java "setters" are called mutators. I'm sure in C# they call them something else completely. See how computer terms are fun!) So click on the Select Getters button and that will select only the getter methods to be generated. Click OK and you'll be put back into your Java code editor and see the newly created methods. These methods follow the Java Bean Standard (JSR-273) which basically puts the word "get" in front of the field's name and capitalizes the first letter of the name. See hard standard to follow, eh? Now in our constructor, we are going to set the values of these fields. This way the fields are given a value when someone requests the POJO, and they can only read those values. When someone requests a new POJO, new values are pumped into the fields. Here's the final code for our class: package com.blogger.beans; import java.util.Date; public class HelloBean { private Date currentDate; private Integer randomNumber; private String someMessage; public HelloBean() { this.currentDate = new Date(); this.randomNumber = (int) (Math.random() * 10); this.someMessage = "Hello, World!"; } public Date getCurrentDate() { return currentDate; } public Integer getRandomNumber() { return randomNumber; } public String getSomeMessage() { return someMessage; } } As you can see in the constructor, I've given each field a value. So now we save our bean and let's create a new JSP page. In our Project Explorer (left side), go ahead and find our current index.jsp and delete it, by right mouse clicking on the file and choosing Delete from the context menu. You'll get a pop up asking if you are sure. Now let's create a new one by right mouse clicking on the WebContent folder and choosing New → JSP File. In the wizard dialog thing, name the file index.jsp (again) and in the second step of the wizard pick the HTML one again. We are now going to tell the JSP compiler that we wish to use our Java bean that we just created. To do that we need to use one of the standard JSP tags. These are located in the built in namespace called jsp. The tag that we wish to use is So just above the element in your newly generated JSP page, add a space between the DOCTYPE declaration and the html tag and press CTRL+Space to call up the auto complete. You'll see a slew of jsp tags that you can use. Go ahead and start typing jsp:us and you should see the tag that you are looking for pop into the box. (It is important that when you want to auto-complete tags that you NOT type the opening marker "<", Eclipse will do it for you.) You will note that it goes ahead and puts in one of the attributes called "id". Go ahead and give this attribute the value of "mybean". Now we need to tell the JSP compiler which Java class to associate with this ID. We do that with the "type" attribute. For good measure we will also do the "class" attribute. We want to fill both of these attributes with the fully qualified name of our bean: com.blogger.beans.HelloBean. However, the nice thing is that if we type enough say, "com.blo" we can then use auto-completion. The final attribute that we need to set is called "scope". This basically tells the JSP compiler how often it should build the POJO from our Java class. Right now, the default is page. This means that the POJO will exist as long as the page. If you refresh the page, then you get a new POJO. There is all kinds of request scopes and in a later post, I'll cover them. However, let go ahead and explicitly declare this. Now let's use the bean in the JSP. In the body of the web page create a paragraph element and in paragraph element go ahead and create a jsp:getAttribute element. (Remember you can press CTRL+Space and then type "jsp:getA" to auto-complete it) and in paragraph element go ahead and create a jsp:getAttribute element. (Remember you can press CTRL+Space and then type "jsp:getA" to auto-complete it) You'll see two attributes in this element "property" and "name". The "name" attribute is the name you gave in the ID of the jsp:useBean tag. Go ahead and fill that in with the name "mybean". Move back over to the property attribute and CTRL+Space. You'll see a list of fields that comply with the JSR-273 standard. Go ahead and select the currentDate field. <%@> <jsp:getProperty<br /> <jsp:getProperty<br /> <jsp:getProperty </p> </body> </html> Now you are ready to run this web application on your server. You can quickly run the project by click on the run icon in the toolbar (about time I started talking about the toolbar, eh?) Here's a picture of what it looks like: You should see your web page appear with all the information. You can click the refresh button to see the information updated with every page. Ta-Da! You've now built a more powerful web application by using beans! You've also ditched the <% %> tag method to start using the more XML friendly JSP tags. There's a lot of places to go now, but we've only created a read-only bean. How do we make and use read-write beans? We'll create a slightly more powerful and interactive web application on the next go round. For now, get use to using the auto-completion and building JSP pages. I'm going to start dropping the step-by-step and start looking at the general overview. So get cozy with creating Java classes, servlets, and JSP pages. Cheers!
http://ramenboy.blogspot.com/2012/12/moving-on-up-and-beans.html
CC-MAIN-2018-13
refinedweb
1,592
73.47
Developing Axis Web services with XML Schemas. Developing SOAP based web services (Note: If you are looking for RESTful web services, please refer Axis2 ) with Axis1.4 is pretty easy, if the consuming clients are purely java. The real challenge comes if you want to make your web services interoperable with wide range of clients including .Net, Perl, C++ and Flash MX etc. Axis supports 4 types of web service styles i.e. RPC, DOCUMENT, Wrapped and Message. But the ?document/literal' type web services are most interoperable with wide range of clients. This tutorial does not explain what are web services about or the SOAP message formats with different styles. For more information about AXIS web services you may visit the Axis website . This tutorial will explain the step-by-step procedure to quickly develop the working web services with xml schemas. All the necessary Axis jar files are included in the tutorial source code project. Step1: Identify your Web service and its business methods. Here, I have identified ?StockQuoteService' is my web service and ?getStockQuote (String ticker)' is the business method. I am visualizing, the following java classes. StockQuoteService.java Stock.java Quote.java Step2: Define XML Schema and WSDL . 1. Define XML Schema ( Stock.xsd ). You can find this file in the downloaded project under directory StockQuote\src\ws\schemas. The two java objects 'Stock' and 'Quote' are defined as shown below in Stock.xsd. Stock element has two attributes; one is ?ticker' of data type xsd:string and the other is ?quotes' which is array of ?Quote' elements. maxOccures=?unbounded? indicates that stock object contains array of ?quote' objects. Quote element has two attributes, one is ?quotePrice' of data type xsd:int and the other is ?dtQuote' of data type xsd:date. ?getStockQuote' element represents the input parameter to the to the web service method ?getStockQuote()'. ?getStockQuoteResponse' element represents the out parameter of the web service method getStockQuote(). 2. Define WSDL (StockQuote.wsdl). You can find this file under the directory StockQuote\src\ws\schemas. Below section shows the definition of the namespace. The namespace need not be actual URL on the web. Also note that we have imported the Stock.xsd with proper namespace, which we defined in A. Below section shows the definition of the input and out put messages for our business method. Note that the part name is the actual name defined in Stock.xsd file. Below section shows the definition of Port type and the operation (our business method) with input and out put parameters. Below section shows the definition of binding name for the above port type. Here we defined the web service style as ?document'. Below section defines the service for the above binding. Step3: Run WSDL2JAVA task by running schema-build.xml file located under directory StockQuote\src\ws. Note the below given axis-wsdl2java task. Here we pointed URL attribute to the ?stockquote.wsdl' file. There is another file called NStoPackages.properties, which defines the Name Space to Package definitions to the generated java files. This will generate Stock.java, Quote.java , web service files and deploy.wsdd files under the directory StockQuote\src\ws\wsdd-build Copy Stock.java and Quote.java files to ?StockQuote\src\com\stock\model' directory. Open the deploy.wsdd file and remove unwanted ?>'characters from rtns:>Stock and ns:>Stock. I found axis tool is adding these unwanted ?>' characters. Change the class name to our actual implemented web service class <parameter name = ?className? value=?com.stock.model.Quote.StockQuoteService?/> Copy <Service> to </Service> tag from deploy.wsdd file and replace in StockQuote\web\web-inf\ server-config.wsdd file. Note : once the moving of java files and copying of wsdd file is done, delete the directory ?wsdd-build'. Other wise, the next step project build will give compile errors. For the sake explanation schama-build.xml file configured to generate the files under ?wsdd-build' directory. This can be configured to your actual model class directory, so that moving of java files are not needed. Step4: Build and deploy the web service. Run build.xml located under directory stockQuote . This will build the project and generate stock.war file under ?dist' directory. Deploy this war file in tomcat. In your browser open the URL . You should be able to see the axis generated WSDL file in the browser. Step5: Test the deployed web service. Run StockQuote\webservice-client\webserviceclient-build.xml file. Note the deployed web service URL in this build file. Change this to appropriate URL, if your server port and host name are different. This will generate the required client stub classes. Run StockQuoteTest.java located under ?StockQuote\webservice-client\client' directory. If all well you should be able to see the output with out any exception. . Axis Web services with XML Schemas. View All Comments Post your Comment
http://roseindia.net/webservices/developing-axis-web-services-XML.shtml.shtml
CC-MAIN-2017-09
refinedweb
810
53.68
My, in particular with the Schematron program (quite like it!), but I have also contributed some code to the Flamingo/Substance project over at JavaDesktop, which provides novel looks and feels and more modern GUI components. The only time I use Microsoft products is on my laptop at home (a present from my dear old Dad), but I need it to run the SynthEdit program for making virtual synthesizers. Oh, I occasionally also use a ten year old Microsoft C++ compiler, to make some DSP filter code: I have released about 80 filters open source this way. I’m not a Microsoft hater at all, its just that I’ve swum in a different stream. Readers of this blog will know that I have differing views on standards to some Microsoft people at least. As a regular participant at ISO standards, on and off for more than a decade at my own expense, it has always frustrated me that the big companies would not come to the table and make use of ISO’s facilities. So I am a big fan of the Mass. governments push that governments should use standard formats only. I know some of the ODF people, I had some nice emails with the ODF editor over Christmas for example, and Jon Bosak asked me to join the original ODF initiative at OASIS (I couldn’t due to time, unfortunately.) So. The same myth comes up in the form “You have to implement all 6000 pages or Microsoft will sue you.” Are we idiots? Now I certainly think there are some good issues to consider with ODF versus OOXML, and it is good that they come out an get discussed.? In fact, the issue of whether there should be two standards largely comes down to the issue of how ISO members interpret the ISO term “contradiction”, which is the show-stopper. The ODF people want a very loose understanding of it, the OOXML people want a very tight understanding of it; the precedent at ISO (which involves a case made by IEEE against China on ISO/IEC 802 encryption IIRC) seems to favour a tight definition: in that IEEE case, the contradiction would break the standard internally and break other standards: the preferred route was “harmonization” (where the Chinese technology could be used, but expressed and implemented in ways that wouldn’t break the existing standards.) There is no need for this kind of harmonization in ODF versus OOXML because one does not break the other. Therefore there is not the same kind of “contradiction.” So I don’t see that the IEEE case supports ODF, actually. But it is a legitimate question to ask, even if the answer is “OOXML does not contradict ODF by overriding it or utilizing it incompatibly” (which is, IMHO, the correct answer.) But there is also a sea of crap being produced, and if offends me a little to see the ISO process get slung with this kind of mud. I suspect that many technical reviewers for National Bodies will take a dim view of vague or stupid claims. For example, in the Wikipedia entry, it currently mentions that “the members of ISO have only 31 days to raise objections”, the implication being that this is far too short a time; yet, if I understand matters correctly, ODF was submitted in a fast-track procedure that didn’t even allow these kind of objections. My understanding from attending the ISO meetings in Korea last year was that MS chose the two-step process to demonstrate that they are not trying railroad this through with no open-ness in the process. (On the other hand, the kind of openness that a completed external specification like OOXML can have is different from the kind of openness that a work-in-progress external specification like ODF affords.) Actually, I should get off the high horse; much of the FUD amuses me, it is hilarious (I have even heard an ODF guy claim that MS wants to enable death squads with their UUIDs, ROFL); I’m looking forward to the next few days. Since you openly admit to being paid my Microsoft you immediately destroy any credibility as a neutral commentator. End of story. First, my position: pro-ODF. I'd like to reply to a few points: >>>>The OOXML specification requires conforming implementations to accept and understand various legacy office applications>As I have mentioned before on this blog, I think OOXML has attributes that distinguish it: ODF has simply not been designed with the goal of being able to represent all the information possible in an MS Office document You wrote: . It's a bit harsh, but I have to agree with Ian Lynch's comment. Look what Microsoft did in Massachusetts, and is still trying to do- derail ODF at all costs, to the extent of trying to re-organize the state government so that a "task force" would take control away from the Information and Technology Division. Now what business does Microsoft have interfering in any government body to that degree?. Had Microsoft participated in the development of the ODF spec, as they were invited to do, their claims that ODF was not developed with MS Office formats in mind would be largely a non-issue. In fact, this point makes Microsoft's claims largely FUD. And I agree with the sentiments that being paid by Microsoft shoots your credibility out of the sky. Honestly, wouldn't it have been better for you to offer corrections voluntarily? Or at least be paid by an independent body. It seems both silly and redundant to have to point out that you cannot both be paid ("contracted" in your terms) by an interested party for an opinion on an issue, and be "independent" on that issue. I am aware that there are people who would make the argument that this is ethically possible, but note that such arguments are almost invariably made by people who are being paid to do so. Even in a courtroom setting, where the system goes to great lengths to maintain a version of this illusion, expert witnesses are presented as "for the defense" or "for the prosecution". Peter Yellman How *DARE* you clean up anti-M$ FUD on wikipedia! I'M TELLING RMS ON YOU! Perhaps I'm missing something but I thought the purpose of a standard was for people to create interoperable implementations. Having something like "strings" spew out bits of ascii text from an ODF document would be "conformant" under your definition it would just not implement 99% of the "bits" and say so. This seems even more absurd.. As far as I'm concerned, this issue can be broken down into a single crux; can a document in OOXML using a legitimate partial implementation be opened in a MS product, saved, and still be opened by the original, non-MS tool? Similarly, can a file created in an MS product be altered by a non-MS tool and still be valid?. "Or at least be paid by an independent body." If you can find one that is truly independent, and not a Microsoft-funded shill. :) The example of the Chinese WAPI contradiction is certainly a precedent. But so is the case last year where the German and UK NB's raised a contradiction in JTC1 against Microsft's C++/CLI specification. (See for details). This page is gathering a lot of good information. @Rick, >". My viewpoint: pro-ODF, anti-FUD, pro-open standards.. @Rob,!" What is the point of having an approved and accepted standard if any large corporation can come along and insist on their own file format being a "standard"?. The need to keep to archivists happy is easily understood, and I have no objection to the notion of Microsoft creating an XML-based format that can express every single piece of legacy data in their back catalogue. That's their business. But what need is there for it to be an ISO standard? Wikipedia entry doesn't cover even half of the problems with OOXML, there's more complete list at I'm on your side. I hope you are able to take it on. The FUD-calling is pretty disgraceful, and it bothers me a lot that supposed professional executives for really big brightly-colored organizations (formerly known as the biggest monopoly on the planet until another one arrived) are making a death-match out of this. Oh about the maturity of ODF. Let's see, OpenOffice.org still doesn't produce an ODF document that relies exclusively on the ODF-blessed namespaces. There is still no formula specification for spreadsheets and other formula usage.. "but there is no provision to say what format that blog is in" Sorry, I meant "blob" not "blog." to: M. David Peterson A technology company creating new technologies?! THAT'S JUST AWFUL! Think of the children! However, your basic premise is wrong. Microsoft does not create open standards. It's so called standards are simply a set of specifications controlled by Microsoft. Upon detailed diagnosis, every one of Microsoft's so called standards are simply part of its ongoing strategy of embrace, extend, exterminate frank There is something fundamentally wrong with accepting payment to contribute to Wikipedia. Wikipedia is a consensus of what, under certain guidelines, a very large community thinks. This is not much different from accepting a paid lobbying contract; if anyone is paid to contribute to Wikipedia and not a member of the Foundation itself, it is by nature astroturfing. I hope you can agree that it should be discouraged.. For one that claims understanding of the ISO standardization processes, you leave much to be desired with respect to the current topic. ODF was accept through the fast track procedure and OOXML is on the fast track procedure. The difference, of course, is that the ODF spec (around 700 pages) is about 1/10 the size of OOXML (about 8000 pages). Please read Rob Weir's blog if you haven't already; I have found it to be an excellent eye-opener about just how horribly evil OOXML is. If you can actually stomach reading Rob's blog an still go on with this job... well... actually either way I want to ask: How much money are they paying you and what are the terms? Did you ask if it was OK to blog about the specifics? /amazed MS announced years ago that bloggers would be selling vista. Specifically, On another note, I think that companies paying people to correct harmfully incorrect things about them in Wikipedia is a great idea and makes a lot of sense. I'm sure it happens all the time, but I don't know of any prior cases of people admitting to doing it. If you're going to try to be honest and transparent about it though, you should of course say on your userpage what you are doing and who's paying you. Sorry for the rapid-fire comments; I'll stop now. How amusing... Microsoft dosen't being the victim of FUD. Feel free to change the wording as long as you don't hide the problem. The difficulty is that, as written, the spec allows a compliant document to contain any Microsoft legacy format, and the resulting document is still considered an OOXML file. In my view, a standard document format should be just that, with sufficient information to allow programs to be written to fully parse that document format. Old formats should not be considered OOXML. Orcmid wrote:. Quite apart from the MS propaganda/"fact-correcting" issue, the author seems to be pointing a finger at Wikipedia - regarding the inaccuracy of information on its pages.. re: M. David Peterson's "his credibility would be exactly where it would be based on the knowledge of who Rick is"! Re: Finite: Let's see, OOXML is a huge piece of crap. That's a fact. If you write about it objectively MS ain't going to be very happy ^_^ For the record, although pseudonymous (so you'll have to take my word for it) I feel I should note at this time that I am not employed by any players in this field :) I just happen to really hate fake openness, crap standards, Microsoft, _and_ shills*... so I've got a strong personal interest in this matter.: Wow, so many comments. Here's a few quick responses. Rick:. You said: "yet, if I understand matters correctly, ODF was submitted in a fast-track procedure that didn't even allow these kind of objections.". Rick, thank you for your response. I really hope that once you have had some time to think this over, you decide to turn it down. You sound like an interesting, intelligent, self-directed sort of guy. I really would like to hear your own opinions of the formats, and how each can be improved. I do not want the things you say to be subjected to "he was paid to say that," even if you finally decide to say things I disagree. Brad: Thanks for finding me attractive. I am even more attractive in person, actually. I have been involved in standards work at ISO, W3C, Standards Australia, IETF and a regional body, and there has always been a corporate influence. Standards committees are not always a paradise of humanitarians and altruism, and certainly not of commercial dis-interest. SGML came out of IBM. XML came out of Sun's Jon Bosak's organizing ability. And so on. The idea that there has not been corporate involvement in standards is not real. Some standards committees, such as W3C Internationalization, have a large corporate influence but are highly benign and fun. Other groups are just a hard slog, with the big boys trying to sabotage each other at every step. It's unfortunate for Rick and Microsoft that he announced before doing the job because the more he will do the harder the Wikipedia community will fight back.. OOps wrong copy paste. That response was meant to Dare's blog note here about this article: Sorry folks. - Sylvain Stephen: Actually, I haven't read any material from MS on ODF versus OOXML yet. My thoughts so far are unfortunately all my own.. Thanks for responding, but I don't feel like my question is quite answered yet :). >> "The OOXML specification requires conforming implementations >> to accept and understand various legacy office applications." >". Why didn't Microsoft create the OOXML file format so that it wasn't dependent on previous file formats?. I must say that especially IBM seems very intent on trying to create a smearcampaign against OOXML. (with of course Groklaw following IBM as always). I wish they would try and put their efforts in improving the ODF spec instead as at the moment I find it hardly workable to use the ODF spec for use in applications as it seems impossible to create compatible documents from just using the specs. (something in which OOXML also isn't great). The fact that odf fans just jump on any comment coming from IBM and try to add it in wikipedia is just pathetic. Both specs are at best moderatly workable and it seems wiser to let OASIS and Ecma first improve to the next versions in stead of trying to discuss the merits and flaws of both formats. People are actiing like standards are something solid and set in stone but actually development on both formats will continue for many more year so I think people should move forward more and if they think OOXML is flawed then come up with improvements and simular for ODF. Must admit I find Microsoft's move a little unnerving, but that's probably not too rational. I've no doubts about your integrity and I don't think that's undermined in this case by your being paid by an interested party, especially since you have publicly declared this. If anything, if ODF is better than OOXML (for any definition) then clearing up misinformation will be doing ODF a favour, because arguments can be based on solid premises. I bet there's also something of a (spontaneous, not-paid-for) counter-initiative, MS's move will add motivation to people wanted to clear FUD on ODF.. You're assuming OOXML and ODF can coexist with very different data models because they'll each be used within their own vertical isolated silo.. @Frank Daley, I stated, A technology company creating new technologies?! THAT'S JUST AWFUL! Think of the children! Your follow-up, However, your basic premise is wrong. Microsoft does not create open standards. It's so called standards are simply a set of specifications controlled by Microsoft. Maybe its just me, but I fail to see how me stating "technology" and you redefining technology to mean "open standards", can be used as "proof" that I have the basic premise wrong. Me: "The sky is blue!" You: "M. David Peterson has stated that the sky is blue. It seems he misunderstands the fact that the sky can not be candy apple red. The store was out of the color when they painted the sky." @Danny, "Is it then the case that OOXML can faithfully (reversibly) represent all the information possible in an ODF document?" I don't have the answer to this question, but I think it can be said that we both understand the fact that attempting to map one XML format to another, and do so without any loss of fidelity, is a difficult, at best, task to take on. I think of the task of converting RSS to Atom, and through experience know that even with an XML format as simple as RSS and Atom, its still near to impossible to convert directly between the two without at least some loss in fidelity. Of course, you could add a third layer to the mix (similar to what MSFT did with their RSS extensions for their web feed engine) and at least give yourself a fighting chance. But even then you are going to find at least a few instances in which are going to lose at least some fidelity during the process. @El Cerrajero, "Let's see, OOXML is a huge piece of crap. That's a fact." Okay, I see "That's a fact" that is preceded by an single statement of opinion "OOXML is a huge piece of crap." The only fact that I see is that you have an opinion, and from my experience that opinion is completely inaccurate. None-the-less, To Each And Everyone of You: If you are going to make an argument, please include not just "I think it sucks, therefore it does" but also "the reason I feel this way is because of reason X, Y, and Z." If nothing else, at very least it adds value to your overall argument, as opposed to its currently state of meaningless comment graffiti. Thanks! @Finite,). The audacity? Ahh, fair enough. Audacity is not a trait of mine that I see as anything but -- well, just me being me, and setting aside the fear of being scorned by some to instead state what I believe to be true interpretation on a specific manner. re: "He obviously missed the key word *neutral* in the thread's first comment, either accidentally or intentionally" No, I didn't miss it. What I instead chose to focus on, however, was the first point of credibility. Rick is the single most credible source on this planet, in my opinion, when it comes to the ability to provide a truly *neutral* perspective on standards and document formats. He himself has developed as ISO standard, is an insider to the ISO organization, and has proven time and time again that he is worried about representing the facts of each argument instead of propagating the FUD. In other words, his history of neutrality is a part of what gives him his credibility. Maybe I should have made my point a bit more clear, so fine, fair enough... I just did. s/manner/matter @Rick,. AMEN TO THAT! :D @Danny,. I think a lot of people are finding this to be the case, which means MSFT's job is to build a better, and therefore more attractive product in MS Office if they want to continue forward in the Office Applications vertical. If Office 2007 is any indication, I think they'll still be around for a while. ;) @Brad Eleven, -- "If O'Reilly pays me to write a book, does that mean the contents can not be trusted?" Yes, if the topic of the book is one in which O'Reilly has a financial interest. So in other words, if O'Reilly Media chose to publish a book on "How to publish a book", because they are in the business of publishing books, that book can not be trusted? Are you sick? Heaven forbid that anyone should ever have beliefs and morals while at the same time bring a paycheck home every week! Sorry, Brad, but you seem to believe in a world where morals and profit and mutually exclusive. I don't believe in the same world you do. -- "TECHNOLOGY IS NOT EVIL!" No, it's not. Neither are guns. Either can and has been wielded by human beings with evil intent, often in the guise of righteousness. So then because some technology can be used for evil, and some guns can be used to kill, should we then place a ban on *ALL* technology, and *ALL* guns in the off chance that someone might use either to cause harm upon another? Sticks and stones can be used to kill people, and the combustion engine can wreak havoc on our environment. Should we ban stick, stones, and the combustion engine too -- you know -- just in case? Brad > WAKE UP! Or is waking up and getting out of bed evil too? You know -- just in case something bad were to happen if you did? correction: "where morals and profit and mutually exclusive." should read "where morals and profit *are* mutually exclusive [of one another]." Wikipedia's Conflict of Interest guideline at says: If you fit either of these descriptions: 1. you are receiving monetary or other benefits or considerations to edit Wikipedia as a representative of an organization (whether directly as an employee or contractor of that organization, or indirectly as an employee or contractor of a firm hired by that organization for public relations purposes); or, 2. you expect to derive monetary or other benefits or considerations from editing Wikipedia; for example, by being the owner, officer or other stakeholder of a company or other organisation about which you are writing; then we very strongly encourage you to avoid editing Wikipedia in areas in which you appear to have a conflict of interest. Wikipedia's neutral point of view policy states that all articles must represent views fairly and without bias, and conflicts of interest significantly and negatively affect Wikipedia's ability to fulfill this requirement. It also says:. This is repulsive. You're admitting to becoming a paid shill for Microsoft. Isn't this in violation of Wikipedia's terms of use? While you're over there editing, why don't you check out the article on Astroturfing? I hope O'Reilly dumps you over this. M. David Peterson: the vociferousness and manner of your defense of Rick Jelliffe's decision and your assurances of his professional objectivity are having the opposite of the intended effect, and are quickly eroding my natural inclination to give Rick the benefit of any doubts on whether he can or will be objective/impartial. If it is important to you that he be able to conduct his work effectively, I suggest you just stop. Peter Yellman Simple question from me is will OOXML as a standard if I implement it allow me to read any compliant document or will people be able to produce tools that are "compliant" that are not wholly readable by another tool. If so how could it be considered a standard? @Peter, M. David Peterson: the vociferousness and manner of your defense of Rick Jelliffe's decision and your assurances of his professional objectivity are having the opposite of the intended effect, How so? And to whom? You? Why should I care, or in other words, why does your opinion of the effect they are suggest to me that I need to not stand up for what I feel is something worth standing up for. and are quickly eroding my natural inclination to give Rick the benefit of any doubts on whether he can or will be objective/impartial. Your natural inclination is to argue for the sake of arguing, Peter. Nothing I am stating throws any sort of red flag that could normally be seen as something to be leary of. And the simple fact that anyone can go in and re-edit his work means you don't *HAVE* to trust his work. If you believe it is wrong, CHANGE IT! That's the whole point with this! He has disclosed the MSFT connection, has pointed out areas of inconsistency, and has stated his plan to fix the areas that he sees as being incorrect. So wheres the problem?! If it is important to you that he be able to conduct his work effectively, I suggest you just stop. Ahhh, the old "throw in something that everyone should care about, to then throw in a statement suggesting that if I don't do this, that, or something else, this is proof that I don't care about the mentioned someting". "I suggest you just stop." Answer: NO! I will defend what I believe to be the truth, and will do so in my own very special way. If it gets to the point where it seems that I might actually be having the reverse of the intended effect, I will then look to rectify, if necessary, apologize, and then adjust as necessary as to not have the undesired side effects. At the moment, I don't believe this is what is taking place. Am I pissing a few people off because of my comments? Probably. But the fear of pissing someone off is not something that stands in the way of standing of for what I believe. So once again, NO! I will continue to fight each and every absurdity that I believe needs to be fought. END OF STORY! As a long time business technology consultant and consumer, I have very real concerns about OOXML standard from Microsoft, more from legal perspective - as expressed by leading "intellectual property" attorneys, who are quite skeptical of Microsoft's intentions and plans in this matter. Because Microsoft has invariably practiced unsavory, unethical (and illegal, in anti-trust cases) business operations regarding any technology that they did not own or control, even today in many creditable reports, I am loathe to grant them any consideration of their technology proposals/products until the company, including it's upper management demonstrates to my satisfaction - how ever long it takes - that it is a good corporate, national and international citizen. In the meantime no amount of PR, even hiring yourself as a honorable person, will make them less vile. One cannot purchase honesty and integrity. One cannot purchase honesty and integrity. So what you are suggesting is, a) you don't believe that Microsoft is honest. which, given the fact that a company is as honest/dishonest as the employees that lead and guide this company, would lead to, b) you don't believe that the current base of leadership is honest in their dealings which, if this were to be the actual case (and I don't believe that it is), the road to honesty would be firing the current leadership and hiring new leaders with a track record of proven honesty, correct? One cannot purchase honesty and integrity. Sure you can. You simply seek after people with a proven track record of honesty and integrity, offer them a job, and if they accept, *WHAMO*, you've just purchased honesty and integrity. "tz: Since OOXML is the native saving format for Office 2007, I don't know how you can say that it hasn't been designed to support all the information in an MS Office document? What magic captures the other information if not the file format?" No, Microsoft's extended and PARTIALLY UNDOCUMENTED version of OOXML is the native saving format for O2007. The entire point is that the 6000 pages submitted to ISO is NOT the complete description of what Microsoft uses as OOXML. Their "native format" includes all the artifacts, sidebands, quirks, idiosyncrasies, and hidden emulations (the "Do as Word 5 did" tags). To render a document with fidelity, you need to duplicate not only the 6000 pages of "the standard", but also all these hidden things which aren't in the standard. You call it "magic", but it is there. To use a more common example, there are plenty of magical things why a perfectly conforming page that is right in a perfectly conforming browser but won't render or work correctly in Internet Explorer - even version 7. So you either have to code differently depending on the browser, or make a page that will look bad in a correct browser. OOXML looks to be another cascading style sheet, javascript, etc. problem, only worse. Their "native format" is a fairly large (and maybe not even a proper) superset of what is in the OOXML spec. Or at least the "open" part. Wow, so many comments. Yikes. Just a quick point on Wikipedia procedures. First, I don't think what I am doing falls under the category of astroturfing in anyway: I am not faking a groundswell. I don't know why astroturfing was even brought up. Second, I certainly will look at the Wikipedia guidelines on conflict of interest, and I thank the reader who brought this up. Just because everyone else is doing something does not make it acceptable. If I were to summarize an article like this which I had written, it would read something like, "Microsoft offered me a big pile of money to do something I consider questionable. Please condone it." Sorry. You've already made your own judgment there. M. David Peterson: your comments basically boil down to "trust me, you can trust Rick". This doesn't work for me. A quick look at your bio should raise some questions for other readers as well. Your posts defending Rick's credibility, independence, what have you, coming as they do from someone who cannot but be described as an evangelist for Microsoft and it's technologies, lead me to the conclusion that it is Rick's credibility and reputation that Microsoft is purchasing, not so much his expertise. (I have a nagging suspicion that it was you who suggested Rick's name to Microsoft marketing!) Surely there must be people who actually work for Microsoft who are qualified to correct any "factual" errors regarding OOXML in the Wiki entry. That Microsoft has chosen to go this route is fairly convincing proof that it is not so much expertise that they are looking for, but credibility, and, were it not for Rick's disclosure, the appearance of objectivity. As for whether you should care what I think -- well then: don't! But as touting credibility seems to be one of your main objectives here, it seems to me you don't have much of choice. It's your box, live in it. Peter Yellman "But it is a good idea to put note up on my user page (I didn't know I had one.)" ... What does that even mean? Do you have an account? What is your username? "Child slavery is horribly evil." Indeed it is! I responded to that in your next blog post. Rick, I really hope you don't eventually announce you've decided not to do this because of Wikipedia policy or something like that. If your edits are valid then you should be allowed to be paid to edit, even if some Wikipedians will try and tell you otherwise. The reason you should not to do this is because successful standardization of OOXML will make the world a worse place, and why would you want to help with that for any amount of money? Rick: in order to avoid any apparence of conflict of Interest, I would either a) refuse MS's offer of financial compensation, but still contribute the corrections to Wikipedia; or b) publicly ask that MS send the money as a donation to Wikipedia. I have no fear that your contributions will be unbiased, but the amount of controversy this is generating should be a good indication that accepting money from MS is enough for the *appearance* of impropriety, which in turn can damage your credibility whether what you write is true or not. And, yes, I'm certain there are other paid contributors to Wikipedia, but just because the situation is widespread doesn't mean it's right... Making the corrections free of charge would send the right message both to MS and to its critics, I believe. M. David Peterson: No, I didn't miss it. What I instead chose to focus on, however, was the first point of credibility. What you chose to focus on? M. David Peterson: Rick is the single most credible source on this planet, in my opinion, when it comes to the ability to provide a truly *neutral* perspective on standards and document formats. Credibility which has now been blown away by virtue of the fact the he will be paid for what he writes by a company with a serious vested interest. Credibility now needs to be re-earned. I believe that's what someone was posting above and you're skipping around it. Read the Wikipedia guidelines for guidenace. M. David Peterson: In other words, his history of neutrality is a part of what gives him his credibility. Alas, you're straw clutching. His history of neutrality up until this point lends some credibility to what he's said in the past, but that history of credibility means nothing now that he is apparently going to be paid by a company with a vested interest. The fact that I am having to explain this beggars belief, but there you are ;-). A lot of his credibility over OOXML and ODF is blown away by statements such as: ODF has simply not been designed with the goal of being able to represent all the information possible in an MS Office document This is a load of rubbish. Pray tell, how would ODF go about defining information in a closed product defined by one company, and why on Earth should anything in a closed product by one company be defined as an ISO standard? What purpose would it serve? Since Microsoft Office is obviously a dependency of OOXML, I didn't realise Microsoft Office was an ISO standard, or that it adheres to any in a way which makes OOXML implementable, fully, outside of Microsoft's sphere. The ISO has guidelines for this stuff, and should be looked at. The issue is not whether OOXML is relevant versus ODF (although duplication needs to be looked at), but whether it should be accepted as a credible ISO standard at all. and one of the more political issues is do we want to encourage and reward MS for taking the step of opening up their file formats, at last? It is not the purpose of the ISO to be grateful to Microsoft, or anyone, in apparently opening anything. This statement is totally meaningless besides, because there is nothing to base the statement of 'opening up their file formats' on. Any given standard has dependencies, and those dependencies must not prohibit an independent implementation. As a result, any dependencies must be existing ISO standards (or the issue of reasonable implementation and existing standards looked at), or should co-exist harmoniously with existing standards and specifications that can be reproduced as faithfully as possible. For example: - OOXML's representation of dates and times conflicts with existing standards (this is a workaround for Windows and Excel built into the standard). - It even specifies a fixed list of language codes rather than look at ISO 639. - It refers to Windows Metafiles which cannot be implemented outside of Windows, rather than looking at specifying ISO/IEC 8632 or a reasonable W3C SVG open specification that third parties can and are implementing successfully already. - It implements it's own hash algorithm rather anything from the ISO or other standards groups, thus is unproven and uncertain. - It specifies English Metric Units, which appears to be its own definition of units of measurement. Needless to say, defined and accepted measurements in ISO standards are very important. - It uses it's own Microsoft Office namespace, which contradicts even the ECMA guidelines. this makes it poorer for archiving but paradoxically may make it better for level-playing-field, inter-organization document interchange. But the archiving community deserves support The list goes on, and he thinks that OOXML is better for archiving???!!! The only reason it is apparently better for archiving existing MS Office documents is because only Microsoft knows what's actually going on! That's an unbelievably daft statement. The issue of archiving existing closed and non-standard Microsoft Office documents is a matter for Microsoft, not the ISO. If Microsoft wants to open the format for those non-standard documents then that's fine, but whatever Microsoft produces must meet the needs of an ISO standard. The issue of archiving Microsoft Office documents is simply not of any concern. So, I'm afraid the possible payment from Microsoft in conjunction with his comments above adds up to not an awful lot of credibility. Sorry Rick, but I have to disagree. Standards that allow 'optional implementation' are no standard at all. The only way that such a standard is 'open' is that it is an open invitation for vendors to cheat. The problem that Microsoft has with ODF is obvious; ODF makes it more difficult to maintain their office products monopoly. No amount of sophistry is going to change that. Archiesteel: would prefer Wikipedia to remain NOT PAID FOR. Do you want to live in a world where the views that please the men with money become the loudest? I would prefer to live in a horizontal web of human beings. Again, what is the username (or IP number, if you don't have one) that you edit(ed) wikipedia with? Guys, I just want to jump in and point out that many of you are discussing something that hasn't happened. Nobody has offered Rick money to get their point of view into entries on Wikipedia. Instead, he was offered money to contribute HIS point of view to Wikipedia. I understand all the appearance-of-influence angles and so on -- I have a bit of a background in journalism, and these debates are timeless and always interesting to me. And the issue of Wikipedia's policies, which they're free to set, is relevant too. But when you start talking about people getting paid to enforce Microsoft's view of anything, you're off on a theoretical tangent. That hasn't happened in this case. Additional observations:............... The fact that you're telling us how non-Microsoft oriented you are before you get to your actual point rings alarm bells straight from the off, and I get worried every time I see it. Sorry. It may well be true, but there's no need for you to feel the need to dredge through your history to justify yourself, and one is then entitled to ask the question 'why?' For example, in the Wikipedia entry, it currently mentions that "the members of ISO have only 31 days to raise objections", the implication being that this is far too short a time; yet, if I understand matters correctly, ODF was submitted in a fast-track procedure Respondents have had a good few years (four or five I believe - OASIS has been open and worked on for a long time) to respond to the OASIS specification. Since it's already a standard that has been out there and the subject of significant review, the fast track process of the ISO can be warranted. How long has ECMA-376 been up for public peer review? How long was the ODF specification available to public review before being published as an ISO standard? Answer: One month versus eighteen months respectively. That's possibly something you can do some research on and update Wikipedia with ;-). You are no longer neutral in a dispute if one side pays you. Taking the money of one site makes you part of that side. If the article bothers you so much, you could have changed the wikipedia entry anytime, without being paid by Microsoft. But no, you didn't. So any change you now do is clearly motivated by Microsoft's money, and not by your desire to represent things in a neutral way. The paid shills of a convicted monopoly are everywhere, a lot of the time posting only once in a thread or forum to cause a trolling effect and move on to another subforum or forum and continue this effort. If they are successful enough, they will continue to participate and troll a thread for days, weeks, however long it takes to cause chaos. Generally only one troll post is needed to set the honest, caring Linux users up into wasting their time responding to what they think is someone with honest issues. On Usenet you'll notice many of the trolls speak with horrible English skills and almost always rely on the one-post-troll method. rweiler: Actually, there are many standards with optionally implementable parts. For example, in my standard, Schematron, I clearly state which parts are optional for a validator to use. (For example, the assert element is not optional, while the flag attribute is.) ISO 8879 SGML, the standard which XML is a profile of, even has a little configuration language (the SGML Declaration) to say which optional bit the document uses. Brian Jones has a specific post on the topic of optional compatibility settings at I mention it because several people have brought the subject up. As a quick summary, Brian quotes the standard (how serpentine!) It is important to note that all compatibility settings are optional in nature - applications may freely ignore all behaviors described within this section and these settings should not be added unless compatibility is specifically needed in one or more cases... and points out that ODF has an element config-item which application settings (such as compatibility settings) can be placed, and ignored by other applications. He saves an ODF document and finds one called "UseOldNumbering" for example. Now, since ODF has this element to mark up information that is optional or application-specific, do you therefore include it as "not a standard at all"? Now I think it is a legitimate question to say "well, maybe the ISO standard should not have these particular compatability bits in it, or just leave them for some other non-standard documentation" but that is a different issue to saying that a standard shouldn't allow optional information: ODF does too. But I think your comments have another flaw: that if OOXML becomes an ISO standard it will necessarily undermine ODF's progress. In fact, if they are differentiated whether by features or quality or purpose, then governments are perfectly capable of still mandating ODF if that is what they want. I just believe that the decision to choose ODF or OOXML or PDF or whatever is one that should occur at the user level, not at the ISO committee level. People know that an ISO standard has had a certain level of scrutiny and fulfills certain obligations as to format and availability and voting, but the decision as to which technology creates the best level-playing field is one for users to decide, not ISO. (It seems to be a kind of gay marriage argument: that if gay marriages are allowed, then it threatens straight marriage. But what if the straights keep on a-marrying {i.e. ODF adoption continues} regardless, while with different needs get what they need too (i.e., people who want to use standard OOXML)? Frank: I guess you missed the sentence "In fact, I already had added some material to Wikipedia several months ago, so it is not something new, so I'll spend a couple of days mythbusting and adding more information." What sponsorship gives me is the time to make improvements. I enjoyed the Slashdot posting on this thread: see Microsoft's Doug Mahugh responded, posting the text of the invitation to me, which is very gentlemanly of him. Which part of the API is enableDeathSquad(uuid) under? I can't find it in the documentation and I really need to straighten out some clients ... Finite. I now have the user name "Rick Jelliffe" but I have not used it. The old edits were not made with a user name: I don't know whether this is because I have been doing little misc. Wikipedia edits on an off for several years or why. Albert: Look harder, it is right there next to perpetuateChildSlavery() See :-) why didn't you talk about that issue *before* MS start to pay your bills? Will you act like a man and apologize for your apparent mistake? Christian: If you read my blog, you will see that I have indeed been talking about this issue for a lot of last year, on and off, and not always from a side favorable to MS or to ODF. And if you read the article you would see that I had previously edited the Wikipedia entries. So I suspect you are a troll. but why didn't you modify the wiki-pages by your own (before the MS-Money trigger)? if you are upset because of the pro-ODF entries, you can write your opinion without getting paid for it. now i can't believe your words. Ronald: Which mistake. I suspect you are a troll. Wendell: They want to pay me to improve Wikipedia's integrity, but you are talking about their integrity. Everyone: Please feel free to let me know if I write anything that operates by raising Fear, Uncertainty or Doubt. But that is not the same as just raising specific objective technical issues! You keep saying you've edited about this subject on wikipedia before, but you haven't given us the IP number you used so that we can see your actual edits... so I suspect you are a troll. And the question remains, why have you (still!) not corrected the things you pointed out in this blog post that you think are currently wrong with the OOXML article? Publicly stating that certain changes need to be made to a wikipedia article, without fixing them first or immediately thereafter, is the mark of a person who doesn't really grok the wiki concept. I ask again for a specific pointer to edits you've made previously. Finite: I don't think it would be prudent to give my IP address on an forum of antagonistic hackers! In any case, from my ISP it will allocate different IP numbers. One of them is on a page I made but that IP address seems to be been active for just a couple of days in late 2005. One reason I haven't started correcting the Wikipedia is dealing with these blog comments and the raising of whether it is appropriate under Wikipedia rules. (Which you also have helped resolve, I think.) IMO, no standard including ODF should allow optional features. That standards historically have provided such capability has in large part made a mockery of the entire process. That's not a huge surprise since by and large, the standards are made by vendors, and the vendors view the standardization process as just another way to gain a competitive advantage (ie ODF) or as an aid to derailing competition (ie OOXML). The difference between ODF and OOXML is that if OOXML is adopted, the customer loses because there will be one, and only one office suite that can properly read and write OOXML documents. You can take that to the bank. W/R/T to users choosing the 'best' standard, if the users are to decide, there is no point in having a standard at all. Slashdot makes me want to throw up. What's the deal with those guys? If it's any consolation Mr. Jelliffe, I believe you and Doug Mahugh have honorable intentions. understand, however I think it's important that the sponsor in this case not have a vested strategic interest in promoting OOXML over ODF. Of course, I truly believe that you would be objective, but should it become common practice for corporations to openly hire people to correct mistakes they feel are against their interest, it becomes a very slippery slope before independent "editors for hire" start following an editorial line dictated by whoever holds the purse strings. Wikipedia is supposed to be self-correcting by the contribution of its user community. If there are inaccuracies in the OOXML pages, then MS should trust the user community (which will undoubtedly have some people who are sympathetic towards them) to correct the mistakes. Anonymous: Thanks. Slashdot is just kids sounding off. Its funny. The thread on Slashdot is whether corporations should be abolished: it shows where the readers minds are at, which is fine. When you realize the juvenile level that some of the debate is being conducted at, I think you realize why I (and some ODF people!) think that there is too much FUD and smoke and mirrors in discussions about OOXML. I have no doubt that MS is just as capable as anyone to do FUD, but in this case I have to say that it mostly seems to be coming from some people on the ODF side. The Computerworld article is more serious, in my book: it suggests that I am exposing a scandal, or that there is something hidden and underhand going on. But that is so far from the truth that is pathetic. I've received a couple of requests to talk with journalists on the issue of paid editing of Wikipedia, but I don't expect they operate on Australian time so I have no intention of getting involved in those stories. I have been in contact with some Wikipedia volunteers, who I hope can help me do the right thing by Wikipedia. This blog entry is currently the most read of the OReilly blogs, I see. Probably the longest too. :-) You sucker Oh, now its in Infoworld too. That seems a lot closer to reality than the ComputerWorld article. And IT Business (crazy one this!) The debate over pay-per-Wiki will make the one over pay-per-blog-post look trivial. I particularly appreciated the line What Microsoft has done is not necessarily bribery. What kind of a moron writes that? What Microsoft has done is not necessarily arson, incest or baby-snatching, either. I could find your article throw some spanish references: (slahsdot spanish version) (technology section of one of the most important spanish newspapers, the link to your article is broken) it seems that you will have more repercussion than expected because the title of the newspaper article says: "Microsoft busca mercenario que hable bien de ella en la Wikipedia", that means: "MS looks for a mercenary to "talk well" about the company in Wikipedia" what a success :) S: In what way? Alberto: Mercenary? But then a journalist wouldn't know the right word for someone being paid to edit information to be neutral and balanced, would they? :-) At least based on the evidence of the articles so far. The thing is not that something wrong has been done, its that nothing has been done! I haven't edited anything, I have been completely transparent, MS encouraged the transparency, when we found out about the Conflict of Interest guidelines at Wikipedia we have been talking to them about how it applies, yet these articles present matters in terms of some vast conspiracy that has been uncovered. Shoot the messenger? Rick, This series of posts will teach you not to mention "Microsoft" in public again. You've now seen firsthand what people with more time than brains do to make themselves feel important. Don't worry, they will forget you quickly and move onto another perceived scandal. Good luck with it. rob weir must be so busy blogging against OOXML, he still has not found the time to read about XAML or even try to understand what it's about... just keep the FUD going. obviously, there's nothing wrong with FUD as long as it comes from the right camp. sad. @Sege This is a load of rubbish. Pray tell, how would ODF go about defining information in a closed product defined by one company, and why on Earth should anything in a closed product by one company be defined as an ISO standard? What purpose would it serve? Well everyone seems to be just fine with PDF as an ISO standard, yet last time I checked, Adobe still held firm to the claim that standard or no standard, it certainly was within their rights to maintain control over who could implement support and who could not. So answer me this: What good is an ISO standard (which PDF is), if you are still required (as in the case of Adobe vs. MSFT, in which Adobe will not allow them to implement direct support distributed as part of Office) to ask permission to use it? re: grasping at straws: The only grasping that is taking place in all of this is though of you who insist that there is still something wrong with all of this. What I find striking is that no one is contending the fact that there exist gross errors and misrepresentations of Open XML on its Wikipedia page. So the argument isn't "Wikipedia is correct as it stands" and instead "How dare you even consider being paid to make corrections!" Maybe its just me, but shouldn't the *REAL* concern be within the confines of "is the Wikipedia page correct? If no, shouldn't someone who knows where the errors exist, and how to fix them, do just that?" I mean, that's what Wikipedia is attempting to do, right? That is, provide a true representation of any given person, place, or thing to the best of the knowledge of the people? Or should we just call it what it is: "The Peoples Tabloids" Hi Rick, how funny to see your name appear on the blogosphere! Talk about trying to drag the wrong person into the middle of things... :-) James So Mr Jelliffe, you are willing to edit facts that you consider wrong on some wikipedia page, but are perfectly fine with what is in my view just as wrong, which is all what those pages omit to say. Do you think "lie by omission" is ok? If you accept money, and find that lie by omission is ok, then your credibility is zero, right? A refresher : Let us know when you are ready to edit the wikipedia page, and add the fact that the specs are in spirit the same kind of questionable specs that Microsoft used to distribute for older binary file formats in the past. In other words, nothing that can in all fairness be called a standard. Or perhaps you think that's FUD too. @Peter, I don't know whether I should laugh, cry, or cry from all of the laughter that preceded it from all of the effort being made to find some sort of "evil connection" with all of this. Here's my favorite part, (I have a nagging suspicion that it was you who suggested Rick's name to Microsoft marketing!) Wow! As if that would even be required to bring Rick Jelliffe's name to the attention of the "All Mighty Eveel One" itself, Me: "Oh, Dear All Mighty Eveel One: I present to you "Rick Jelliffe" who I believe can be converted to your Eveel Ways! MSFT: Uh, three questions, 1) Why do you keep calling us "Mighty Eveel One"? 2) Yeah, we are quite aware of who Rick Jelliffe is, but yeah... thanks. 3) Who the hell are you, anyway, ya phreak, and how did you get this phone number???!!! Go away, you're scaring me, my wife, and you just made my seven year old burst into tears from that "scary sounding man on the phone!" She's going to have nightmares for weeks, you jerk! "Click." Me: Hmmmm... That didn't goes as well as I had thought. Me: Damn. --- So my bio states that I specialize in XML, XSLT, C#, the .NET platform, and in functional programming languages such as Lisp and Scheme. Of my six mentioned specialties, two of them have direct ties to Microsoft, the rest representing a base set of fundamentally cross-platform technologies (well, XML and XSLT (which is an XML-based language) are fundamentally cross-platform. Scheme and Lisp just happen to have implementations on a majority of the platforms in existence, making them cross-platform by default.) Question: So does this mean that anybody who happens to know a thing or two about C# and .NET is "suspect!"? Yikes! That's like 10 million developers... That's a lot of suspects! The other "connection", apparently, is that I began my career working as a *contractor* for Microsoft. Just to set things straight, I have never, nor will I ever work for MSFT or any other corporation as a full time employee, unless that corporation happens be one in which I am a founding member of***. Why? Because I like my *independence*. I enjoy the freedom of being able to call my own shots. Of course, nothing I say or do or anything of such sort will be enough to convince the conspiracy theorists out there that there is something evil going on. Oh well, conspiracy theory away, my friends... Conspiracy theory away. --- *** Of course, if a corporation I was a founding member of were to be purchased by another corporation, that would kind of null and void this statement. Not that I can foresee this scenario ever taking place, but if it were to take place, I would hate for something like this to be used against me in the court of public opinion, something I am beginning to understand it for what it truly is. Whatever "the people" say it is, regardless of the facts and/or circumstances at hand. Oh well, so be it... Since you've not yet responded to my last observation - that Office 2007 is a (possibly not propers) superset of what is IN the OOXML spec, I would like to add something I missed. The specification indicates that undocumented, nonstandard, or proprietary formats be used, e.g. VML or Windows Metafiles. Office 2007 knows how to handle these, but are they part of a compliant OOXML implementation or not? So when archivists and others using something which perfectly implements the open and public portion of the spec see a big box with "unsupported Microsoft proprietary feature" instead of a graphic, that would be OK with you? And if OOXML won't allow interoperability with Office 2007 (and later), why bother implementing it? Or would you be willing to call Office 2007 a NON COMPLIANT implementation so could not be used for storing OOXML archival files (they would need a converter to strip or fix the proprietary junk, EXACTLY like they need a filter to load or save ODF)? Good show, kill the FUD. But take care you don't get hurt in the process! Your apologetic tone in taking up Microsoft's illogical defenses of their monopolistic practices of platform lock-in is most unfortunate. It makes a strong point other than the one you are trying to make: that despite any demonstration of abilities and skills in unbiased logical analysis prior to this, your analyses and motives will from this point on be suspect as corruptable by corporate money. There is no return to grace. You'll join the Exxon Global Warming shills in the list of sell-outs to corproate greed. What a shame. I'd advise you to back out while you still have some semblence of character left. What is driving your need to become a Redmond shill? Is business that bad? Why pay someone else to clear something up when you are (legally) right on this? tz: Whether what Office 2007 is compliant with Ecma 376 can be primarily tested by validating the files using the schemas and by generating other files according to the spec and seeing whether it accepts them or not. All standard XML formats of any sophistication allow extensibility, whether by allowing elements in different namespaces (as ODF does, IIRC), by having open content models, by having open-ended attributes, and so on. And every time there is extensibility, you need special systems to support anything other than generic operations. XML formats with any history are also prone to having deprecated elements and attribute values. Neither XML Schemas nor RELAX NG, as I understand them (and I was on the working group for XSD at W3C), really allow arbitrary injection or removal of elements. So there are solid technical reasons why a schema coming in from industry might include deprecated parts. When you don't have extensibility or a deprecations, then you could have guaranteed interoperability. When you are in a different position, you have to define a profile and behavior in order to get there. XML itself is a case of this: all parsers are required to accept UTF-8 and UTF-16 but all other encodings are options. There is no guarantee of data interoperability with XML, unless you use UTF-8 or UTF-16. But the availability of the other encodings allows vendors to differentiate their products and, most importantly, makes it convenient for users to on-ramp their data into XML systems. Absolutely no-one on the ISO SC34 WG1 working group will be surprised by a data format that is extensible and which therefore allows odd media types that may not even be enumerated. In fact, I am the editor of an ISO standard called Schematron which is all about allowing a separation between highly permissive schemas (e.g. using XSD) and highly restrictive profiles (which guarantee or promote application-level interoperablity). It is an issue that there is very little sophisticated recognition of; people want to adopt a standard (a schema) and ignore the necessity of having a profile. So yes yes yes, I would be very surprised if either OOXML or ODF didn't allow extensibility, and the solution is not to blame them but to recognize their place in the food chain: I have mentioned several times in my blog or XML-DEV that government organizations interested in interoperability need to utilize profiles. See my blog Great Irish Government Subsets of XML Standards for a good place to start. So I would distinguish the cases of extensibility (different media types, legacy formats, legacy data import envelopes, open ended attribute values, etc.) with cases of current binary formats. Now I have not had time to check up the current status of Stephane's reverse engineering of the .bin format in Office 2007, as in But it is low on my list, because that relates more to Office 2007 than to OOXML, it seems to me. Can I suggest a different angle? If OOXML is standardized through ISO, then that gives an independent conformance test to judge MS by. If they don't conform, government purchasing can reject them, in favour of Word Perfect, or OpenOffice, or whatever. Standardization shifts the power to users away from vendors. Why not take the deal! The only reason I see: You can make more money publicising this all over the web, then install google adsence and make more money! To: M. David Patterson [QUOTE] Since when, in the history of the entire planet, has *ANY* generation been able to sit still and be happy with what they already have, and have been happy to simply just "work together as a community for the greater good of everyone." [/QUOTE] I suppose you're employed very productively in an organisation that works exclusively on inventing the new wheel? Of course that is because you firmly believe that your new square (or is it polygonal? perhaps orthogonal?) wheel is a million times more efficient and effective than the silly existing round wheel. And of course you believe that to use the existing round wheel would be nothing short of communism! God forbid the world be communist! I completely understand, you poor lost, lonely soul. [QUOTE] All standard XML formats of any sophistication allow extensibility... [/QUOTE] Surely you mean the extensibility of the bit-mask? And surely mixing said "extensible" bit-mask technology with XML provides an excellent, human-readable, extensible solution eh? And I suppose, you also mean re-inventing the wheel is a MS(tm)GoodThing. I mean why on earth use SVG when you have the opportunity to invent MSVG (or is it called VML?)? And it must be a MS(tm)GoodThing to encode legacy cruft in a new standard? You must sincerely believe that the sole intention of this MS move is to enable even the oldest documents ever created in MS Office to be accessible and readable to all implementors. Of course no implementor other than MS could legally and openly implement such vaguely defined "compatibility". But why should that bother you? And what about requiring implementors to handle 1900 as a leap year? That has to be a MS(tm)GoodThing, right? Why use the ISO date formats and the Gregorian Calendar when the MS(tm)Calendar has mandated that 1900 be a leap year? An interesting view on standards, I must say. G Fernandes: Two points. First, I don't see how the subject of bitmasks comes up when talking about extensibility. There are only three different uses of bitmasks that I can find in the Ecma spec: one is to do with metadata for file choosers, which hardly seems earthshaking, one is concerned with conditional formating in tables: inline signals that the current cell has odd-cell formatting for example, and some strange thing to say whether a native table in a presentation has bi-directional text. These would add about a minute to a programmer's time to handle, over having separate attributes. I agree they are ugly, but certainly in the table cell case I can see why they might be justifiable for filesize reasons. Second, Groklaw and the other sites are wrong when they claim that bit-masks cannot be validated, e.g. using ISO Schematron. I've posted code to the Schematron-love-in mail list using division, and Ken Holman also has some XSLT code using mod on his site. Furthermore, for schemas for large data sets it is not unusual to have terse markup, for entirely practical reasons. This isn't made for toys, but potentially for documents with hundreds or thousands of pages. It is consistent with the super-terse element names. I read that the famous chef of el Bulli near Barcelona has a desert made of foam frozen in liquid nitrogen. It looks like solid block but as soon as you touch it, the whole thing just evaporates and disappears. The horrors of the bitmask seem to be the same. G. Fernandes: Actually, VML came out before SVG. See That OOXML uses VML and not SVG is yet another reason why ODF is more suitable for level-playing-field data exchange and for organizations to mandate (and profile) for that use. (Corrected 2007-01-25: "not" missing, sentence made no sense) Rick Jeliffe wrote: "That OOXML uses VML and SVG is yet another reason why ODF is more suitable for level-playing-field data exchange and for organizations to mandate (and profile) for that use." Rick, Why are you stating that OOXML uses SVG??? The article you linked to doesn't even claim that. Are you sure you've researched the topic, Rick? Have you read this document: To save you 2 minutes of google and searching the pdf, here's an extract: "Examples of existing standards not used in OOXML include SVG for drawings and MathML for equations. Instead, OOXML "reinvents the wheel," creating unnecessary complexity for programmers." Rick, what's next in your mission to cleanse Wikipedia? A new improved history of XAML?. bene bene male male Your main point seems to be this: ." From what I can tell, you are thouroughly mistaken on that main point. ODF has, in fact, been designed to accomodate everything known to exist in Microsoft formats.;title=OpenDocument%3A%20Fully%20supporting%20legacy%20MS%20Office%20documents%0A&type=article&order=&hideanonymous=0&pid=528990#c529349 This fact is attested to by this blog about the daVinci plugin. Read it, and understand it, before you attempt any *cough* corrections *cough* on Wikpedia entries that are not, in fact, incorrect. I'm afraid to say, Rick, it is you who is incorrect. Mike: Sorry to confuse you. I missed out a "not" in that sentence and it made no sense without it. I've corrected it now. (I need a good editor!) Press update: This has now made it all the way to CNN Jeliffe wrote: "Mike: Sorry to confuse you. I missed out a "not" in that sentence and it made no sense without it. I've corrected it now. (I need a good editor!)" Thanks for the apology, Rick. And the correction. And the deft use of irony to introduce a little humour to this discussion. Would you care to share your views about the heart of the matter we are discussing now? I think it goes to the core of the reason why so many people are expressing dismay about the prospects of someone with your reputation and skills contemplating accepting money to edit Wikipedia for Microsoft. (I'm not saying you have accepted anything...). We were talking about Scalable Vector Graphics (SVG), which is an open standard for web graphics from the worldwide web consortium (the people who invented the web and who define what HTML is). SVG is the result of years of dedicated work by leading engineers, designers, artists and business people from the world's leading software companies, manufacturers and publishers to standardize graphics on the web. Microsoft participated in the standards process, but never implemented SVG in Internet Explorer. Why do you think that is? Lack of resources? Lack of importance of vector graphics? Lack of demand? Now fast forward to 2007. Microsoft's new Vista operating system features... scalable vector graphics. But wait a minute... the graphics language Microsoft found time to implement is not the worldwide web standard SVG... it is a new variant that has the same functionality and technical merits... but slightly different syntax, and a new name, XAML. Why do you think that is? Could you explain to the lay community (tuning in from CNN now) the significance of a slightly different syntax? Mark: "Would you care to share your views about the heart of the matter we are discussing now? " See my blog "Wikigate!" at Also "An astounding offer" at OK, so Microsoft doesn't intend to constrain what you write in any way, and they'll pay up front, so aside from a certain feeling that it's not quite right to take someone's money and then harm them, there's no constraint on what you would write. It doesn't look good, because it's impossible for anyone else to tell whether being paid has impacted your objectivity, and it's also impossible from outside to tell whether there are informal guidelines in the relationship that we're unaware of. But there's no actual constraint. But, pardon me for asking, what if they do it again? At that point expectations of future money begin to be set up, and there's a subtle but real (and if the media in general is any guide, quite practically effective) awareness that if you write stuff they don't like, you don't get hired again. That would to a moderate degree be a constraint. Can Wikipedia users be fairly confident that this is a one-shot? Would you change your views about the appropriateness of this behaviour if it looked as if Microsoft intended a longer term or repeating arrangement? Personally, there's no way on earth I would accept money from Microsoft in specific to do anything that would influence opinion in any way, even if in general I didn't have a problem with the idea of something like this Wikipedia gig, simply because I'm too well aware of many, many instances of Microsoft's massive untrustworthiness, aggressiveness, and propensity for unscrupulous schemes. No matter how much a proposal seemed on the up and up, I would find myself wondering what goals it really served beyond the obvious, and have no confidence whatsoever in my ability to determine them. Indeed, one side purpose may be precisely to undermine the credibility of a pesky open standards advocate. All I know is that the corporate graveyards are littered with outfits who co-operated with Microsoft under the impression that they could profit from Microsoft's enlightened self-interest. Rick Jeliffe wrote: "Mark: "Would you care to share your views about the heart of the matter we are discussing now? "" "See my blog..." Rick, my name is Mike, not Mark. The blog entries you link to don't address the questions I asked you. Rufus: I think MS knows that, in order to win this one, they have to win it fairly and on its merits and with transparency. They have a lot of suspicious eyes on them. Which makes them very susceptible to FUD but it is not a weapon that would do them any good, in this case. It certainly is an ironic position for them to be in, and unimaginable for some people, but not a dishonorable one, nor that bad for the rest of us IMHO. The trouble here has been caused by too much transparency, paradoxically. I should have researched up on the Wikipedia guidelines and raised the issue on the Wikipedia talk pages before mentioning it on the blog. Newspapers picked it up and ran it as if there were a conspiracy uncovered: "Writer asked to write" is a boring headline. The original version of the blog had me asking readers "What do you think?" but I took it out because it sounded defensive and I had nothing to be defensive about. Then newspapers interpret it as me whistleblowing on MS, then they take the conspiracy theory angle that somehow I have been found out, then they startle poor Wikipedia people who blurt out the general policy, and then this becomes some kind of war between MS and Wikipedia, and it gets syndicated and today it is lead article on CNN technology section. But in the private mails I have been cced on between a Wikipedia person and an MS person, there has been nothing but civility and mutual understanding, which is different from resolution of course. This is the kind of thing that can be sorted out. You're assuming you know what they want and what they are trying to win. Consider Microsoft's deal with Novell; it's win-win for Microsoft. Either they create some good FUD about Linux's legal liabilities, scaring people away from distributions other than Novell, or they taint Novell and get rid of a competitor. If they're lucky, maybe both. Novell thought they knew what Microsoft wanted and what they were trying to win; whether or not they do OK out of the deal, it is unlikely that they were right. [quote]Since you openly admit to being paid my Microsoft you immediately destroy any credibility as a neutral commentator. End of story.[/quote] Not being paid, asked to be paid. That's fundamentally different. [quote]there is also a sea of crap being produced[/quote] Yes, like false emails, it's called 'junk mail', must be something new for you, right? Like dream on. My dream? Work for microsoft! Rick Jelliffe, there are literally hundreds of people all over the web attesting to the fact that ODF format can (and in actual fact does) cover all of the Microsoft legacy format capabilities. : * OpenDocument as the Perfect MS Office File Format: How to: Add native file support for OpenDocument to Microsoft Office. * Running on OpenDocument Inside of MS Office: Perfect Conversion Fidelity & The daVinci OpenDocument Plugin for Microsoft Office.. " Mr Edwards is the person who wrote the original post on Groklaw. Here:;title=OpenDocument%3A%20Fully%20supporting%20legacy%20MS%20Office%20documents%0A&type=article&order=&hideanonymous=0&pid=528990#c529349 Gary should know, because he has in fact done it, and demonstrated it. For real. To governments. Gary says: " It's absolutely true that ODF can handle anything that MSOffice and the legacy of billions of binary documents can throw at it. This includes the years of line of business applications dependent upon MSOffice, the critical day to day business processes built onto the MSOffice platform, and even the low level assistive technology add-ons problematically layered into MSOffice. ODF handles these issues in much the same way as MOOXML, with equal fidelity. " He also says this: "The larger, more robust, more capable ODF can handle MOOXML - MSOffice tasks with ease. We can't however do the reverse. We can't "fit" all that ODF can handle into the comparatively constrained and limited MOOXML." !!!! ODF is the larger, more capable format. ODF can handle OOXML, but OOXML cannot handle ODF! These are the facts, Rick. The daVinci plugin proves it to be so. Para creer que la propuesta de Microsoft no es ética hace falta carecer de dos cosas: inteligencia y sentido de la realidad. Wikipedia es uno de los sitios más visitados de Internet y es lógico que una empresa que tiene los medios para hacerlo, cuide su imagen en este sentido. Lo malo es que con este panorama, si Wikipedia dice que el almacén de la esquina de mi casa vende huevos en mal estado, pero no es cierto, dificilmente alguien haga lo mismo para corregir ese error, aunque si lo dijese de las hamburguesas de Mc Donalds, pronto se encargarían de corregir el "falso" dato. Por lo visto, y paradójicamente, Wikipedia podría convertirse en un portal publicitario para las grandes empresas que pudieran pagar por el "mantenimiento" de rigor, y hasta incluso por tener mayor cantidad de referencias relacionadas con sus productos y/o servicios. Ya era hora de que se convirtiera en una enciclopedia verdaderamente democrática... No? [QUOTE] That OOXML uses VML and not SVG is yet another reason why ODF is more suitable for level-playing-field data exchange and for organizations to mandate (and profile) for that use. [/QUOTE] Thank you for your clarifications. And thank you also for making your position clear (fair/impartial v/s ardent OO-XML proponent). I'll answer to both your comments in this one reply. 1. While bit-masks are not horrifying per-se, they are a maintenance nightmare. So I disagree with you that a few bitmasks here and there are "ugly, but ok". The code for handling bitmasks is always a maintenance nightmare. And the use of bitmasks in XML is baffling to my simple mind. I can conceive no situation that couldn't be solved otherwise, in a cleaner and more elegant manner. That aside, this is a great example of defining a "standard" around an "implementation". This, in my experience, is a bad way as it necessarily limits the people building the standard to one implementation. Contrast that with attacking a general problem in the abstract and formulating a generic solution to it. 2. While SVG may have been born later than VML (or XAML - and MS's behavior in pushing XAML is an important reason why OOXML should never be allowed to become a standard), the fact remains that SVG is the W3C standard and MS seems intent on somehow subverting the standard and presenting a proprietary, Windows-only replacement that "looks" like a standard, but really is proprietary. Vendor lock-in has been MS strategy since time immemorial and, while I have great respect for your integrity and your fairness, I have no doubt that the sole reason for pushing OOXML is to subvert standards and retain MS Office format lock-in. MS tried this stunt with Java and (fortunately for the world) failed. While your intentions are undoubtedly honorable, the fact remains that MS is an incorrigible monopolist. It MUST be stopped. Forcing MS to play fairly with ODF will be an important achievement for all consumers of office suite software. I agree with you that FUD is not the way to do this. But I am also of the view that creating a standard against a (provably flawed) implementation is not the way standards should be created. MS is the person on death-row that is pleading for a 10th and last chance to change itself. One must remember that although one might not have been directly affected, or even around at the time, MS has abused all the previous 9 chances. It is now time to execute the sentence. Here is some other interesting info that can be dug up about Microsoft and their recalcitrance when it comes to ODF. Find the text on this page:;title=OpenDocument%3A%20Fully%20supporting%20legacy%20MS%20Office%20documents%0A&type=article&order=&hideanonymous=0&pid=528990#c529349 "But hey, this issue itself could have been dealt with back in 2002, when Microsoft first joined the OASIS Open Office XML TC. Sadly they chose to the quietly secretive role of "observer", never once breaking their silence with some measure of participation or comment. Not once. That's not to say Microsoft wasn't well represented on the ODF TC. Some of the greatest reverse engineering experts in the world worked on ODF, including Stellent's legendary binary file format expert, Phil Boutros. I often wondered if there was actually anyone working at Microsoft who could match his knowledge of their legacy file formats." Given all this, and given the fact that 100% perfect round-trip interchange between Microsoft legacy formats and ODF can and has been achieved, I think it pretty much kills any chance that your thought that "ODF has simply not been designed with the goal of being able to represent all the information possible in an MS Office document" is totally wrong. Microsoft simply assert (without any proof whatsoever) utterly false positions such as "ODF has simply not been designed with the goal of being able to represent all the information possible in an MS Office document" so that they can then say "we won't support ODF, instead we will submit our own format for approval". Give it up, Rick. Microsoft's bluff has well & truly been called here. Microsoft's OOXML format is an utter sham, the sole purpose of which is to try to undermine the fully open and fully capable ODF format. G. Fernandes: No, standards are dealt with on their own merits at ISO, not the merits of other acts of one stakeholder in a standard. ISO committees are not anti-trust courts. That is not the way it works. On the subject of Java, of course you would remember that Sun was going to standardize it through ISO, then pulled out to keep it proprietary. They instigated the JCP as a way to keep control of their baby. That is their right, but in doing so they lost the ability to say to MS (when it pulled the J++ stunt) and to IBM (with the SWT stunt) "Oi, you should be following the standard!" On the other hand, the presence of two "standard" graphical languages for Java has lead to a richness for users as well as a wasted duplication of effort: the calculus of benefits and costs is not as simple as the mono-culturalists would have you believe. All these big companies play hard, and adopt standards or not as suits their advantage; that is OK, ISO is not designed to hinder competition, even self-defeating competition, but to facilitate agreement(s) fairly. Mark: (Sorry about the name confusion earlier.) It doesn't matter how many parrots say something. We can look at the ODF committees records: they are online at Their search engine wasn't working for me, and when I tried Google it had not indexed all the entries. (The search on Google revealed two mentions of Microsoft in 2006. One of them was a discussion on what to do when Microsoft tried to interfere and block ODF at ISO...of course, MS did no such thing, it let ODF through entirely without a campaign, almost without a whisper...I was attending ISO meetings at the time so I remember it was very interesting...but now the ODF people are doing exactly the kind of thing that MS didn't do. Don't be fooled that these are guys who care about gentlemanliness or other fluffy goodness.)? There is a 'fork' of wikipedia's policy which disallows original content to be authored and posted: One can post non-neutral point of view wikipedia-like articles on wikinfo.org then link to them from the wikipedia entry. Microsoft in this case should be able to post their own point of view without hiding the fact, thus preventing edit wars and its consequential coverage in online news and the blogosphere. Rick, I'd go ahead and write what you think needs fixing. Half the people commenting on this say people can just correct you anyway, according to them... The other half think bad information should not be corrected because their football team is "Open Source" not "Microsoft". No amount of logic will sway them from their opinion (team) because they aren't in it for objective information. They are in it to stick it to the man, the "evil empire", the big bad corporation. (The other team.) Whats wrong with Open Source vs Microsoft, etc and for that matter our electoral process is that many people stop mentally participating and it just degenerates into a my team vs your team debate with little objectivity. Either you will be able to fix you think is wrong or you won't. If you can't, Wikipedia becomes nothing more than a sounding board for misinformation and opinion. If you can, by all means, let Microsoft pay you for your time only and not biased information and praise. If you do that, Wikipedia and you will gain some credibility. If you let Microsoft pay you to put out misinformation, you both lose credibility. So keep your objectivity, and do the right thing. It's really a bad idea to accept this offer! I think that wiki was not a website to be paid to write some article for a compagny and be paid for this. Wiki was an encyclopedia for everyone and made by "normal" person. Not by a guy who want to make some money!! PLEASE, don't accept that and Wikipedia must do something to counter this kind of thing! An simply surfer. I'd like to reply to Finite who wrote: think that this is correct, except that the disclosure would need to be on wikipedia, not on this site. It's only meaningful if the reader of wikipedia knows that what he or she is reading is a paid comment from a contracted employee of MS. Since posting to wikipedia is anonymous (how many readers would bother to check the user page?) there is no way to make this disclosure, without which the posting would be completely unethical. Unfortunately (Fortunately?), the media coverage of this has opened a can of worms that is shining a very bright light on the whole issue at hand: How should competing ideologies exist in Wikipedia. The nature of the Wikipedia beast is that the mob wins. A good example of the kind irrationality that is going on can be seen in the comments of this blog entry: GASP! Microsoft Caught Trying to Change Wikipedia Entries Update. See What actually is Wikipedia's guidelines for conflict of interest? I'd like to thank all the emails and comments of support I have been sent in the last few days. People can see through a media beat up, or at least, through this one. I wonder what Alexis de Tocqueville would think of this case. Not so much the ISO clarifications but just the idea of paying a person to edit an entry on one of the best examples of a democracy (and not to confuse with capitalism) ever displayed to a world audience. Wikipedia is designed and built with all intentions of peer-reviewed and maintained community. The MSFT idea falls under an axiom of economics (Howard S. Piquet):The Pursuit of Self Interest. If you want a capitalistic based information-community, go to godaddy.com, register/build a website for that very purpose. Leave the pure democratic qualities in Wiki please. Rick Jelliffe wrote: ?" I hope I can clear up some confusion for you here. The Gary Edwards daVinci plugin is explained here: It is a plugin for Microsoft Office. Microsoft Office already understands the old legacy binary formats, and can read those formats into the office applications. The daVinci plugin can then save the internal contents of Microsoft office applications (ie, the current document in memory) in ODF format ... with perfect fidelity. It can ready the ODF files back in again, and they can be save back as legacy formats using the normal Microsoft Office saves. The point is, the documents survive this "round trip" perfectly. 100% intact. This proves the point that the ODF format can handle anything (any formatting, any data) that legacy format Microsoft documents can contain. If you think about this fact for just a moment, it also shows Microsoft were not correct when the refused to support ODF in the first place, giving as their reason the "ODF cannot support our legacy formats". That claim was not correct. ODF can support their legacy formats. As for the bit about the legacy binary bits being still present in OOXML, and why that is a bad thing, please understand that it is a bad thing for competition. The daVinci plugin still uses most of Office to decipher legacy format data. This trick therefore still requires most of Office. Hence, keeping the legacy formats in any way, including as binary blobs within OOXML, still precludes and competing Office applications from other vendors. The legacy formats are still not vendor neutral, and they never will be. The best transition then at this point is for the world to move as one to ODF formats. These are the more capable of the two formats, and the more open and unencumbered. The ODF formats are proven to be able to store all of the information in legacy documents, and the daVinci plugin plus a copy of Microsoft Office gives us a tool to convert all legacy documents to an open, unencumbered and vendor-neutral XML format in ODF. Finally, I'll finish with some quotes from the linked page, just to hammer home the crucial point: that ODF formats can handle everything in legacy documents, despite Microsoft's false claim they cannot. Please bear in mind as you read this how thoroughly it all undermines Microsoft's whole rationale for submitting a new proposed standard which heavily conflicts with the existing approved standard ISO 26300. Now for the quotes: "The OpenDocument format ("ODF") is able to handle anything Microsoft Office can throw at it, and handle it at least as well as Microsoft's new EOOXML file formats. That includes the bound business processes, assistive technology add-ons, line of business dependencies and advanced feature sets unique to various versions of Microsoft Office. " "Full fidelity is a term used by the file conversion congnoscenti. It refers to the quality of conversions from one file format to another. Full fidelity means the conversion from one format to another cannot result in data loss. If data loss is possible, for example depending on what software features are invoked in a given document, then we refer to the conversion as lossy. For example, there is the always problematically lossy and always one way-only conversion of a Microsoft Word 97 binary file format (.doc) to a Microsoft Word 2003 binary file format (.doc). There is also the common file format conversion of a Microsoft Word binary .doc to Rich Text Format ("RTF") and back. " "For our purposes, we are concerned with the fidelity of file conversions between OpenDocument and binary files bound to Microsoft Word versions from Word 97 to Word 2007. Microsoft is able to perfect a full fidelity conversion of those same binary documents to and from EOOXML, using the Microsoft XML compatibility pack plugin. We argue that the same full fidelity of conversion is possible between Microsoft Word and OpenDocument, using the daVinci plugin for Microsoft Word. In fact, the process of how this is done is very similar to that used by the MS XML compatibility pack." "Enter daVinci. The conversion of binary documents occurs at the headpoint of the process, Microsoft Word, and it is full fidelity. No need to waste expensive human attention fixing conversion artifacts. " "To exchange documents, participants first have to synchronize the versions of Microsoft Office used to produce these usually compound and data centric transaction instruments. They call it version madness in that there is no way to exchange Microsoft Office documents without first having everyone involved using exactly the same version. Meaning, the quality of fidelity conversion between different versions of MSOffice is a killer. Data loss occurs unpredictably. It is unacceptable." "However, try to convert one of these documents, and risk dropping formulas, data bindings, rules based routing, or workflow scripting, and the whole process will come to a screeching halt. As it should. This is but another way some proprietary vendors lock in their customers. If you can't do a full fidelity conversion, and be confident of the results, the only alternative is to turn to a single vendor and year after year pay the price." "When Massachusetts put out their request for information, as it happened we were only an installation program away from our first ODF 1.0 compatible plugin for Microsoft Word, the most heavily-used application in Microsoft Office. In June Massachusetts sent us our first set of 150 primary importance test documents. We sent them their first plugin install, which was dialed for perfect interoperability with the ODF 1.0-compliant reference implementation, OOo 2.0. In August, we sent Massachusetts the first da Vinci version of the plugin, which was dialed for perfect, 100% round trip conversion fidelity with the legacy of Microsoft Word binaries." "The Microsoft assistive technologies were never an issue for us because the plugin works natively within Word. Microsoft Word handles the assistive technologies, and all the plugin does is the conversions from Word's in-memory-binary-representation to ODF and back." "The situation with the MSOffice bound business processes was such that everyone agreed we had to have a much higher fidelity converting those binaries than the extraordinary 85 per cent fidelity credited to the OpenOffice.org file conversion engine. We had to have perfect fidelity because there was no reasonable expectation of ever successfully migrating those business processes to a Microsoft Office alternative like ODF-ready OpenOffice.org, StarOffice, WorkPlace or Novell Office. Such a re-engineering of the business processes would be costly and beyond disruptive.." "My educated guess is that it would take all of two weeks for Microsoft to write an Microsoft Office ODF plugin. Indeed, Microsoft developers reportedly told Massachusetts that it would be "trivial" for them to implement ODF in Microsoft Office. In all three of the major apps. If they can do it for something as complex and convoluted as EOOXML, ODF will be a snap. The trick is not in XML. It's in having the secret legacy binary format blueprints." "There's a reason we call our plugin "da Vinci". Yeah, you guessed it. There is in fact a secret code needed to unravel the remaining mysteries of the legacy binaries; the elusive 15% just beyond the reach of the OpenOffice.org conversion engine." "The da Vinci plugin is conformant with version 1.2 of the ODF specification still working it's way through the OASIS ODF sub-committees and is dependent on features of the draft specification that may conceivably change. Massachusetts was well aware of this fact, and knew we were treading on dangerous ground because ODF 1.2 was not yet final. They gave us the go-ahead anyway. Such is the importance of round trip high fidelity with the legacy binaries." "Why ODF 1.2? Microsoft is notorious for frequently changing its file formats. There is even a Microsoft document jarred loose in the antitrust litigation where they brag about maintaining a "moving target" for other vendors' efforts to achieve interoperability with Microsoft applications. For example, there is no single "DOC" file format. There are versions after versions of just the word processing format, all different. And their specifications are still secret. Imagine the volumes of unspecified binary objects, application version specific or add-on specific processing instructions, and aging system dependencies buried in those billions of legacy binary files. There is no telling when or where they will pop up and da Vinci will have to somehow handle what are otherwise one unmappable black hole after another." . The starting point of this migration is exactly where Massachusetts ITD thought it would be - with ODF plugins for Microsoft Office." Mark: Thanks for posting the very long press release for an unreleased product (is it open source? is it commercial?) that generates a non-standard version of ODF based on plans for ODF 1.2, and for which Google provides no test results or even home page. It seems that daVinci is an Word plug-in, not a general Office tool: so is your claim actually some ODF people assert without providing any evidence so far? But what it means also is that only now, after the OOXML is well under way, is ODF getting the features available in OOXML. Hmmm, good for ODF and everyone I'm sure. Have you seen it? Rick said: "Thanks for posting the very long press release for an unreleased product (is it open source? is it commercial?) that generates a non-standard version of ODF based on plans for ODF 1.2, and for which Google provides no test results or even home page." The Opendocument Foundation (sponsors of the plugin) say this: "The infamous ODf Plugin is not yet available for download. Our plan is to submit the plugin to participate in the Commonwealth of Massachusetts trials. Following the trials, and completion of development, the plugin will be available to the public. National and State governments, governmental agencies and systems consultants having an interest in the trials are welcome to contact us for information, and possible contribution - participation suggestions. We're not yet aware of how the trials are to be structured, but input and advice is most welcome." I'm fairly sure that the Opendocument Foundation is waiting for Microsoft to release Vista and Office 2007 to the general public, in order that the daVinci plugin can't be sabotaged in the way it works at the last minute. Rick: "It seems that daVinci is an Word plug-in, not a general Office tool: so is your claim actually some ODF people assert without providing any evidence so far" Sorry, that is not correct. The plugin has been demonstrated to Massachusetts, to some other government interested parties, and to a commission in Europe. There is an offer on the table to demonstrate it to the ISO JTC. Refer to: Rick: ?" No. They had the capability of "100% able to handle MS legacy formats" with ODF version 1.0 too. Going to ODF version 1.2 exposes more of the legacy format information to other non-MS-Office applications, and so is better for interoperability with non-MS-Office applications. "But what it means also is that only now, after the OOXML is well under way, is ODF getting the features available in OOXML. Hmmm, good for ODF and everyone I'm sure." No. ODF has had the ability to handle everything in MS legacy formats from version 1.0. MS engineers knew this also, and said as much to Massachusetts representatives. MS engineers told Massachusetts representatives that it would be "trivial" for them to make MS Office fully capable and compliant with ODF (even at ODF version 1.0). Still Microsoft management killed that idea, they came up with OOXML instead, and they had the audacity to make the utterly false excuse that ODF could not handle their legacy formatted documents. It could then, it still can now, and Microsoft knew it. "Have you seen it? " No, I have not. It is not yet released to the public. But it does exist, and it has been demonstrated, and it does work. As advertised. And hence, it does proove the essential points. ." All I would ask is that you keep all of these facts in mind before you go trying to *cough* "correct" *cough* anything to align it better with Microsoft's spin. You would end up with a massive amount of egg on your face if you just took Microsoft's word for things at face value. Mark: Again, no proof, just press releases. On the example I gave before, what about tables in presentations? ODF 1.0 did not allow that AFAIK. You can see in the schema for ISO ODF that it doesn't. But the OOXML format does. So I don't see by what magic it is possible, sorry. One schema says one thing, the other schema allows something different. The most charitable meaning I can think of is that there might be some "trivial" changes to both ODF (e.g. ODF 1.2 might meet the mark) and Office that would make them compatible. ." Excuse me? I was trying to work on the assumption that you're an honest person seriously thinking about the problem, but that assumption can no longer hold. This is ludicrous sophistry. I can no longer trust a thing you put in that entry. You've shown that your intellectual independence has already been sufficiently compromised by the stance you've taken, whether because of the money or because of the tendency for people to harden their stances once they've entered an adversarial position, that you cannot be trusted and are no longer independent in this matter. If you're willing to squirm around the letter of the rule to this extent, your credibility as an independent with integrity in the matter is gone. The question of whether you're technically allowed to say what you want and therefore technically might be imagined not to be swayed in your opinions by the money is out the window. It is utterly clear what the purpose of those guidelines is: People aren't supposed to be commenting on things when they've been paid by someone with a significant vested interest in a non-neutral point of view. OOXML is Microsoft's baby, they're pushing it because they have a strong financial interest in blunting adoption of ODF, and whether it "should" be a standard or not there is no real argument that it was created purely as a definition of the behaviour of a specific Microsoft product/group of products. Oh, but it's not a "brand"! Give me a break. This is blatant intellectual dishonesty, and if you're capable of it over this, you're capable of it in your edits to Wikipedia itself. Here's the thing, once you take money from Microsoft to perform a service, you are an employee of Microsoft. Once you are a Microsoft employee, there is a serious conflict of interest with regards to your editing of content pertaining to Microsoft or any of its competitors. Even if that employment is as an outside contractor, the fact remains that Microsoft is then in a position to reward or punish you financially based on their view of the content you create or modify. To truly put this in perspective, you have to consider the precedent. If it is OK for you to take money in order to edit pages in a manner that you personally feel comfortable with while taking money from an interested third-party (and therefore being in their employ), then it is OK for any person to work under the same principals. This means it is OK for a lobby firm to have its employees make changes to articles related to their clients or political motivations. It doesn't matter that you have a personal code of ethics that you feel keeps you neutral. The individuals working in the lobby firm feel exactly the same way. They might feel that a certain scientifically-based fact is not sufficiently proven, and therefore deserves ommission in their eyes. Taking on this task at Microsoft's bequest can only be done if you feel comfortable with corporations and interest groups having their employees take on the same kind of tasks. The difference in motives can't be the measuring stick of whether or not one person's editing for money is more appropriate than another's. For no two people will ever agree on what that measurement is, nor would it be reasonable to expect the site owners and readers to be able to tell what motiviations another person had when making changes. When dealing with issues of interests, the best policy is to act in a manner that is not just devoid of interest conflicts, but to act in a manner in which not even the appearance of the potential for a conflict exists. Rick Jelliffe: "Again, no proof, just press releases." Proof has been provided. Sorry, but demonstrations of functionality to official bodies are not "press releases". ." Now, in your head, put the shoe on the other foot. Ask yourself what evidence, other than Microsoft's say-so, has ever been put forward the ODF is not fully capable of handling everything in Microsoft's legacy formats. On the ODF side, you do have evidence, and it has been presented to independent official witnesses. On Microsoft's side, they have no evidence whatsoever of any failing of the ODF format, and indeed Microsoft engineers have stated that a full ODF capability for Microsoft Office is a "trivial exercise". Rick Jelliffe: "The most charitable meaning I can think of is that there might be some "trivial" changes to both ODF (e.g. ODF 1.2 might meet the mark) and Office that would make them compatible." The most charitable thing I can think of is that you are desperate to see a way that Microsoft's spin could in any way be remotely feasible to be true. One has to question exactly why you are so keen to see this issue in Microsoft's favour. One has to wonder if you have been offered any monetary incentive to see it that way. Oh wait, ... isn't that exactly where this whole topic started ... So what if MS OS their file formats. It is of no use to the average PC user.And only use to some programers.Besides is it really that safe to edit MS programs and files ,it may all come crashing down at your feet and then you may stand in something sticky.:) There are far better OS to use. Microsoft can not baffle us with bull shit. They try..... "Gerard said the situation is regrettable though. "We're disappointed that Microsoft thought it had to work by stealth like this," he said. The company would be better off donating the money to Wikipedia and earning the goodwill that would result, he said." Why don't they do this. They could also send me some money as well it's not like they are short of cash. Mark: I did some digging myself. The very first ODF TC meeting minutes, say "The TC agreed that transformability into potential Microsoft office XML formats could be sensible, but is not a formal requirement." Unless something changed later, I stand by my original statement ODF has simply not been designed with the goal of being able to represent all the information possible in an MS Office document. On the subject of daVinci, I have found the download page, at Open Document Foundation. I downloaded the MS updater they suggest, and downloaded it (twice) but it would not install on my system. But it hasn't been released you, in any case. So it isn't quite vaporware after all! daVinci looks quite interesting. Readers should be aware of bait-and-switch. Now seems you can round-trip any format (in ODF or OOXML) by embedding it as binary object. For example, ODF has an element <office:binary-data> that allows you to have a graphics file in any format (Waaa, I thought that OOXML had to be rejected because it allowed Windows Metaformat as a clipboard type?) So the bits that are easy and exposed in the relevant API (the daVinci material talks of MSXML here: I don't get it) can be converted to ODF, and parts that are based on legacy formats have to be reverse engineered or embedded as binary. That seems to be the way. So round-tripping doesn't necessarily mean exposing the information. From the sound of it, daVinci can do at least the 85% conversion that the MS/Novell -sponsored ODF converter aparantly claims, and can round-trip data, but they have trouble that they cannot figure out all information from IBMR the way that MS do. Testing will tell how far they go. Of course, another approach is the multi-version file approach: save it as some native format for the originating application for immediate round-tripping, to ODF for interchange, and as PDF for fast display and printing, all in the same ZIP. Fat but it would meet a lot of different needs. Not quite all the needs that OOXML does (see Peter Sefton's comment to another blog entry) though, it seems to me. Patrick Durusau, the ISO ODF editor, emailed to say about his amusement on some of the stories and to ask me to post this: "Apparently rumor has it that we will have to wait 5 years to do any corrections to ODF 1.0. Actually OASIS is the maintainer of ODF and I expect to see ODF 1.2 out this coming year, with lots of corrections and some additions, so the 5 year stuff is just a misunderstanding of PAS maintainent." Now, after this week of Chinese Whispers, I would be entirely unwilling to say that this is FUD or even real. Even Patrick doesn't seem to have actually heard it, it is just an apparent rumour to him. I hope every time someone asks a question on a blog, or puts a question in the form of a statement, this doesn't lead to some big round of accusations of FUD! That seems to have been the trouble that happened out of this entry: a blog comment is part of a conversation and shouldn't necessarily be quoted as if it were a well-researched statement or part of some massive conspiracy. There is enough trouble with explicit statements of FUD with URIs, I think we need to be very careful before we react at all to rumours of FUD. Perhaps Patrick is trying to give me the opportunity to have show balance, or perhaps he is concerned that the ODF side looks so bad out of all this that he wants to show that the OOXML side has its share of FUDmeisters too (er, well, apparant rumours of FUD...) But happy to oblige! A breath of fresh air. I wish some of the FUD-pushers currently jumping onboard the ISO/IEC Sub Committee that will look at this, would be as honest in declaring their affiliation and backing from IBM - the only ECMA member organisation that voted against the European standardization of OOXML and who now seem intent on a spoiling operation, having lost all the arguments around the table at the first stage... The issue for me is functionality offered by both offers - I do not think that they occupy the same problem space, so I think the arguments that OOXML "contradicts" ODF is like saying JGEP contradicts RAW, or AAC contradicts MP3...They offer different functionalities for different needs, and I for one will not throw out Word (which can open and save ISO-compliant ODF) in order to step down to more limited functionality and be "interoperable" on a lowest-common-denominator (LCD) basis. Word offers, by design, thousands of options, any small subset of which is valuable to one community of users or another: It aims to please all by a "something for everyone" aproach, like it or not, that is its strength. ODF on the other hand offers a simple LCD solution that has its value for simple document exchange but please spare us the BS that it is the only document format that avoids lock-in and is "free"... On another note: can anyone point me to software that implements the ISO-approved version of ODF (not the other ODF versions, approved by OASIS, that are the basis of, for example, OpenOffice offers)? The irony is that Office2003 and 2007 offers ISO-conformant ODF already.... As Rick pionts out, ODF was rushed through ISO-fast tracking last year, without any reference implementations available and Microsoft are at least falling over themselves to play the ISO game according to the rules. The sea of Crap, with Microshaft in the middle. You folks all forget the saying "It is not what you know but who you Blow and how much Money you grease the palm with!". Now as far as Massachusetts look at who you have for politicians(example Ted and John). Remember when I.B.M. did not play nice with bully billyboy? Microshaft wants to be the one the only HO you will ever have, even if there is better. Free enterprise to Microshaft means we have money if we can not bully you, we will buy you or sue you. Remember microshaft, Linux was around long before you and competition is good, bully's are not. Short remarks to Rick Jelliffe "FUD enrages" "My first computer was a Mac Plus"( "An interesting offer: get paid to contribute to Wikipedia Monday January 22, 2007 10:13AM by Rick Jelliffe in Opinion"): my later years I worked on an Amdahl too. Embedded scientific writing seems to me nowadays canononical? And xml is data . It's me who works a lot with such xml_hooks. But I more enjoy xml and find the whole MSOffice spreadsheet or other text editor stuff (compare please the W3CxmlRelease'07) rather a funny redundancy. >>> ...If anyone sees any examples of incorrect statements on Wikipedia or other similar forums in the next few weeks, please let me know: whether anti-OOXML or anti-ODF. ..... Alberto: There is nothing unethical about doing an honest job respecting the Wikipedia rules and editors, under the full scrutiny of the world and with transparency. AFAIK we haven't talked money terms to MS yet, and I don't even know if they want me to go ahead. I have started to suggest some minor changes in Wikipedia, some of which have been accepted so far, but I am not doing any direct edits. We don't need to analyze and understand OOXML and ODF to know what's really going on here. Microsoft itself holds the keys to interoperability. They have had the ability all along to publish APIs and specs, and to create tools for cross-platform data compatibility. All those gigabytes of open source code have always been there for them to study and use. The obstacle to interoperability and open, cross-platform data formats has always been, and still is, Microsoft. Despite stiff resistance from MS, we already have a fair bit of .doc, .xls, and .ppt compatibility in the FOSS world. At any time they could have opened up .doc, which has become a de-facto standard. But they haven't, and they won't. Anyone who thinks MS is offering a genuine open standard in OOXML is too naive to live on their own- their record, and their current actions, speak louder than their twisty double-talk and 6000-word "spec". That's not a specification, that's plain old obstruction. The offer smells, and not because of any arguable ethical considerations, but because of hard cold facts. And as usual it's the cannon fodder (that would be you, mr Jeliffe) that takes the hits, not Microsoft. I for one have no problem with Rick editing articles for Microsoft, so long as they are neutral and factual. If they are not, then the edits will get changed anyway. But I doubt Rick will do this. Incidently, I'm no fan of Microsoft, yet I wrote most of the Windows 2000 and MDAC articles. Both are featured. What does this say about me? Dear Rick. The issue of contradictions is deeper than you state. OOXML should not contradict any significant existing ISO standard -- not just ODF. It is unfortunate for OOXML that it redefines some basic ISO standards -- such as dates and distances. In the case of distances it also introduces new units which are not compatible with existing ISO units -- twips being the most outrageous, being a non-decimal fraction of an inch. Note that OOXML had no deployment when the contradictions were submitted, so it makes no sense to argue for "twips" and the like in terms of "compatiblity with installed base". The Chinese wireless proposal did not reach into fundamental measures and attempt to redefine them. The Chinese wireless proposal was also complete. From my reading of OOXML it is not complete., referencing non-ISO and sometimes non-published materials. The OOXML proposal is also missing some major work on compliance. The trend at IEEE and ISO has been to specify comprehensive compliance tests within the standard, as a device leading to better interoperability. Such a complex proposal missing a comprehensive compliance section raises eyebrows. OOXML may well be a good thing -- XML software isn't my field. But this proposal for this OOXML is simply too shoddy. Do an interview with Wikinews, you've been playing, might as well set the record straight. Glen: The discussion page of the Grocdoc site has lots of interesting points. It notes that the twips are based on PostScript units (I have not verified this). It is interesting that the comment from an anti-OOXML person when the objection is found to be flimsy is No one is pretending that any of the flaws described in that section, taken individually, are reasons to reject Ecma 37 and yet, actually, someone is "pretending" exactly that: err, you. If we take the time to argue about some technical issue, I think we need to make sure we are up-to-speed on which claims are wobbly. Have you actually read the OOXML spec and the ODF spec and other IS document type specs such as ISO HTML, RELAX NG or Schematron, for comparison, to know what is "shoddy"? Ed: I have put in a request on the Wikinews page to challenge the article. I have had several friends ask me why I am not suing over some of the more extreme press articles and blogs; a friend from a major three-lettered company (not *that* one, the other one) warned me against sueing people from billion dollar companies. The thing I have asked Wikipedia is for them to clarify that the underlying basis of the story, that there was some kind of clandestine scheme to do something not allowed by rules uncovered, is incorrect; since that is the whole basis for the story existing, it doesn't matter that the article itself is moderately inoffensive. Neutrally reporting rumour, and especially reporting off-the-cuff answers by people to questions with incorrect factual bases is not, in fact, neutral at all. If some is asked "MS has paid someone to secretly change articles" then an answer like "That is disappointing" is appropriate; if the question was "MS is trying to find productive ways to counter bias and bending over backwards to try to respect the rules" than an answer like "Oh, good, I am sure we can work something out" is appropriate. On this subject, look for an announcement from Wikipedia on handling enterprise complaints soon! Microsoft corrupt? No way! OK, let's review some history: 23-Aug-01 Microsoft Astro-turfs Again Yet again, a Microsoft front organization gets caught trying to influence government with a phony "grass-roots" letter writing campaign. ... [One state attorney general said] "This is not a company that appears to be bothered by ethical boundaries". From April 10, 1998:." How about the time Microsoft offered higher education instructors a $200 reward for mentioning Microsoft products in a classroom setting? No, Microsoft's behavior hasn't changed since before the Windows 3.1 beta release. Exodus 23:8 "And thou shalt take no gift: for the gift blindeth the wise, and perverteth the words of the righteous." Dan, you are clearly a troll (in the technical sense). Please try harder. Jesus dined with publicans and spoke with women. I have no problem with doing a short, honest, open job for them, as allowed by the Wikipedia guidelines. If the ODF people or even some government or other body would pay me, I would have no problem with that either. Honi soit. Rick, rise above and beyond. Be strong. Do you don't need the money; it shows. Don't take it. Not because it's wrong, because it's not for you, seemingly, but because succombing to temptation of money is such a sign of weak character, which I hope we can all agree that is not FUD. You seem like you have the mettle to rise above this. Just do the corrections. For free. For yourself. Prove to everyone, and most importantly to yourself that money doesn't and never did play a role in your intentions. Many of us "kids" look up to older folks like you and some of those in the comments section. People of strong, virtuous, morally unblemished character. Prove them, us, all wrong! And don't worry, it's not "them" that win, it's everyone that wins, including you, heck, even including MS! (if their original intents were as you assumed they were) Adios! The problem is that people are doing it wrong. If you're going to game Wikipedia, the key is to do it anonymously. As long as the articles conform with wikipedia standards there is nothing wrong with it where is the offer? And wiki is a free contribution system. Why would they be paying to our contributions?
http://www.oreillynet.com/xml/blog/2007/01/an_interesting_offer.html
crawl-002
refinedweb
20,776
61.16
Building a two player Wordle clone with Python and Rich on Replit. Once you're done, you'll be able to play a command-line-based game with a friend (with both of you sitting at the same machine), as shown below. We'll be using Python, and to do the green and yellow colors we'll use Rich, a library for rich-text formatting. To follow along, you should know some basic Python, but we'll explain each code sample in depth so you should be able to keep up even if you are not familiar with Python. Getting started To get started, create a Python repl. Installing Rich Rich isn't part of the Replit Universal Installer, so we have to install it manually. Open up the "Shell" tab in the repl workspace and run the following commands: python3 -m poetry init --no-interaction python3 -m poetry add rich This will create a pyproject.toml file to define Rich as a dependency, and Replit will automatically install it for us next time we run our app. Printing colored text The first thing we need to figure out is how to print out different colored letters. By default, we'll use similar settings to the Wordle defaults - Green = correct letter in the correct position - Yellow = correct letter in the incorrect position - Gray = incorrect letter Because we're using Rich, we don't have to mess around with ANSI escape codes. It's possible to use them to style terminal text, but you end up having to deal with nasty-looking strings like \033[0;32m, and there are likely to be compatibility issues too. Rich abstracts this away for us, and we can use nicer-looking controls like '[black on green]TWORDLE[/]' to describe how the text should look. Take a look at how this works now by adding the following code to main.py and pressing "Run": import rich rich.print('[black on green]TWORDLE[/]') Because we may want to customize what specific colors mean at some point, let's define each of our three cases in functions. Replace the existing code in main.py with the following: import rich def correct_place(letter): return f'[black on green]{letter}[/]' def correct_letter(letter): return f'[black on yellow]{letter}[/]' def incorrect(letter): return f'[black on white]{letter}[/]' WELCOME_MESSAGE = correct_place("WELCOME") + " " + incorrect("TO") + " " + correct_letter("TWORDLE") + "\n" def main(): rich.print(WELCOME_MESSAGE) if __name__ == '__main__': main() Run this code, and you'll see a Wordle-styled welcome message, demonstrating all three styles, as shown below. Creating the game loop As in classic Wordle, our game will allow the player six tries to guess a word. Unlike classic Wordle, we'll allow for two players. Player 1 will choose a word, and player 2 will attempt to guess it. The basic logic is then: Get word from Player 1 Get guess from Player 2 While Player 2 has guesses remaining Get new guess If guess is correct End the game So let's ignore our fancy colored text for a moment and build this logic. Getting and guessing the word We'll use the Console class from Rich, which creates a virtual output pane on top of our actual console. This will make it easier to have more control over our output as we build out the app. Add the following two imports to the top of the main.py file: from rich.prompt import Prompt from rich.console import Console And now replace the main() function with the following code: def main(): rich.print(WELCOME_MESSAGE) allowed_guesses = 6 used_guesses = 0 console = Console() answer_word = Prompt.ask("Enter a word") console.clear() while used_guesses < allowed_guesses: used_guesses += 1 guess = Prompt.ask("Enter your guess") if guess == answer_word: break print(f"\n\nTWORDLE {used_guesses}/{allowed_guesses}\n") If you run this, you'll be prompted (as player 1) to enter a word. The entered word will then be hidden from view to avoid spoiling the game, and player 2 can enter up to six guesses. At this stage, player 2 doesn't get any feedback on correct or incorrect letters, which makes the game pretty hard for player 2! If player 2 does happen to guess correctly, the loop will break and the game will display how many guesses were used. Providing feedback on correct letters Let's add a helper function to calculate whether each letter should be green, yellow, or gray. Add this function above the main() function in main.py: def score_guess(guess, answer): scored = [] for i, letter in enumerate(guess): if answer[i] == guess[i]: scored += correct_place(letter) elif letter in answer: scored += correct_letter(letter) else: scored += incorrect(letter) return ''.join(scored) This function takes in player 2's guess and the correct answer and compares them letter by letter. It uses the helper functions we defined earlier to create the Rich formatting string for each letter, and then joins them all together into a single string. NOTE: Here we simplify how duplicate letters are handled. In classic Wordle, letters are colored based on how often they occur in the correct answer, for example, if you guess "SPEED" and the correct word is "THOSE", the second E in your guess will be colored as incorrect. In our version, it will be labeled as a correct letter in the wrong place. Handling duplicate letters is tricky, and implementing this logic correctly is left as an exercise to the reader. Call this function from inside the while loop in main() by adding the console.print line as follows: while used_guesses < allowed_guesses: used_guesses += 1 guess = Prompt.ask("Enter your guess") console.print(score_guess(guess, answer_word)) # new line if guess == answer_word: break Now player 2 has something to work on from each guess, and it should be a lot easier to guess the correct word by incrementally finding more correct letters, as shown in the example below. Adding an emoji representation for spoiler-free sharing A key part of Wordle is that once a player has guessed a word, they can share a simple graphic of how well they did, without giving away the actual word. For our two-player version, this "no spoilers" feature isn't as important, but let's add it anyway. As with the letter-coloring, we want to keep the emoji we use configurable. By default, we'll use green, yellow, and gray squares. Let's start by defining this in a dictionary, near the top of our main.py file. Add the following to your code: emojis = { 'correct_place': '🟩', 'correct_letter': '🟨', 'incorrect': '⬜' } Replace the score_guess function with the following: def score_guess(guess, answer): scored = [] emojied = [] for i, letter in enumerate(guess): if answer[i] == guess[i]: scored += correct_place(letter) emojied.append(emojis['correct_place']) elif letter in answer: scored += correct_letter(letter) emojied.append(emojis['correct_letter']) else: scored += incorrect(letter) emojied.append(emojis['incorrect']) return ''.join(scored), ''.join(emojied) The logic is very similar to before, but instead of only calculating the correct style for the letter, we also keep track of each emoji. At the end, we return both the string to print out the scored word, and the emoji representation for that guess. To use this in the main function, replace the code for the while loop with the following code: all_emojied = [] while used_guesses < allowed_guesses: used_guesses += 1 guess = Prompt.ask("Enter your guess") scored, emojied = score_guess(guess, answer_word) all_emojied.append(emojied) console.print(scored) if guess == answer_word: break print(f"\n\nTWORDLE {used_guesses}/{allowed_guesses}\n") for em in all_emojied: console.print(em) If you run again, the game will work as before, but now you'll see the emoji representation printed after the game ends. This can be copy-pasted to share and help our game go viral. You can see what it looks like in the image below. Some finishing touches The one messy part of our game remaining is that the input prompts are still shown after player 2 has entered each guess. This means that each word is shown twice: once in its colored form, and once exactly as the player entered it. Let's adapt the game to clear the console and output just the colored versions of each guess. To do this, we need to keep track of all player 2's guess, which we were not doing before. Replace the while loop in the main() function with the following code: all_emojied = [] all_scored = [] while used_guesses < allowed_guesses: used_guesses += 1 guess = Prompt.ask("Enter your guess") scored, emojied = score_guess(guess, answer_word) all_scored.append(scored) all_emojied.append(emojied) console.clear() for scored in all_scored: console.print(scored) if guess == answer_word: break This clears the console completely after each guess by player 2, and then prints out each of the (styled) guesses. The output looks neater now, as shown below. Adding instructions People will like our game more if they can figure out what to do without having to read documentation. Let's add some basic instructions for each player to the game interface. Below the WELCOME_MESSAGE variable we defined earlier, add the following: P1_INSTRUCTIONS = "Player 1: Please enter a word (player 2, look away)\n" P2_INSTRUCTIONS = "Player 2: You may start guessing\n" Now update the main() function like this: def main(): allowed_guesses = 6 used_guesses = 0 console = Console() console.print(WELCOME_MESSAGE) console.print(P1_INSTRUCTIONS) answer_word = Prompt.ask("Enter a word") console.clear() console.print(WELCOME_MESSAGE) console.print(P2_INSTRUCTIONS) all_emojied = [] all_scored = [] while used_guesses < allowed_guesses: used_guesses += 1 guess = Prompt.ask("Enter your guess") scored, emojied = score_guess(guess, answer_word) all_scored.append(scored) all_emojied.append(emojied) console.clear() console.print(WELCOME_MESSAGE) for scored in all_scored: console.print(scored) if guess == answer_word: break print(f"\n\nTWORDLE {used_guesses}/{allowed_guesses}\n") for em in all_emojied: console.print(em) Now our welcome message stays at the top, and the players are prompted by simple instructions. Have fun playing it with your friends! Where next? The basics of the game are in place, but there is still a lot you could build from here. Some ideas: - Fix the logic for handling duplicate letters. - Fix the fact that the game crashes if player 2 enters the wrong number of letters. - The game still says 6/6, even if player 2 has not guessed the word after six tries. Have the game print out X/6in this case, as in classic Wordle. - Give player 2 more guesses based on the length of the word player 1 enters. - [CHALLENGING] Make the game work over the internet instead of requiring both players to be in same room. You can find the code for this tutorial here:
https://docs.replit.com/tutorials/two-player-wordle-clone-python-rich
CC-MAIN-2022-27
refinedweb
1,754
62.48
I am trying to generate an array of all combinations of an arbitrary number of arrays. From the generated array, I would like to add an constraint that the sum of the numbers must lie between two bounds (say 'lower' and 'upper') One method of doing this is to use cartersian, sum the elements, and select the ones that fall within the lower and upper bounds. However, the main limitation is that it is possible to run out of memory given a large number of input arrays. Another method is to use itertools.product: import itertools import numpy as np def arraysums(arrays,lower,upper): p = itertools.product(*arrays) r = list() for n in p: s = sum(n) if lower <= s <= upper: r.append(n) return r N = 8 a = np.arange(N) b = np.arange(N)-N/2 arraysums((a,b),lower=5,upper=6) [(2, 3), (3, 2), (3, 3), (4, 1), (4, 2), (5, 0), (5, 1), (6, -1), (6, 0), (7, -2), (7, -1)] a = np.arange(32.) arraysums(6*(a,),lower=10,upper=20) You could use recursion. The main advantage here is that you can short-circuit the enumeration of tuples at each stage. For example, if item has been selected from the first array, then the new lower and upper limits for the rest of the arrays should be lower-item and upper-item, and you can automatically throw out any value in the other arrays that is bigger than upper-item. This intelligently reduces the size of your search space at each level of the recursion. import itertools def arraysums_recursive(arrays, lower, upper): if len(arrays) <= 1: result = [(item,) for item in arrays[0] if lower <= item <= upper] else: result = [] for item in arrays[0]: subarrays = [[item2 for item2 in arr if item2 <= upper-item] for arr in arrays[1:]] result.extend( [(item,)+tup for tup in arraysums(subarrays, lower-item, upper-item)]) return result def arraysums(arrays,lower,upper): p = itertools.product(*arrays) r = list() for n in p: s = sum(n) if lower <= s <= upper: r.append(n) return r a = list(range(32)) For this test case, arraysums_recursive is over 67x faster than arraysums: In [70]: %time arraysums_recursive(6*(a,),lower=10,upper=20) CPU times: user 3.67 s, sys: 0 ns, total: 3.67 s Wall time: 3.68 s In [73]: %time arraysums(6*(a,),lower=10,upper=20) CPU times: user 4min 8s, sys: 0 ns, total: 4min 8s Wall time: 4min 8s
https://codedump.io/share/PTETVOgqZhNk/1/summing-all-possible-combinations-of-an-arbitrary-number-of-arrays-and-applying-limits
CC-MAIN-2016-50
refinedweb
418
62.17
If I do a Can0.begin(1000000, filter) with filter.id = 0x70 to set a mask of 0x70, this still allows addresses of 0x110 through. If I'm understanding the documentation correctly, it will do an AND operation with the received message and then pass to a mailbox for further filtering. In this case, 0x70 AND 0x110 is 0x10. But I have each mailbox with a filter of also 0x70, yet frameHandler() is still receiving data with messages that do not have 0x70 address Thanks, I'll definitely take a look at that. Even if I didn't have a mask set, shouldn't the filters on the individual mailboxes take care of it on their own? Or are you saying that a mask is mandatory for the filters to work properly? Success! Did some reading and also went back and took a closer look at Darcy's example from earlier in the thread. Part of what was tripping me up is that setMask() expects a 29-bit number. The documentation says 11 or 29 bit, so that wasn't very clear. I don't think I would have figured this one out without Darcy's example. Can0.begin() also doesn't seem to work for setting a default mask. I tried passing 0x7FF as well as 0x7FF<<18, but neither seemed to work. Maybe the mask is only applied when using read() instead of frameHandler? Either way, it seems like setMask() must be set for every mailbox of interest if you want to use the callback interface. Here's the working code to filter all mailboxes for a single address:.Code:#include <FlexCAN.h> uint16_t raw; class ExampleClass : public CANListener { public: bool frameHandler(CAN_message_t &frame, int mailbox, uint8_t controller); //overrides the parent version so we can actually do something }; bool ExampleClass::frameHandler(CAN_message_t &frame, int mailbox, uint8_t controller) { raw = 0; raw |= frame.buf[5] << 8; //received bytes are in Intel LSB order raw |= frame.buf[4]; analogWrite(A14,raw); return true; } ExampleClass exampleClass; // ------------------------------------------------------------- void setup(void) { delay(1000); //turn LED on pinMode(13, OUTPUT); digitalWrite(13, HIGH); //change analogWriteResolution to 16-bit to avoid pre-bitshifting to 12-bit analogWriteResolution(16); CAN_filter_t filter; filter.id = 0x70; filter.flags.extended = 0; filter.flags.remote = 0; Can0.begin(1000000); Can0.attachObj(&exampleClass); for (uint8_t filterNum=0; filterNum<14; filterNum++) { Can0.setMask(0x7FF<<18,filterNum); //require exact match on filter.id, bitshift is necessary for 11-bit id's Can0.setFilter(filter,filterNum); } for (uint8_t filterNum=0; filterNum<14; filterNum++) { exampleClass.attachMBHandler(filterNum); } } // ------------------------------------------------------------- void loop(void) { } Last edited by monqy; 05-22-2017 at 04:39 AM. I am stuck; first basic question, Has anyone had this system work with the GMLAN? Specifically the high speed 500kb one. I had a Teensy 3.2 connected to one of those Chinese SN65HVD230 boards. () It is in turn connected to the the GMLAN +/- of a 2009 Silverado I can see data being presented to pin 4 of the Teensy with my scope. Shows a 3v signal with pulses dropping to about 1.5v ref to ground. using this program from the examples I can see the greeting line and then a period every second but no data. this was the simplest sample I could fine here and I just get the greeting.this was the simplest sample I could fine here and I just get the greeting.Code:/* * Object Oriented CAN example for Teensy 3.6 with Dual CAN buses * By Collin Kidder. Based upon the work of Pawelsky and Teachop * * Both buses are set to 500k to show things with a faster bus. * The reception of frames in this example is done via callbacks * to an object rather than polling. Frames are delivered as they come in. */ ('.'); } My end goal is to translate the data from the 2009 engine to older Class 2 data for my 1999 Jimmy and plant that engine in it, keeping the more advanced control system on the 2009. Any help would be appreciated.My end goal is to translate the data from the 2009 engine to older Class 2 data for my 1999 Jimmy and plant that engine in it, keeping the more advanced control system on the 2009. Any help would be appreciated.Code:// ------------------------------------------------------------- // CANtest for Teensy 3.1 // by teachop // // This test is talking to a single other echo-node on the bus. // 6 frames are transmitted and rx frames are counted. // Tx and rx are done in a way to force some driver buffering. // Serial is used to print the ongoing status. // //#define USE_V1_LIB #ifndef USE_V1_LIB #include <FlexCAN.h> //FlexCAN CANbus(125000); #else #include <FlexCANv1.h> FlexCANv1 Can0(125000); #endif static CAN_message_t msg,rxmsg; static uint8_t hex[17] = "0123456789abcdef"; // ------------------------------------------------------------- static void hexDump(uint8_t dumpLen, uint8_t *bytePtr) { uint8_t working; while( dumpLen-- ) { working = *bytePtr++; Serial.write( hex[ working>>4 ] ); Serial.write( hex[ working&15 ] ); } Serial.write('\r'); Serial.write('\n'); } // ------------------------------------------------------------- void setup(void) { #ifdef USE_V1_LIB Can0.begin(); #else Can0.begin(500000); #endif delay(1000); Serial.println(F("Hello Teensy 3.1 CAN Test.")); } // ------------------------------------------------------------- void loop(void) { while ( Can0.read(rxmsg) ) { Serial.print("Packet: "); Serial.print(rxmsg.id, HEX); Serial.print('-'); hexDump( rxmsg.len, (uint8_t *)rxmsg.buf ); } } Keshka If you are using flexCAN by ColinK, then it will need more work as this is not a J1939 standard. This is possible with the current library. It would take some work on your part in your overridden gotFrame() method as the first frame (frame.buf[0]) contains the information related to total payload size and flow control. The 0 frame would be handled, and essentially inspected to determine the number of frames to be considered as a single message. I have my Teensy set to a 64 byte buffer. This would allow up to 64 bytes to be buffered to be decoded.This would allow up to 64 bytes to be buffered to be decoded.Code:#define SIZE_RX_BUFFER 64 //RX incoming ring buffer size Last edited by Detroit_Aristo; 05-25-2017 at 12:41 PM. Have you connected TX? If you read back a few posts, Teensy will discard messages that are not acknowledged (by someone on the bus). If you don't want Teensy writing to the bus, you need to set up listen-only mode. I will have to admit, C++ gives me fits. I am an old school C programmer and am comfortable with it but some of the things done in C++ I can't translate well. That in mind, I did not quite understand everything in your remarks Detroit. The define statement is easy enough but I don't know what else "more work" implies. If you could post a sample of your code that would help me considerably. At present, I don't know enough about capturing/decoding data from the CAN bus nor the GMLAN. Colin, pawelsky and teachop all have put a great deal of time into the libraries and when things work as supposed to, then cut/paste/go/thank you. In my case, "sorry, no banana" and the three have not gone into detail of how the code works making attempts at debugging quite challenging, especially when you toss in the fact that this old buzzard's difficulties with C++. I am going to try translating the libs today and see how far I get but I sure could use some help. I can provide detailed feedback and test results, schematics and hookup information. I have a 100 mhz digital storage scope, spectrum analyser and the entire control system from the 2009 Silverado, the full wiring harness, all of the computers, all of the components, right down to the fuel pump on my shop floor all hooked up and running as my test bed. I was very pleased to find this thread and hope all have not moved on. I thing everyone's work here is very valuable and will become more so as time goes by after all GM has only produced about 100 million vehicles in the last ten years, all using the new GMLAN so any assistance the members of this group can offer will be greatly appreciated. Keshka Anyone? is thread dead? I hope not, I sure could use some help It's not unlikely that you have a hardware issue. Several people had issues with bad transceivers. Some suggestions: Check the polarity of the transceiver. Try talking between 2 Teensies with Can, there are examples. Try to capture whatever appears on the RX pin and check the baud rate and if it's a valid Can message. The CanBUS Wikipedia page has enough details on the basic message format. There is a logic analyzer project for Teensy: I agree, I would first try using one of the basic examples with Arduino IDE and Teensy to confirm that the hardware is reading (anything) correctly. If not on your setup, test a different car's CAN lines to see if you get anything. Also check the SN65 number on the chip to see if it really is a 230, not 231 or 232. Also make sure that pin 8 (iirc) on the chip, aka Rs, is connected to ground = high speed mode. It should not be left floating, nor high. Somewhere in this thread you can find the chip marking number of the known bad chips. will do, am going to try the logic analyzer to see if it can read anything Ok, finally had a chance to test further. I am thinking the sn65hvd230 pair of boards I have are bad. I have 2 boards of a different layout from another supplier I will try later. The results I am seeing seem to indicate the sn65hvd230 can not drive the Teensy. Using my scope I can see clean pulses coming from the R pin (4) when the GM computer is active (key on) if the sn65hvd230 is only driving the scope. As soon as I connect the R pin to a pin on the Teensy, the signal degrades to the point it can't be read by the Teensy. Here is my test code (R pin(4) connected to Teensy 3): When run output with pins connected:When run output with pins connected:Code:int countH = 0; int countL = 0; void setup() { pinMode(3, INPUT); pinMode(4, INPUT); pinMode(13, OUTPUT); Serial.begin(115200); Serial.println("ready"); delay(10000); Serial.println("GO"); } void loop() { int foo; foo = digitalRead(3); if (foo){ countH++;} else{ countL++;} digitalWrite(13,foo); if(countH == 500) {Serial.println("countH"); delay(2000);} if(countL == 500) {Serial.println("countL"); delay(2000);} } ready GO countH when run output with pin 3 disconnected: ready GO countL scope output(s) same scope settings: Pin 3 disconnected: Pin 3 connected: this is my board: Teensy, sn65hvd230 and scope all share a common ground with the GM computer Teensy powered via USB of laptop sn65hvd230 powered from the 3.3v pin on the Teensy Ok, tried the other manufactures board and so far success! The TeensyLogicAnalyzer can now see the signal. Next, FlexCAN here is a photo of the other board: Great ZOT! I have FlexCAN working. So far just the simple test posted by TurboStreetCar but that is a start. And thanks to tni for pointing me to that logic analyzer program....I will use that more in the future. updates to follow PS, do you know of a lib similar to FlexCAN for the older class 2 serial data used in the 90's and early 2000's? CollinK, I am having difficulty running FlexCAN CANtest.ino with Arduino IDE 1.82 and Teensyduino, using two SN65HVD230D transceiver adapter boards from The while (Can0.available())is never satisfied. Exactly what conditions are necessary for Can0.available to be TRUE? Also for troubleshooting, I removed the transceivers and connected CAN0TX to CAN1TX and CAN0RX to CAN1RX. The Serial Monitor was intermittent. It seems to me that the circuit was affected by stray capacitance. I added a 10 pF ceramic capacitor across CAN1TX and CAN1RX and the Serial Monitor output became rock solid. However, this did not work when the transceivers were re-connected. Any insights, comments, or suggestions? Thanks, Dave K You really should leave the transceivers in there. CAN isn't meant to work without the transceivers. Technically it's possible but just don't do it. So, suggestions: 1. Did you terminate the bus? People quite often miss this part. You need your bus to have 60 ohms of resistance from high to low. This is supposed to be done with 120 ohm resistors on both ends (terminating resistors). In robust designs this will actually take the form of two 60 ohm resistors with a 47nF cap in between them connected to local board ground. But, 120 ohms will work. And, you can usually get away with only one 120 ohm resistor or one 100 or one 60 if your bus is short. But, you need something there between 50 ohms and 120 ohms or it is not going to work. 2. Are your boards perhaps bad? Above in the thread people had bad boards and it messed them up. This can be tough to test when you are first starting out and you don't have a lot of other hardware to test against. 3. Do you have filtering messed up? I believe that FlexCAN defaults to allow everything through if you don't ask it otherwise but double check that you haven't set any filters that could be blocking things. Hey! Board designer here. Are you sure you have the Rs pin pulled low? You need to add something along the lines of in your code, ideally in setup, before any CAN functions. This is not included in the FlexCAN lib by default.in your code, ideally in setup, before any CAN functions. This is not included in the FlexCAN lib by default.Code:pinMode(28, OUTPUT); digitalWrite(28, LOW); This pin can be used for a low-power mode when pulled high. If a logic high (> 0.75 VCC) is applied to RS (pin 8) in Figure 30 and Figure 32, the circuit of the SN65HVD230 enters a low-current, listen only standby mode, during which the driver is switched off and the receiver remains active. In this listen only state, the transceiver is completely passive to the bus. It makes no difference if a slope control resistor is in place as shown in Figure 32. The μP can reverse this low-power standby mode when the rising edge of a dominant state (bus differential voltage > 900 mV typical) occurs on the bus. The μP, sensing bus activity, reactivates the driver circuit by placing a logic low (< 1.2 V) on RS (pin 8). Hi everyone, I've tried my best to read into this, but am so far failing to find an answer to one of my questions, let me try and explain. I am a car enthusiast, and have just purchased an ECU which is able to send a CAN Stream (). I have yet to fit the ECU, and as such am trying to get a head start on development before I can actually see data flowing in. My hardware is a Teensy 3.2, with a SN65HVD230 transceiver. According to the spec (above) the stream uses 29bit (extended) Identifiers. My project will only read messages on the BUS, and I wondered if I needed to set an Extended ID filter to do so, or if it will do so automatically? Here is the code I am hoping to use to test the stream before continuing on my development path Any advice would be gratefully received.Any advice would be gratefully received.Code:#include <FlexCAN.h> int led = 13; static CAN_message_t rxmsg; void setup(void) { Serial.begin(9600); while (!Serial) ; // wait for Arduino Serial Monitor Serial.println("Teensy 3.1 CANlisten Example"); //boolean result = CANbus.begin(); -- Currently .begin object doesn't return state of bus //Serial.print("CAN begin successful: "); //Serial.println(result ? "YES" : "NO"); // Init CAN Can0.begin(1000000); //Light on to indicate on-bus state pinMode(led, OUTPUT); digitalWrite(led, 1); } void loop(void){ //Poll Rx FIFO while (Can0.read(rxmsg) ) { //when message available / append string as required if (rxmsg.len >= 1) { text = String(text + " DATA: "); } //construct string for available bytes (trunctate to DLC to avoid reading garbage) for( int idx=0; idx<rxmsg.len; ++idx ) { text = String(text + String(rxmsg.buf[idx],HEX)); text = String(text + " "); } //print result Serial.println(text); //LED back on to indicate watching Rx FIFO digitalWrite(led, 1); } } Thanks Pawelsky wrote: but you wrote:but you wrote:###Driver API FlexCAN(baud, id, txAlt, rxAlt) Create the FlexCAN object. The table below describes each parameter together with allowed values. Defaults are marked bold. When a non-allowed value is used default will be taken instead. So how can I use alternat(iv)e TX/RX on my Teensy 3.6? Can you share sample code?So how can I use alternat(iv)e TX/RX on my Teensy 3.6? Can you share sample code?###Driver API All available CAN buses have pre-created objects similarly to how the serial devices are created (Serial, Serial2, etc). In the case of these CAN buses they are called Can0 (Teensy 3.1/3.2/3.5/3.6) and Can1 (Teensy 3.6 only). begin(baud, defaultMask, txAlt, RxAlt) Enable the chosen CAN bus. regards, Sorry Guys first post and possibly a over simple question, But I am having my first go on a Teensy with flex can. (coming from a uno with a canshield). But how do I set the pins using flexcan on a Teensy 3.2. I cant seen to get any data from my can bus, And I am guessing its mostly likely my pin setup! Thanks Hello everyone, i did some search on the forum here, but didn't what i'm looking for, so to not make a new thread, will ask here. I'm using Teensy 3.2 and FlexCAN for some projects and i'm loving it, for reading and receiving it works great, the question is how could i read and receive messages on one Teensy at the same time? maybe some one has example code or something?
https://forum.pjrc.com/threads/39867-Another-fork-of-FlexCAN?s=d5d69a971048b8221a511e9b8a2c3a7d&p=149748
CC-MAIN-2020-24
refinedweb
3,042
66.23
Create an Azure file share To create an Azure file share, you need to answer three questions about how you will use it: What are the performance requirements for your Azure file share? Azure Files offers standard file shares which are hosted on hard disk-based (HDD-based) hardware, and premium file shares, which are hosted on solid-state disk-based (SSD-based) hardware. What are your redundancy requirements for your Azure file share? Standard file shares offer locally-redundant (LRS), zone redundant (ZRS), geo-redundant (GRS), or geo-zone-redundant (GZRS) storage, however the large file share feature is only supported on locally redundant and zone redundant file shares. Premium file shares do not support any form of geo-redundancy. Premium file shares are available with locally redundancy and zone redundancy in a subset of regions. To find out if premium file shares are currently available in your region, see the products available by region page for Azure. For information about regions that support ZRS, see Azure Storage redundancy. What size file share do you need? In local and zone redundant storage accounts, Azure file shares can span up to 100 TiB, however in geo- and geo-zone redundant storage accounts, Azure file shares can span only up to 5 TiB. For more information on these three choices, see Planning for an Azure Files deployment. Applies to Prerequisites - This article assumes that you have already created an Azure subscription. If you don't already have a subscription, then create a free account before you begin. - If you intend to use Azure PowerShell, install the latest version. - If you intend to use the Azure CLI, install the latest version. Create a storage account Azure file shares are deployed into storage accounts, which are top-level objects that represent a shared pool of storage. This pool of storage can be used to deploy multiple file shares.. To create a storage account via the Azure portal, select + Create a resource from the dashboard. In the resulting Azure Marketplace search window, search for storage account and select the resulting search result. This will lead to an overview page for storage accounts; select Create to proceed with the storage account creation wizard. Basics The first section to complete to create a storage account is labeled Basics. This contains all of the required fields to create a storage account. To create a GPv2 storage account, ensure the Performance radio button is set to Standard and the Account kind drop-down list is selected to StorageV2 (general purpose v2). To create a FileStorage storage account, ensure the Performance radio button is set to Premium and Fileshares is selected in the Premium account type drop-down list. The other basics fields are independent from the choice of storage account: - Storage account name: The name of the storage account resource to be created. This name must be globally unique, but otherwise can any name you desire. The storage account name will be used as the server name when you mount an Azure file share via SMB. - Location: The region for the storage account to be deployed into. This can be the region associated with the resource group, or any other available region. - Replication: Although this is labeled replication, this field actually means redundancy; this is the desired redundancy level: locally redundancy (LRS), zone redundancy (ZRS), geo-redundancy (GRS), and geo-zone-redundancy (GZRS). This drop-down list also contains read-access geo-redundancy (RA-GRS) and read-access geo-zone redundancy (RA-GZRS), which do not apply to Azure file shares; any file share created in a storage account with these selected will actually be either geo-redundant or geo-zone-redundant, respectively. Networking The networking section allows you to configure networking options. These settings are optional for the creation of the storage account and can be configured later if desired. For more information on these options, see Azure Files networking considerations. Data protection The data protection section allows you to configure the soft-delete policy for Azure file shares in your storage account. Other settings related to soft-delete for blobs, containers, point-in-time restore for containers, versioning, and change feed apply only to Azure Blob storage. Advanced The advanced section contains several important settings for Azure file shares: Secure transfer required: This field indicates whether the storage account requires encryption in transit for communication to the storage account. If you require SMB 2.1 support, you must disable this. Large file shares: This field enables the storage account for file shares spanning up to 100 TiB. Enabling this feature will limit your storage account to only locally redundant and zone redundant storage options. Once a GPv2 storage account has been enabled for large file shares, you cannot disable the large file share capability. FileStorage storage accounts (storage accounts for premium file shares) do not have this option, as all premium file shares can scale up to 100 TiB. The other settings that are available in the advanced tab (hierarchical namespace for Azure Data Lake storage gen 2, default blob tier, NFSv3 for blob storage, etc.) do not apply to Azure Files. Important Selecting the blob access tier does not affect the tier of the file share. Tags are name/value pairs that enable you to categorize resources and view consolidated billing by applying the same tag to multiple resources and resource groups. These are optional and can be applied after storage account creation. Review + create The final step to create the storage account is to select the Create button on the Review + create tab. This button won't be available if all of the required fields for a storage account are not filled. Enable large files shares on an existing account Before you create an Azure file share on an existing account, you may want to enable it for large file shares if you haven't already. Standard storage accounts with LRS and ZRS or ZRS can be upgraded to support large file shares. If you have a GRS, GZRS, RA-GRS, or RA-GZRS account, you will need to convert it to an LRS account before proceeding. Open the Azure portal, and navigate to the storage account where you want to enable large file shares. Open the storage account and select File shares. Select Enabled on Large file shares, and then select Save. Select Overview and select Refresh. Select Share capacity then select 100 TiB and Save. Create a file share Once you've created your storage account, all that is left is to create your file share. This process is mostly the same regardless of whether you're using a premium file share or a standard file share. You should consider the following differences. Standard file shares may be deployed into one of the standard tiers: transaction optimized (default), hot, or cool. This is a per file share tier that is not affected by the blob access tier of the storage account (this property only relates to Azure Blob storage - it does not relate to Azure Files at all). You can change the tier of the share at any time after it has been deployed. Premium file shares cannot be directly converted to any standard tier. Important You can move file shares between tiers within GPv2 storage account types (transaction optimized, hot, and cool). Share moves between tiers incur transactions: moving from a hotter tier to a cooler tier will incur the cooler tier's write transaction charge for each file in the share, while a move from a cooler tier to a hotter tier will incur the cool tier's read transaction charge for each file the share. The quota property means something slightly different between premium and standard file shares: For standard file shares, it's an upper boundary of the Azure file share, beyond which end-users cannot go. If a quota is not specified, standard file share can span up to 100 TiB or 5 TiB if the large file shares property is not set for a storage account. If you did not create your storage account with large file shares enabled, see Enable large files shares on an existing account for how to enable 100 TiB file shares. For premium file shares, quota means provisioned size. The provisioned size is the amount that you will be billed for, regardless of actual usage. Also, the performance (IOPs/Mbps) you receive is based on the provisioned size. For more information on how to plan for a premium file share, see provisioning premium file shares. If you just created your storage account, you can navigate to it from the deployment screen by selecting Go to resource. Once in the storage account, select the File shares in the table of contents for the storage account. In the file share listing, you should see any file shares you have previously created in this storage account; an empty table if no file shares have been created yet. Select + File share to create a new. For standard file shares, the quota will also determine what performance you receive. - Tiers: the selected tier for a file share. This field is only available in a general purpose (GPv2) storage account. You can choose transaction optimized, hot, or cool. The share's tier can be changed at any time. We recommend picking the hottest tier possible during a migration, to minimize transaction expenses, and then switching to a lower tier if desired after the migration is complete. Select Create to finishing creating the new share. Note The name of your file share must be all lowercase. For complete details about naming file shares and files, see Naming and referencing shares, directories, files, and metadata. Change the tier of an Azure file share File shares deployed in general purpose v2 (GPv2) storage account can be in the transaction optimized, hot, or cool tiers. You can change the tier of the Azure file share at any time, subject to transaction costs as described above. On the main storage account page, select File shares select the tile labeled File shares (you can also navigate to File shares via the table of contents for the storage account). In the table list of file shares, select the file share for which you would like to change the tier. On the file share overview page, select Change tier from the menu. On the resulting dialog, select the desired tier: transaction optimized, hot, or cool. Expand existing file shares If you enable large file shares on an existing storage account, you must expand existing file shares in that storage account to take advantage of the increased capacity and scale. - From your storage account, select File shares. - Right-click your file share, and then select Quota. - Enter the new size that you want, and then select OK. Next steps - Plan for a deployment of Azure Files or Plan for a deployment of Azure File Sync. - Networking overview. - Connect and mount a file share on Windows, macOS, and Linux.
https://docs.microsoft.com/en-us/azure/storage/files/storage-how-to-create-file-share?WT.mc_id=AZ-MVP-5003408
CC-MAIN-2021-39
refinedweb
1,832
61.67
Let’s see pimpl and its alternatives in a real application! I’ve implemented a small utility app - for file compression - where we can experiment with various designs. Is it better to use pimpl or maybe abstract interfaces? Read on to discover. - Intro - The app - command line file compressor - pimpl version - Abstract Interface version - Comparison - Summary Intro In my previous post I covered the pimpl pattern. I discussed the basic structure, extensions, pros and cons and alternatives. Still, the post might sound a bit “theoretical”. Today I’d like to describe a practical usage of the pattern. Rather than inventing artificial names like MyClass and MyClassImpl you’ll see something more realistic: like FileCompressor or ICompressionMethod. Moreover, this will be my first time when I’ve used Conan to streamline the work with third-party libraries (as we need a few of them). Ok, so what’s the example? The app - command line file compressor As an example, I’ve chosen a utility app that helps with packing files. Basic use case: Users run this utility app in a console environment. A list of files (or directories) can be passed, as well with the name of the output file. The output file will also specify the given compression method: .zip for zip, .bz2 for BZ compression, etc. Users can also run the app in help mode that will list some basic options and available compression methods. When the compression is finished a simple summary: bytes processed and the final size of the output file is shown. Requirements: - a console application - command line with a few options - output file - also specifies the compression method - list of files (also with directory support) - basic summary at the end of the compression process The same can be achieved with command line mode of your favourite archive managers (like 7z). Still, I wanted to see how hard is it to compress a file from C++. The full source code can be found at my GitHub page: GitHub/fenbf/CompressFileUtil. Simple implementation Let’s start simple. When I was learning how to use Conan - through their tutorial - I met a helpful library called Poco: Modern, powerful open source C++ class libraries for building network- and internet-based applications that run on desktop, server, mobile and embedded systems. One thing I’ve noticed was that it supports Zip compression. So all I have to do for the application is to use the library, and the compression is done. I came up with the following solution: Starting from main() and going into details of the implementation: int main(int argc, char* argv[]) { auto inputParams = ParseCommandLine(argc, argv); if (inputParams.has_value()) { auto params = inputParams.value(); RunCompressor(params); } else ShowHelp(); } I won’t discuss the underlying implementation of parsing the command line, let’s skip to RunCompressor() instead: void RunCompressor(const InputParams& params) noexcept { try { FileCompressor compressor; compressor.Compress(params.m_files, params.m_output); } catch (const std::exception& ex) std::cerr << "Error: " << ex.what() << '\n'; catch (...) std::cerr << "Unexpected error\n"; } Ok, so what’s the deal with pimpl or abstract interfaces? The first iteration has none of them :) FileCompressor is declared in FileCompressor.h and is directly included by the file with main() ( CompressFileUtil.cpp): #include <Poco/Zip/Compress.h> class FileCompressor { public: void Compress(const StringVector& vecFileNames, const string& outputFileName); private: void CompressZip(const StringVector& vecFileNames, const string& outputFileName); void CompressOneElement(Poco::Zip::Compress& compressor, const string& fileName); }; The class is straightforward: just one method Compress where you pass vector of strings (filenames) and the file name of the output archive to create. It will check the output file extension and forward the work to CompressZip (only zip for now): void FileCompressor::CompressZip(const StringVector& vecFileNames, const string& outputFileName) { std::ofstream out(outputFileName, std::ios::binary); Poco::Zip::Compress compressor(out, /*seekable output*/true); for (const auto& fileName : vecFileNames) CompressOneElement(compressor, fileName); compressor.close(); } CompressOneElement() uses Poco’s compressor to do all the magic: Poco::File f(fileName); if (f.exists()) { Poco::Path p(f.path()); if (f.isDirectory()) { compressor.addRecursive(p, Poco::Zip::ZipCommon::CL_MAXIMUM, /*excludeRoot*/true, p.getFileName()); } else if (f.isFile()) { compressor.addFile(p, p.getFileName(), Poco::Zip::ZipCommon::CM_DEFLATE, Poco::Zip::ZipCommon::CL_MAXIMUM); } } Please notice two things: - Firstly: all of the private implementation is shown here (no fields, but private methods). - Secondly: types from a third party library are included (might be avoided by using forward declaration). In other words: every time you decide to change the private implementation (add a method or field) every compilation unit that includes the file will have to be recompiled. Now we’ve reached the main point of this article: We aim for pimplor an abstract interface to limit compilation dependencies. Of course, the public interface might also change, but it’s probably less often than changing the internals. In theory, we could avoid Poco types in the header - we could limit the number of private methods, maybe implement static free functions in FileCompressor.cpp. Still, sooner or later we’ll end up having private implementation revealed in the class declaration in one way or another. I’ve shown the basic code structure and classes. But let’s now have a look at the project structure and how those third-party libraries will be plugged in. Using Conan to streamline the work The first iteration only implements the part of requirements, but at least the project setup is scalable and a solid background for later steps. As I mentioned before, with this project I’ve used Conan (Conan 1.0 was released on 10th January, so only a few days ago!) for the first time (apart from some little tutorials). Firstly, I needed to understand where can I plug it in and how can it help. In short: in the case of our application, Conan does all the work to provide other libraries for the project. We are using some third party libraries, but a Conan package can be much more (and you can create your custom ones). To fetch a package you have to specify its name in a special file: conanfile.txt (that is placed in your project directory). It might look as follows: [requires] Poco/1.8.0.1@pocoproject/stable [generators] visual_studio Full reference here docs: conanfile.txt Conan has several generators that do all job for you. They collect information from dependencies, like include paths, library paths, library names or compile definitions, and they translate/generate a file that the respective build system can understand. I was happy to see “Visual Studio Generator” as one of them (your favourite build tools is probably also on the list of Conan’s Generators). With this little setup the magic can start: Now, all you have to do is to run (in that folder) the Conan tool and install the packages. conan install . -s build_type=Debug -if build_debug -s arch=x86 This command will fetch the required packages (or use cache), also get package’s dependencies, install them in a directory (in the system), build the binaries (if needed) and finally generate correct build options (include/lib directories) for your compiler. In the case of Visual Studio in my project folder\build_debug I’ll get conanbuildinfo.props with all the settings. So I have to include that property file in my project and build it…. and it should work :) But why does Conan help here? Imagine what you would have to do to add another library? Each step: - download a proper version of the library - download dependencies, - build all, - install, - setup Visual Studio (or another system) and provide the corrects paths… I hate doing such work. But with Conan replacing libs, playing with various alternatives is very easy. Moreover, Conan managed to install OpenSSL library - a dependency for Poco - and on Windows building OpenSSL is a pain as far as I know. Ok… but where can you find all of the libraries? Have a look here: - Conan Center - Conan Transit - Bincrafters - and their blog - bincrafters.github.io Let’s go back to the project implementation. Improvements, more libs: The first version of the application uses only Poco to handle zip files, but we need at least two more: - Boost program options - to provide an easy way to parse the command line arguments. - BZ compression library - I’ve searched for various libs that would be easy to plug into the project, and BZ seems to be the easiest one. In order to use the libraries, I have to add a proper links/names into conanfile.txt. [requires] Poco/1.8.0.1@pocoproject/stable Boost.Program_Options/1.65.1@bincrafters/stable bzip2/1.0.6@conan/stable Thanks to Bincrafters boost libraries are now divided into separate packages! Still, boost in general has a dense dependency graph (between the libraries), so the program options library that I needed brought a lot of other boost libs. Still, it works nicely in the project. We have all the libraries, so we move forward with the project. Let’s prepare some background work for the support of more compression methods. Compression methods Since we want to have two methods (and maybe more in the future), it’s better to separate the classes. That will work better when we’d like to add another implementation. The interface: class ICompressionMethod { public: ICompressionMethod() = default; virtual ~ICompressionMethod() = default; virtual DataStats Compress(const StringVector& vecFileNames, const string& outputFileName) = 0; }; Then we have two derived classes: ZipCompression- converted from the first implementation. BZCompression- BZ2 compression doesn’t provide archiving option, so we can store just one file using that method. Still, it’s common to pack the files first (like using TAR) and then compress that single file. In this implementation, for simplicity, I’ve used Zip (fastest mode) as the first step, and then BZ compresses the final package. There’s also a factory class that simplifies the process of creating required classes… but I’ll save the details here for now. We have all the required code, so let’s try with pimpl approach: pimpl version The basic idea of the pimpl patter is to have another class “inside” a class we want to divide. That ‘hidden’ class handles all the private section. In our case, we need CompressorImpl that implements the private details of FileCompressor. The main class looks like that now: class FileCompressor { public: FileCompressor(); ~FileCompressor(); // movable: FileCompressor(FileCompressor && fc) noexcept; FileCompressor& operator=(FileCompressor && fc) noexcept; // and copyable FileCompressor(const FileCompressor& fc); FileCompressor& operator=(const FileCompressor& fc); void Compress(const StringVector& vecFileNames, const string& outputFileName); private: class CompressorImpl; const CompressorImpl* Pimpl() const { return m_pImpl.get(); } CompressorImpl* Pimpl() { return m_pImpl.get(); } std::unique_ptr<CompressorImpl> m_pImpl; }; The code is longer than in the first approach. This is why we have to do all the preparation code: - in the constructor we’ll create and allocate the private pointer. - we’re using unique_ptrso destructor must be defined in cppfile in order not to have compilation problem (missing deleter type). - the class is move-able and copyable so additional move and copy constructors are required to be implemented. CompressorImplis forward declared in the private section Pimplaccessors are required to implement constmethods properly. See why it’s essential in my previous post. And the CompressorImpl class: class FileCompressor::CompressorImpl { public: CompressorImpl() { } void Compress(const StringVector& vecFileNames, const string& outputFileName); }; Unique pointer for pimpl is created in the constructor of FileCompressor and optionally copied in the copy constructor. Now, every method in the main class needs to forward the call to the private, like: void FileCompressor::Compress(const StringVector& vecFileNames, const string& outputFileName) { Pimpl()->Compress(vecFileNames, outputFileName); } The ‘real’ Compress() method decides which Compression method should be used (by the extension of the output file name) and then creates the method and forwards parameters. Ok… but what’s the deal with having to implement all of that additional code, plus some boilerplate, plus that pointer management and proxy methods… ? How pimpl broke dependencies? The reason: Breaking dependencies. After the core structure is working we can change the private implementation as much as we like and the client code (that includes FileCompressor.h) doesn’t have to be recompiled. In this project, I’ve used precompiled headers, and what’s more the project is small. But it might play a role when you have many dependencies. Another essential property of pimpl is ABI compatibility; it’s not important in the case of this example, however. I’ll return to this topic in a future blog post. Still, what if the whole compression code, with the interface, sit into a different binary, a separate DLL? In that case, even if you change the private implementation the ABI doesn’t change so you can safely distribute a new version of the library. Implementing more requirements Ok… so something should work now, but we have two more elements to implement: - showing stats - showing all available compression methods How to do it in the pimpl version? In case of showing stats: Stats are already supported by compression methods, so we just need to return them. So we declare a new method in the public interface: class FileCompressor { ... void ShowStatsAfterCompression(ostream& os) const; }; This will only be a proxy method: void FileCompressor::ShowStatsAfterCompression(ostream& os) const { Pimpl()->ShowStatsAfterCompression(os); } (Here’s the place where this Pimpl accessors kicks in, it won’t allow us to skip const when the private method inside CompressorImpl is declared). And… at last, the actual implementation: void FileCompressor::CompressorImpl ::ShowStatsAfterCompression(ostream& os) const { os << "Stats:\n"; os << "Bytes Read: " << m_stats.m_bytesProcessed << "\n"; os << "Bytes Saved: " << m_stats.m_BytesSaved << "\n"; } So much code… just for writing a simple new method. Ok… by that moment I hope you get the intuition how pimpl works in our example. I’ve prepared another version that uses abstract interface. Maybe it’s cleaner and easier to use than pimpl? Abstract Interface version If you read the section about compression methods - where ICompressionMethod is introduced, you might get an idea how to add such approach for FileCompressor. Keep in mind that we want to break physical dependency between the client code. So that’s why we can declare abstract interface, then provide some way to create the actual implementation (a factory?). The implementation will be only in cpp file so that the client code won’t depend on it. class IFileCompressor { public: virtual ~IFileCompressor() = default; virtual void Compress(const StringVector& vecFileNames, const string& outputFileName) = 0; static unique_ptr<IFileCompressor> CreateImpl(); }; And then inside cpp file we can create the final class: class FileCompressor : public IFileCompressor { public: void Compress(const StringVector& vecFileNames, const string& outputFileName) override; void ShowStatsAfterCompression(ostream& os) const override; private: DataStats m_stats; }; And the factory method: unique_ptr<IFileCompressor> IFileCompressor::CreateImpl() { return unique_ptr<IFileCompressor>(new FileCompressor()); } Can that work? How abstract interface broke dependencies? With abstract interface approach, we got into a situation where the exact implementation is declared and defined in a separate cpp file. So if we change it, there’s no need to recompile clients code. The same as we get with pimpl. Was it easier than pimpl? Yes! No need for special classes, pointer management, proxy methods. When I implemented this is was much cleaner. Why might it be worse? ABI compatibility. If you want to add a new method to the public interface, it must be a virtual one. In pimpl, it can be a normal non-virtual method. The problem is that when you use a polymorphic type, you also get a hidden dependency on its vtable. Now, if you add a new virtual method vtable might be completely different, so you cannot be sure if that will work in client’s code. Also, ABI compatibility requires Size and Layout of the class to be unchanged. So if you add a private member, that will change the size. Comparison Let’s roughly compare what’s we’ve achieved so far with pimpl and abstract interface. Summary This was a fun project. We went from a straightforward implementation to a version where we managed to limit compilation dependencies. Two methods were tested: pimpl and abstract interface. Personally, I prefer the abstract interface version. It’s much easier to maintain (as it’s only one class + interface), rather than a class that serves as a proxy plus the real private implementation. What’s your choice? Moreover, I enjoyed working with Conan as a package manager. It significantly improved the developments speed! If I wanted to test a new library (a new compression method), I just had to find the proper link and update conanfile.txt. I hope to have more occasion to use this system. Maybe even as a producer of a package. And here I’d like to thank JFrog-Conan for sponsoring and helping in writing this blog post. But that’s not the end! Next time I hope to improve the code and return with an example of a separate DLL and see what’s that ABI compatibility… and how that works.
https://www.bfilipek.com/2018/01/pimpl-interface.html
CC-MAIN-2020-40
refinedweb
2,821
54.93
0 Hello everyone, This piece of C# code does not produce any overflow exception. wordsize is a constant equal to 32. the x and y can be very big at the computation time. So big that long or decimal even cant hold. But C# handles the problem even the value of the variables exceeds its limits. The computation gives thr right result.(I dont know how it does it) /** * Perform a right "spin" of the word. The rotation of the given * word <em>x</em> is rotated left by <em>y</em> bits. * Only the <em>lg(wordSize)</em> low-order bits of <em>y</em> * are used to determine the rotation amount. Here it is * assumed that the wordsize used is a power of 2. * * @param x word to rotate * @param y number of bits to rotate % wordSize */ private int RotateRight(int x, int y) { return ((int)(((uint) x >> (y & (wordSize-1))) | (uint)(x << (wordSize - (y & (wordSize-1)))))); } I tried to convert it into VB.NET like below. But it always gives an overflow exception. Private Function RotateRight(ByVal x As Integer, ByVal y As Integer) As Integer Return (CInt(Fix((CUInt(x) >> (y And (wordSize - 1))) Or CUInt(x << (wordSize - (y And (wordSize - 1))))))) End Function What can be the reason? How can I solve it? Can you write a better VB.NET equivalent of the C# code above?
https://www.daniweb.com/programming/software-development/threads/261401/overflow-exception-very-large-numbers
CC-MAIN-2017-43
refinedweb
231
76.01
Creating a keypress signal from application button Hello Qt devs! As the title refers to, I'm trying to implement an application button to have the same functionality as when I press "arrow key down" on my keyboard. I need to use signals and slots here right? I have tried with this: @connect(ui.buttonOne, SIGNAL( clicked() ), QApplication::instance(), SLOT( keyPressEvent(Qt::Key_Down) )); @ I'm unsure what I need to have as receiver. - Where I currently have "QApplication::instance()". But perhaps I'm way off here? Thank you for your time! - keyPressEvent isn't slot. - signal with params can't connected to slot with params. - and of course, you can't set constant param to slot in connect definition. you need write slot and send event from it something like: @connect(ui.buttonOne, SIGNAL( clicked() ), QApplication::instance(), SLOT( keyDownSlot())); ... void keyDownSlot() { QKeyEvent event(QEvent::KeyPress, Qt::Key_Down, Qt::NoModifier); QApplication::sendEvent(mainWindow, &event); }@ Thank you for your reply Vass! The argument "mainWindow" in your above post line 9, is the receiver - which is the widget to get the event, right? When I insert my widget it doesn't work. Any idea what to do? [quote author="maxmotor" date="1316006856"] The argument "mainWindow" in your above post line 9, is the receiver - which is the widget to get the event, right? [/quote] Right. What are widget you insert? Yes and no, just sending a keyPress event does not do the same as a real key press. First of all key events are sponataneous events... second, the release event is missing You can have a look at QtTest, how they do it. They have possibilities to simulate key events there. I think what you really want to do is not simulate the key event, but rather connect your signal to a slot that does the same thing as the key event. QTableWidget might already have such a slot. (Unless you are looking for other side effects than just the functionality provided by the key press.) Edit: No, there does not seem to be such a slot, but you could create your own slot that uses the QTableView::moveCursor() function. [quote author="ludde" date="1316011758"]I think what you really want to do is not simulate the key event, but rather connect your signal to a slot that does the same thing as the key event.[/quote] Yes, this is what I want :) I don't understand how the moveCursor() function can be used? Maybe I need to tell you that the software I'm working on will run on a piece of hardware with some hardware buttons and a touch screen. I want the user to be able to press either an assigned hardware button or simply click the GUI button on the screen - the effect should be the same. I hope I'm expressing myself clear enough! :) Thank you for all the inputs! Did you look at the documentation of moveCursor()? You simply pass en enum value as the first argument, e.g. QAbstractItemView::MoveDown for moving down. The second argument can just be Qt::NoModifier, unless you want to also simulate the use of shift / control buttons. Or maybe your problem was that it is a protected method? You need to subclass QTableView and put your slot there to be able to use it. I'm sorry. As you might already guessed I'm new to Qt - and I'm not really that experienced in C++ either. The compiler does indeed complain about it being a protected method. So I need to subclass QTableView into my class. Something like this?: [EDIT: Notice the below code is oh so very wrong. Don't use it :) But I guess you already knew ] @ class QTableView : public MyClass { void QTableView::keyDownSlot(){ ui.tableWidget->moveCursor(QAbstractionItemView::MoveDown, Qt::NoModifier); } }; @ And then I should be able to use the slot in MyClass? Is it something like this? I'm trying to make it work but I keep getting errors.. No offence, but it looks like you might need to learn some basic C++ to actually get that to work... :) Yes, what you need to do is something like the above, but not quite. You need a constructor for your class, and you need to declare your slot as a public slot. And you've got the inheritance order the wrong way around. You should be able to find out how to subclass a Qt widget class from some example. I'd say at least 50% of writing a Qt application is about subclassing existing Qt classes, so it's a good idea to learn how to do that properly. Hm your right ludde. From the looks of it I do indeed need to learn some basic C++. My attempt at writing some code failed miserably. I don't know what I was thinking. Do I dare to try again? :) I will try to explain my overall structure. So please bear with me. I have a Parent_ui class which inherits from QWidget. This Parent_ui holds some basic setup of my windows. This is inherited in all my ui's in order to setup the same window size etc. It is in all these ui's I want to implement something to handle a press of a GUI button (Must function the same way as if I use the arrow keys on my keyboard). Okay, so in order to achieve my goal, I also need to inherit QTableView in my Parent_ui (Multiple inheritance)? I see that QTableView inherits (not all functions) from QWidget. Does this mean I can just entirely delete QWidget as my parent/base class and use the QTableView instead? I can't think anymore tonight. Too tired. Looking forward to your replies. I am very grateful for your time and patience. Could this be a possible structure? Or would it be possible to subclass both QWidget and QTableView in Parent_ui? I'm having a hard time figuring this out :( EDIT: Hm - Just tried creating a separate class for holding my slot like my diagram above shows. @void Test_class::keyDownSlot(QTableView widget) { widget.moveCursor(QAbstractItemView::MoveDown, Qt::NoModifier); } @ I guess I'm still far away from a solution :( I'm sorry, but that picture does not say much to me... Looks like you are using Qt Designer to design your widgets, which is something I have never done (and hopefully never will do :). So someone else will have to help you with that. Regarding multiple inheritance, you cannot inherit from two QObject subclasses, so that's not an option. I don't know what you are using your QWidgets for, but maybe what you want to do is something like this: Create a subclass of QTableView, e.g. MyTableView, which has a couple of new slots moveUp(), moveDown() etc. Create a subclass of QWidget, MyWidget that has a layout and contains some buttons and an instance of MyTableView. Connect the clicked() signals of the buttons to the corresponding signals in the MyTableView instance, e.g. in the MyWidget constructor. Hope this helps. Thank you so much ludde! What you describe is almost what I sketch in my diagram. The only difference I guess is that I had all my UI's have an instance of my QTableView subclass. Of course it should be MyWidget (In my case Parent_ui) that should have the instance of the QTableView subclass. I will try this out! Thank you for your time! EDIT: Come to think about it, in my case the subclasses of Parent_ui needs the instance of MyTableView. This is because it is here the buttons and QTableView is created. I get this error when trying to build: error: 'QTableView& QTableView::operator=(const QTableView&)' is private The header file of MyTableView looks like this: @#include "qtableview.h" class MyTableView: public QTableView { Q_OBJECT; public: MyTableView(QWidget* parent = 0); virtual ~MyTableView(); public slots: void key_down(); void key_up(); };@ Do I need to change something here? Or does it look right? First, not related with your problem things: - ';' not needed after Q_OBJECT - it's macros - 'virtual' keyword for destructor not needed in your class, because it's already defined as virtual in base class. Second, your error: Can you show line where error was happen? For subclasses of QObject assignment operator and copy constructor always are private. - Okay - I'll correct that. - When I remove the virtual keyword I get a warning: "Class "MyTableView" has virtual method 'qt_metacall' but non-virtual destructor" - I get the error in line 3 in the code showed in my previous post. I will add the code again, with the changes you mentioned. @#include "qtableview.h" class MyTableView: public QTableView { Q_OBJECT public: MyTableView(QWidget* parent = 0); ~MyTableView(); public slots: void key_down(); void key_up(); };@ Thank you for your time. - didn't you forget implement destructor body? - Ok, please, show code line where you create instance of MyTableView class or line where you use this instance as parameter of method I think the build error probably has nothing to do with the definition of your MyTableView class, but rather how you use it. Maybe you are using an assignment with a MyTableView object somewhere, where you should really be assigning a pointer? My setup.h file: @#include "ui_setup.h" #include "parent_ui.h" #include "mytableview.h" class Setup: public Parent_ui { Q_OBJECT public: Setup(QWidget *parent = 0); ~Setup(); MyTableView myTableViewInstance; private: Ui::SetupClass ui; void createActions(); private slots: void up(); void down(); void enter(); void back(); };@ My setup.cpp file: @#include "setup.h" #include <QListWidget> Setup::Setup(QWidget *parent) : Parent_ui(parent) { ui.setupUi(this); Parent_ui::ui.headerLabel->setText("SETUP"); myTableViewInstance = new MyTableView(); } Setup::~Setup() { } @ The error I get when calling "myTableViewInstance = new MyTableView();": 'QWidget' is an inaccessible base of 'MyTableView' It's because you are assigning a pointer to an object. myTableViewInstance has to be a pointer. ludde are right: in your setup.h file @ ... MyTableView *myTableViewInstance; ... @ That was it, thank you :) Okay to get back to the subject (Which I slowly turned away from introducing other challenges :) ). I have made a slot in MyTableView: @void MyTableView::key_down(){ QTableView::moveCursor(QAbstractItemView::MoveDown, Qt::NoModifier); }@ This is then used in my setup.cpp file: @void Setup::createActions() { QObject::connect(ui.buttonTwo, SIGNAL(clicked()), this, SLOT(myTableViewInstance->key_down())); }@ This has no effect on my QTableWidget though. But I guess it's me and my coding which is faulty again. Can you see from my code snippets what I'm doing wrong? @ connect(ui.buttonTwo, SIGNAL(clicked()), myTableViewInstance, SLOT(key_down())); @ I get this error: 'QObject' is an inaccessible base of 'MyTableView' Please show MyTableView constructor implementation It is empty :/ @MyTableView::MyTableView(QWidget* parent) : QTableView(parent){ }@ oh... I haven't more ideas :) Try change @#include "qtableview.h"@ to @#include <QTableView>@ if nothing changes, just put all your sources to file hosting and get me link :) I have sent you a link :) Oh... many points: - In your sources @class MyTableView: private QTableView {@ although, in example above you wrote: @class MyTableView: public QTableView {@ - You don't needed MyTableView, you already have QTabletWidget on form - You don't needed inheritance in this case. - In setup.cpp I rewrite some things: It's for local slot, because MyTableView not needed anymore @connect(ui.buttonTwo, SIGNAL(clicked()), this, SLOT(down()));@ in slot, as example, you can add any checks and other logic to their: @void Setup::down() { Parent_ui::ui.tableWidget->selectRow(Parent_ui::ui.tableWidget->currentRow() + 1); }@ same for up slot: @void Setup::up() { Parent_ui::ui.tableWidget->selectRow(Parent_ui::ui.tableWidget->currentRow() -1); }@ Vass you are very kind! I will have a look at this the first thing in the morning. Especially you and ludde have been a big help so far dealing with my lack of Qt/C++ skills. Thank you guys! I just wanted to tell you that my code is now working as intended! - Thanks to you! I'm very impressed of the willingness to help out on this forum. And the fast response was superb. I'm almost positive that we will talk again! ;) Thank you so much for your time! [quote author="maxmotor" date="1316166090"]I just wanted to tell you that my code is now working as intended![/quote] Glad to hear! :) However, I highly recommend you learning C++ - it just save your time in future
https://forum.qt.io/topic/9493/creating-a-keypress-signal-from-application-button
CC-MAIN-2017-39
refinedweb
2,040
66.33
Sorry for the old question. I have clarified it. How can I start an stop thread with my poor thread class ? EDIT : It is in loop, I want to restart it again at the beginning of the code. How can I do start-stop-restart-stop-restart ? my class ; import threading class Concur(threading.Thread): def __init__(self): self.stopped = False threading.Thread.__init__(self) def run(self): i = 0 while not self.stopped: time.sleep(1) i = i + 1 inst = Concur() while conditon: inst.start() #after some operation inst.stop() #some other operation This is David Heffernan's idea fleshed-out. The example below runs for 1 second, then stops for 1 second, then runs for 1 second, and so on. import time import threading import datetime as DT import logging logger = logging.getLogger(__name__) def worker(cond): i = 0 while True: with cond: cond.wait() logger.info(i) time.sleep(0.01) i += 1 logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s %(threadName)s] %(message)s', datefmt='%H:%M:%S') cond = threading.Condition() t = threading.Thread(target=worker, args=(cond, )) t.daemon = True t.start() start = DT.datetime.now() while True: now = DT.datetime.now() if (now-start).total_seconds() > 60: break if now.second % 2: with cond: cond.notify()
https://codedump.io/share/KXZX50qfHq6k/1/how-to-start-and-stop-thread
CC-MAIN-2017-26
refinedweb
211
56.62
Path that points to a list of hierarchical nodes. More... #include <Inventor/SoPath.h> Path that points to a list of hierarchical nodes. A path represents a scene graph or subgraph. It contains a list of nodes forming a chain from some root to some descendant. Each node in the chain is a child of the previous node. Paths are used to refer to some object in a scene graph precisely and unambiguously, even if there are many instances of the object. Therefore, paths are returned by both the SoRayPickAction and SoSearchAction. When an action is applied to a path, only the nodes in the subgraph defined by the path are traversed. These include: the nodes in the path chain, all nodes (if any) below the last node in the path, and all nodes whose effects are inherited by any of these nodes. SoPath attempts to maintain consistency of paths even when the structure of the scene graph changes. For example, removing a child from its parent when both are in a path chain cuts the path chain at that point, leaving the top part intact. Removing the node to the left of a node in a path adjusts the index for that node. Replacing a child of a node when both the parent and the child are in the chain replaces the child in the chain with the new child, truncating the path below the new child. Hidden children Note that only public children of nodes are accessible from an SoPath. Nodes like node kits limit access to their children and these "hidden children" will not be visible using the SoPath methods. For example, if your application does picking and gets a path from SoRayPickAction, the actual last node in the path (tail) will normally be a shape node. But if that shape is part of a node kit, then the getTail() method will return the node kit, not the shape node. To access all hidden children in the path, simply cast the path object to SoFullPath before calling get methods. To access hidden node kit children (but not all children) in the path, cast the path object to SoNodeKitPath before calling get methods. [C++] Reference counting: Note that the indices in a written path are adjusted based on the nodes that are actually written to a file. Since nodes in the graph that have no effect on the path (such as some separator nodes) are not written, the siblings of such nodes must undergo index adjustment when written. The actual nodes in the graph remain unchanged. SoPath is not able to write "per instance" information to a file for instancing nodes like SoMultipleInstance and SoMultipleCopy. The saved path will reference the whole set of instances under SoMultipleInstance or SoMulitpleCopy node. SoFullPath, SoNode, SoRayPickAction, SoSearchAction, SoNodeKitPath Constructs an empty path. Constructs a path with a hint to length (number of nodes in chain). Constructs a path and sets the head node to the given node. Adds all nodes in fromPath's chain to end of chain; the head node of fromPath must be the same as or a child of the current tail node. Reimplemented in SoNodeKitPath. Adds node to end of chain; uses the first occurrence of childNode as child of current tail node. If the path is empty, this is equivalent to setHead(childNode) . Adds node to end of chain; the node is the childIndex'th child of the current tail node. Returns TRUE if the node type is found anywhere in the path chain. Returns TRUE if the node is found anywhere in the path chain. Returns TRUE if the nodes in the chain in the passed path are contained (in consecutive order) in this path chain. Creates and returns a new path that is a copy of some or all of this path. Copying starts at the given index (default is 0, which is the head node). A numNodes of 0 (the default) means copy all nodes from the starting index to the end. Returns NULL on error. If the two paths have different head nodes, this returns -1. Otherwise, it returns the path chain index of the last node (starting at the head) that is the same for both paths. Reimplemented in SoNodeKitPath. Method to return paths with a given name. Paths are named by calling their setName() method (defined by the SoBase class). This method appends all paths with the given name to the given path list and returns the number of paths that were added. If there are no paths with the given name, zero will be returned and nothing will be added to the list. Method to return a path with a given name. Paths are named by calling their setName() method (defined by the SoBase class). This method returns the last path that was given the specified name, either by setName() or by reading in a named path from a file. If there is no path with the given name, NULL will be returned. Returns the first node in a path chain. Returns the index of the i'th node (within its parent) in the chain. Returns the index of the i'th node (within its parent) in the chain, counting backward from the tail node. Passing 0 for i returns the index of the tail node. Reimplemented in SoFullPath. Returns the index of the instance inside the parent SoMultipleInstance, SoMultipleCopy or SoArray group. The returned value is -1 for other parent nodes. Returns the index of the i'th node instance (within its parent, if it is a SoMultipleInstance, SoMultipleCopy or SoArray group in the chain, counting backward from the tail node. Passing 0 for i returns the instance index of the tail node. Reimplemented in SoFullPath. Returns length of path chain (number of nodes). Reimplemented in SoNodeKitPath, and SoFullPath. Returns the first node and its index, from the head of the given type in the chain. NULL is returned and the index is set to -1 if no node of the given type is found. Returns the i'th node (within its parent) in the chain. Calling getNode(0) is equivalent to calling getHead(). Reimplemented in SoNodeKitPath. Returns the i'th node (within its parent) in the chain, counting backward from the tail node. Passing 0 for i returns the tail node. Reimplemented in SoNodeKitPath, and SoFullPath. Returns the last node in a path chain. Reimplemented in SoNodeKitPath, and SoFullPath. Returns type identifier for path instance. Implements SoTypedObject. The push() and pop() methods allow a path to be treated as a stack; they push a node at the end of the chain and pop the last node off. Reimplemented in SoNodeKitPath, and SoFullPath. Truncates the path chain, removing all nodes from index start on. Calling truncate(0) empties the path entirely. Reimplemented in SoNodeKitPath. Writes the path to the specified output stream. Returns TRUE if all nodes in the two path chains are identical. Reimplemented in SoNodeKitPath. Reimplemented in SoFullPath.
https://developer.openinventor.com/refmans/latest/RefManCpp/class_so_path.html
CC-MAIN-2021-25
refinedweb
1,162
74.19
The repository for high quality TypeScript type definitions. Also see the definitelytyped.org website, although information in this README is more up-to-date. You can also read this README in Spanish! See the TypeScript handbook.="" />. These can be used by TypeScript 1.0. masterbranch of this repository.Typed. First, fork this repository, install node, and run npm install. cd types/my-package-to-edit Definitions bysection of the package header. // Definitions by: Alice <>, Bob <>. typescript // Definitions by: Alice <> // Bob <> // Steve <> // John <>. If you are the library author, members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down. For a good example package, see base64-js.. When a package bundles its own types, types should be removed from DefinitelyTyped. sourceRepoURL: This should point to the repository that contains the typings. libraryName: Descriptive name of the library, e.g. Angular 2instead. To lint a package, just add a tslint.json to that package containing { "extends": "dtslint/dt.json" }. All new packages must be linted.. @typespackages on NPM? The master branch is automatically published to the @types scope on NPM thanks to types-publisher.Typed team member before being merged, so please be patient as human factors may cause delays. Check the PR Burndown Board to see progress as maintainers work through the open PRs. @typesNPM package be updated? NPM packages should update within a few hours. If it's been more than 24 hours, ping @RyanCavanaugh and @andy-ms on the PR to investigate. <reference types="" />or an import? If the module you're referencing is an external module (uses export), use an import. If the module you're referencing is an ambient module (uses declare module, or just declares globals), use <reference types="" />. package.jsonhere.. tslint.json, and some tsconfig.jsonare missing "noImplicitAny": true, "noImplicitThis": true, or "strictNullChecks": true. Then they are wrong. You can help by submitting a pull request to fix them. Here are the currently requested definitions. If types are part of a web standard, they should be contributed to TSJS-lib-generator so that they can become part of the default lib.dom.d.ts.. Then you will have to add a comment to the last line of your definition header (after // Definitions:): // TypeScript Version: 2.1.Typed and deprecate the associated @types package. If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. v2, and copy existing files to it. If so, you will need to: tsconfig.jsonas well as tslint.json. For example history v2 tsconfig.json looks like: { "compilerOptions": { "baseUrl": "../../", "typeRoots": ["../../"], "paths": { "history": [ "history/v2" ] }, }, "files": [ "index.d.ts", "history-tests.ts" ] } If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version. For example, react-router depends on history@2, so react-router tsconfig.json has a path mapping to "history": [ "history/v2" ]; transitively react-router-bootstrap (which depends on react-router) also adds a path mapping in its tsconfig.json."] } } GitHub doesn't support file history for renamed files. Use git log --follow instead., or to use a default import like import foo from "foo"; if using the --allowSyntheticDefaultImports flag if your module runtime supports an interop scheme for non-ECMAScript modules as such. This project is licensed under the MIT license. Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.
https://recordnotfound.com/DefinitelyTyped-DefinitelyTyped-83
CC-MAIN-2018-47
refinedweb
604
60.82
I am a .net developer, trying my hands on nodejs web api development. I was wondering that whether we can create models in nodejs same as we create in asp.net web api. For example public class BaseResponse { public bool Success { get; set; } public string ErrorMessage { get; set; } } public class MovieResponse : BaseResponse { public int MovieId { get; set; } public string MovieName { get; set; } } There's good news and there's bad news. The bad news is the concept of classes and inheritance as you know it from other languages is not supported. The good news, JavaScript attempted to do something along that idea (although it did a miserable job implementing it). Below is an example of the code you provided using JavaScript: function BaseResponse(success, errorMessage) { this.success = success; this.errorMessage = errorMessage; } function MovieResponse(success, errorMessage, movieId, movieName) { BaseResponse.call(this, success, errorMessage); // Call the base class's constructor (if necessary) this.movieId = movieId; this.movieName = movieName; } MovieResponse.prototype = Object.create(BaseResponse); MovieResponse.prototype.constructor = MovieResponse; /** * This is an example of an instance method. */ MovieResponse.prototype.instanceMethod = function(data) { /*...*/ }; /** * This is an example of a static method. Notice the lack of prototype. */ MovieResponse.staticMethod = function(data) {/* ... */ }; // Instantiate a MovieResponse var movieResInstance = new MovieResponse(); Mozilla has really good documentation on JavaScript and classes. In the code above, you are creating two functions BaseResponse and MovieResponse. Both of these functions act as constructors for an object with the appropriate "class" when you use the new keyword. You specify that MovieResponse inherits from BaseMovie with MovieResponse.prototype = [Object.create]()(BaseResponse). This effectively sets MovieResponse's prototype chain equal to BaseResponse's prototype chain. You'll notice that immediately after setting MovieResponse's prototype chain I have to set its constructor to point to MovieResponse. If I didn't do this, every time you tried to initialize a MovieResponse, JavaScript would try to instead instantiate a BaseResponse (I told you they did a horrible job). The rest of the code should be relatively straightforward. You can create instance methods on your brand new, shiny class by defining them on the prototype chain. If you define a function on BaseResponse that is not defined on MovieResponse but call the function on an instance of MovieResponse, JavaScript will "crawl" the prototype chain until it finds the function. Static methods are defined directly on the constructor itself (another weird feature). Notice there is no concept of types or access modifiers (public/private). There are runtime tricks that you can implement to enforce types, but it's usually unnecessary in JavaScript and more prone to errors and inflexibility than adding such checks may justify. You can implement the concept of private and protected members of a class in a more straightforward method than types. Using Node's require(), and assuming you wanted a private function called privateMethod you could implement it as: function privateMethod() { /* privateMethod definition */ } // Definition for MovieResponse's constructor function MovieResponse() { /*...*/ } module.exports = MovieResponse; I will add a somewhat required commentary that I do not agree with: it is unnecessary to use inheritance in JavaScript. JavaScript uses a notion coined "duck typing" (if it looks like a duck and sounds like a duck, its a duck). Since JavaScript is weakly typed, it doesn't care if the object is a BaseResponse or MovieResponse, you can call any method or try to access any field you want on it. The result is usually an error or erroneous/error-prone code. I mention this here because you may come across the notion and its supporters. Know that such programming is dangerous and results in just bad programming practices.
https://codedump.io/share/Y0hV3VZ4sM9D/1/how-to-create-models-in-nodejs
CC-MAIN-2017-43
refinedweb
599
56.05
Pylons Project Documentation Style Guide¶ Introduction¶ This document is aimed at authors of and contributors to documentation for projects under the Pylons Project. This document describes style and reStructuredText syntax used in project documentation. We provide examples, including reStructuredText code and its rendered output, for both visual and technical reference. The source code of this guide is located in its project repository on GitHub. For Python coding style guidelines, see Coding Style. We have adopted the convention from RFC 2119 for key words. Other conventions throughout this guide are adopted and adapted from Documenting Python, Plone Documentation Style Guide, and Write The Docs. Contributing to a project's documentation¶ All projects under the Pylons Projects follow the guidelines established at How to Contribute. When submitting a pull request for the first time in a project, sign its CONTRIBUTORS.txt and commit it along with your pull request. Contributors to documentation should be familiar with reStructuredText (reST) for writing documentation. Most projects use Sphinx to build documentation from reST source files, and Read The Docs (RTD) for publishing them on the web. Experience with Sphinx and RTD may be helpful, but not required. Testing Documentation¶ Before submitting a pull request, documentation should be tested locally. Ultimately testing of documentation must be done before merging a pull request. This is typically done through a project's integration with Travis CI or Appveyor. - Use Sphinx's make htmlcommand to build the HTML output of the documentation without errors or warnings. Some projects use tox -e docsor just toxto invoke Sphinx's make html. Most other build utilities like restview and readme_renderer test only a single file and do not support cross-references between files. - If documentation has doctests and uses sphinx.ext.doctest, then run Sphinx's make doctestcommand. - Optionally use Sphinx's make linkcheckcommand to verify that links are valid and to avoid bit rot. It is acceptable to ignore broken links in a project's change log and history. Narrative and API documentation should occasionally have its links checked. - Optionally use Sphinx's make epuband make latexpdfor make xelatexcommands to build epub or PDF output of the documentation. This project's repository has an example of how to configure Sphinx, tox, and Travis to build documentation. Documentation structure¶ This section describes the structure of documentation and its files. Location¶ Documentation source files should be contained in a folder named docs located at the root of the project. Images and other static assets should be located in docs/_static. reST directives must refer to files either relative to the source file or absolute from the top source directory. For example, in docs/narr/source.rst, you could refer to a file in a different directory as either: .. include:: ../diff-dir/diff-source.rst or: .. include:: /diff-dir/diff-source.rst. File naming¶ reST source files and static assets should have names that consist only of lowercase letters ( a-z), numbers ( 0-9), periods ( .), and hyphens ( -) instead of underscores ( _). Files must start a letter. reST source files should have the extension of .rst. Image files may be any format, but must have standard file extensions that consist of three letters ( .gif, .jpg, .png, .svg). .gif and .svg are not currently supported by PDF builders in Sphinx. However you can use an asterisk ( *) as a wildcard extension instead of the actual file extension. This allows the Sphinx builder to automatically select the correct image format for the desired output. For example: .. image:: ../_static/pyramid_request_processing.* will select the image pyramid_request_processing.svg for the HTML documentation builder, and pyramid_request_processing.png for the PDF builder. See the related Stack Overflow post. Index¶ Documentation must have an index file whose purpose is to serve as a home page for the documentation, including references to all other pages in the documentation. The index file should be named index.rst. Each section, or a subdirectory of reST files such as a tutorial, must contain an index.rst file. The index should contain at least a Table of contents through the toctree directive. The index should include a reference to both a search page and a general index page, which are automatically generated by Sphinx. See below for an example. * :ref:`genindex` * :ref:`search` Glossary¶ Documentation may have a glossary file. If present, it must be named glossary.rst. This file defines terms used throughout the documentation. Its content must begin with the directive glossary. An optional sorted argument should be used to sort the terms alphabetically when rendered, making it easier for the user to find a given term. Without the argument sorted, terms will appear in the order of the glossary source file. Example: .. glossary:: :sorted: voom Theoretically, the sound a parrot makes when four-thousand volts of electricity pass through it. pining What the Norwegien Blue does when it misses its homeland, for example, pining for the fjords. The above code renders as follows. - pining - What the Norwegian Blue does when it misses its homeland, for example, pining for the fjords. - voom - Theoretically, the sound a parrot makes when four-thousand volts of electricity pass through it. References to glossary terms appear as follows. :term:`voom` Note it is hyperlinked, and when clicked it will take the user to the term in the Glossary and highlight the term. Change history¶ Either a reference to a change history log file in the project or its inclusion in the documentation should be present. Change history should include feature additions, deprecations, bug fixes, release dates and versions, and other significant changes to the project. General guidance¶ This section describes the general voice, tone, and style that documentation should follow. It also includes things for authors to consider when writing to your audience. Accessibility¶ Consider that your audience includes people who fall into the following groups: - People who do not use English as their first language (English language rules are insanely complex). According to our web statistics for docs.pylonsproject.org, about 36% of all readers of documentation under the Pylons Project do not use English as their first language. And only about 32% of all visitors are from the United States, United Kingdom, Canada, Australia, New Zealand, and Ireland. - Visually impaired readers (a comma makes a huge difference to a screen reader, adding a "breath", much like a musical breath symbol). - Readers who don't have college-level reading comprehension. - Folks with reading disabilities. Voice¶ It is acceptable to address the reader as "you". This helps make documentation, especially tutorials, more approachable. "You" is also less formal than "the user". Avoid sentence run-ons¶ Instead of using long sentences, consider breaking them into multiple shorter sentences. Long complicated sentences are more difficult to understand than shorter, clearer sentences. Consider that your audience is not familiar with your content. That is why they are reading your documentation. Gender¶ Except for speaking for oneself, the author should avoid using pronouns that identify a specific gender. Neutral gender pronouns "they", "them", "their", "theirs", "it", and "its" are preferred. Never use the hideous and clumsy "he/she". Style¶ Avoid hype and marketing. Avoid words that can frustrate or discourage the reader if they are not able to complete or understand a concept. Such words include "simple", "just", "very", "easy", and their derivations. For example, "Simply run the command foo bar, and you're up and running!" will frustrate a user who has neither installed the requirements for foo nor configured it to execute bar. English Syntax¶ Use proper spelling, grammar, and punctuation. English Language & Usage is a good resource. Never use "and/or". If you cannot figure out whether you should use "and" or "or", and are tempted to use the lazy "and/or", then write the sentence so it is clear. Avoid abbreviations. Spell out words. Avoid "etc.", "e.g.", and "i.e.". They do not translate well or read well by screen readers for the visually impaired. It is lazy, and sounds pretentious. Writers seldom get the usage or punctuation right. Instead spell it out to their meanings of "and so on", "for example", and "in other words". Documentation page structure¶ Each page should contain in order the following. The main heading. This will be visible in the table of contents. ================ The main heading ================ Meta tag information. The "meta" directive is used to specify HTML metadata stored in HTML META tags. Metadata is used to describe and classify web pages in the World Wide Web in a form that is easy for search engines to extract and collate. .. meta:: :description: This chapter describes how to edit, update, and build the Pyramid documentation. :keywords: Pyramid, Style Guide The above code renders as follows. <meta content="This chapter describes how to edit, update, and build the Pyramid documentation." name="description" /> <meta content="Pyramid, Style Guide" name="keywords" /> Introduction paragraph. Introduction ------------ This chapter is an introduction. Finally the content of the document page, consisting of reST elements such as headings, paragraphs, tables, and so on. Documentation page content¶ This section describes the content of documentation source files. Use of whitespace¶ Narrative documentation is not code, and should therefore not adhere to PEP 8 standards or other line length conventions. There is no maximum line length. Lines should be the length of one sentence, without hard wraps. Lines should not end with white space. When a paragraph contains more than one sentence, its sentences should be written one per line. This makes it easier to edit and find differences when updating documentation. For example: This is the first sentence in a paragraph. This is the second sentence in a paragraph. This is a new paragraph. Which renders as follows. This is the first sentence in a paragraph. This is the second sentence in a paragraph. This is a new paragraph. All indentation should be 4 spaces. Do not use tabs to indent. Each section should have two trailing blank lines to separate it from the previous section. A section heading should have a blank line following its underline and before its content. A line feed or carriage return should be used at the end of a file. All other whitespace is defined by reST syntax. Table of contents¶ toctree entries should exclude the file extension. For example: .. toctree:: :maxdepth: 2 narr/introduction narr/install narr/firstapp Headings¶ Chapter titles, sections, sub-sections, sub-sub-sections, and sub-sub-sub-sections within a chapter (usually a single reST file) are indicated with markup and are displayed as headings at various levels. Conventions are adopted from Documenting Python, Sections. Headings are rendered in HTML as follows: The chapter title of this document, Documentation Style Guide, has the following reST code. ************************* Documentation Style Guide ************************* Chapter titles should be over- and underlined with asterisks ( *). The heading for this section, Documentation content, has the following reST code: Documentation content ===================== The heading for this sub-section, Headings, has the following reST code: Headings -------- Sub-sub-section, and sub-sub-sub-section headings are shown as follows. Paragraphs¶ A paragraph of text looks exactly like this paragraph. Paragraphs must be separated by two line feeds. Links to websites¶ It is recommended to use inline links to keep together the context or link label with the URL. Avoid the use of targets and links at the end of the page, because the separation makes it difficult to update and translate. Here is an example of inline links, our preferred method. `TryPyramid <>`_ The above code renders as follows. See also See also Cross-reference links for generating links throughout the entire documentation. Cross-reference links¶ To create cross-references to a document, arbitrary location, object, or other items, use variations of the following syntax. :role:`target`creates a link to the item named targetof the type indicated by role, with the link's text as the title of the target. targetmay need to be disambiguated between documentation sets linked through intersphinx, in which case the syntax would be deform:overview. :role:`~target`displays the link as only the last component of the target. :role:`title <target>`creates a custom title, instead of the default title of the target. Cross-referencing documents¶ To link to pages within this documentation: :doc:`glossary` The above code renders as follows. Cross-referencing arbitrary locations¶ To support cross-referencing to arbitrary locations in any document and between documentation sets via intersphinx, the standard reST labels are used. For this to work, label names must be unique throughout the entire documentation including externally linked intersphinx references. There are two ways in which you can refer to labels, if they are placed directly before a section title, a figure, or table with a caption, or at any other location. This section has a label with the syntax .. _label_name: followed by the section title. .. _dsg-cross-referencing-arbitrary-locations: Cross-referencing arbitrary locations ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To generate a link to that section with its title, use the following syntax. :ref:`dsg-cross-referencing-arbitrary-locations` The above code renders as follows. Cross-referencing arbitrary locations The same syntax works for figures and tables with captions. For labels that are not placed as mentioned, the link must be given an explicit title, such as :ref:`title <label>`. See also See also the Sphinx documentation, Inline markup. Python modules, classes, methods, and functions¶ All of the following are clickable links to Python modules, classes, methods, and functions. Python module names use the mod directive, with the module name as the argument. :mod:`python:string` The above code renders as follows. Python class names use the class directive, with the class name as the argument. :class:`str` The above code renders as follows. Python method names use the meth directive, with the method name as the argument. :meth:`python:str.capitalize` The above code renders as follows. Python function names use the func directive, with the function name as the argument. :func:`pyramid.renderers.render_to_response` The above code renders as follows. pyramid.renderers.render_to_response() Sometimes we show only the last segment of a Python object's name, which displays as follows. :func:`~pyramid.renderers.render_to_response` The above code renders as follows. PEPs¶ Use the directive :pep: to refer to PEPs and link to them. :pep:`8` The above code renders as follows. Lists¶ All list items should have their text indented to start in the fifth column. This makes it easier for editors to maintain uniform indentation, especially for nested and definition lists. Bulleted lists use syntax and display as follows. It is recommended to use asterisks ( *) for each list item because they stand out better than hyphens ( -) in the reST source. * This is an item in a bulleted list. * This is another item in a bulleted list. The second item supports paragraph markup. This is an item in a bulleted list. This is another item in a bulleted list. The second item supports paragraph markup. Numbered lists use syntax and display as follows. Numbered lists should use a number sign followed by a period ( #.) and will be numbered automatically. Avoid manually numbering lists, instead allowing Sphinx to do the numbering for you. #. This is an item in a numbered list. #. This is another item in a numbered list. - This is an item in a numbered list. - This is another item in a numbered list. See also Docutils Enumerated Lists Nested lists use syntax and display as follows. The appearance of nested lists can be created by separating the child lists from their parent list by blank lines, and indenting four spaces. #. This is a list item in the parent list. #. This is another list item in the parent list. #. This is a list item in the child list. #. This is another list item in the child list. #. This is one more list item in the parent list. - This is a list item in the parent list. - This is another list item in the parent list. - This is a list item in the child list. - This is another list item in the child list. - This is one more list item in the parent list. Definition lists use syntax and display as follows. term Definition of the term is indented. A definition may have paragraphs and other reST markup. next term Next term definition. - term Definition of the term is indented. A definition may have paragraphs and other reST markup. - next term - Next term definition. Images¶ To display images, use the image directive. .. image:: /_static/pyramid_request_processing.* Will render in HTML as the following. Source code¶ Source code may be displayed in blocks or inline. Code blocks¶ Blocks of code should use syntax highlighting and specify the language, and may use line numbering or emphasis. Avoid the use of two colons ( ::) at the end of a line, followed by a blank line, then code, because this may result in code parsing warnings (or worse, silent failures) and incorrect source code highlighting. Always indent the source code in a code block. Code blocks use the directive code-block. Its syntax is the following, where the Pygments lexer is the name of the language, with options indented on the subsequent lines. .. code-block:: lexer :option: See also See also the Sphinx documentation for Showing code examples. Syntax highlighting examples¶ Python: .. code-block:: python if "foo" == "bar": # This is Python code pass Renders as: if "foo" == "bar": # This is Python code pass Shell commands should have no prefix character. They get in the way of copy-pasting commands, and often don't look right with syntax highlighting. Bash: .. code-block:: bash $VENV/bin/pip install -e . Renders as: $VENV/bin/pip install -e . Windows: .. code-block:: doscon %VENV%\Scripts\pserve development.ini Renders as: %VENV%\Scripts\pserve development.ini XML: .. code-block:: xml <somesnippet>Some XML</somesnippet> Renders as: <somesnippet>Some XML</somesnippet> cfg: .. code-block:: cfg [some-part] # A random part in the buildout recipe = collective.recipe.foo option = value Renders as: [some-part] # A random part in the buildout recipe = collective.recipe.foo option = value ini: .. code-block:: ini [nosetests] match=^test where=pyramid nocapture=1 Renders as: [nosetests] match=^test where=pyramid nocapture=1 Interactive Python: .. code-block:: pycon >>> class Foo: ... bar = 100 ... >>> f = Foo() >>> f.bar 100 >>> f.bar / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero Renders as: >>>: .. code-block:: bash $ $VENV/bin/py.test tutorial/tests.py --cov-report term-missing \ --cov=tutorial -q Renders as: $ $VENV/bin/py.test tutorial/tests.py --cov-report term-missing \ --cov=tutorial -q Code block options¶ To emphasize lines, we give the appearance that a highlighting pen has been used on the code using the option emphasize-lines. The argument passed to emphasize-lines must be a comma-separated list of either single or ranges of line numbers. .. code-block:: python :emphasize-lines: 1,3 if "foo" == "bar": # This is Python code pass Renders as: if "foo" == "bar": # This is Python code pass A code block with line numbers. .. code-block:: python :linenos: if "foo" == "bar": # This is Python code pass Renders as: Code blocks may be given a caption. They may also be given a name option, providing an implicit target name that can be referenced by using ref (see Cross-referencing arbitrary locations). .. code-block:: python :caption: sample.py :name: sample-py-dsg if "foo" == "bar": # This is Python code pass Renders as: To specify the starting number to use for line numbering, use the lineno-start directive. .. code-block:: python :lineno-start: 2 if "foo" == "bar": # This is Python code pass Renders as: Include code blocks from external files¶ Longer displays of verbatim text may be included by storing the example text in an external file containing only plain text or code. The file may be included using the literalinclude directive. The file name follows the conventions of File naming. .. literalinclude:: src/helloworld.py :language: python The above code renders as follows.() Like code blocks, literalinclude supports the following options. languageto select a language for syntax highlighting linenosto switch on line numbers lineno-startto specify the starting number to use for line numbering emphasize-linesto emphasize particular lines Additionally literal includes support the following options: pyobjectto select a Python object to display linesto select lines to display lineno-matchto match line numbers with the selected lines from the linesoption linenos and lineno-start issues¶ Avoid the use of linenos and lineno-start with literal includes. .. literalinclude:: src/helloworld.py :language: python :linenos: :lineno-start: 11 :emphasize-lines: 1,6-7,9- The above code renders as follows. Note that lineno-start and emphasize-lines do not align. The former displays numbering starting from the arbitrarily provided value, whereas the latter emphasizes the line numbers of the source file. pyobject¶ literalinclude also supports including only parts of a file. If the source code is a Python module, you can select a class, function, or method to include using the pyobject option. .. literalinclude:: src/helloworld.py :language: python :pyobject: hello_world The above code renders as follows. It returns the function hello_world in the source file. def hello_world(request): return Response('Hello %(name)s!' % request.matchdict) start-after and end-before¶. .. literalinclude:: src/helloworld.py :language: python :start-after: from pyramid.response import Response :end-before: if __name__ == '__main__': The above code renders as follows. def hello_world(request): return Response('Hello %(name)s!' % request.matchdict) lines¶ You can specify exactly which lines to include by giving a lines option. .. literalinclude:: src/helloworld.py :language: python :lines: 6-7 The above code renders as follows. def hello_world(request): return Response('Hello %(name)s!' % request.matchdict) lineno-match¶ When specifying particular parts of a file to display, it can be useful to display exactly which lines are being presented. This can be done using the lineno-match option. .. literalinclude:: src/helloworld.py :language: python :lines: 6-7 :lineno-match: The above code renders as follows. Recommendations¶ Out of all the ways to include parts of a file, pyobject is the most preferred option because if you change your code and add or remove lines, you don't need to adjust line numbering, whereas with lines you would have to adjust. start-after and end-before are less desirable because they depend on source code not changing. Alternatively you can insert comments into your source code to act as the delimiters, but that just adds comments that have nothing to do with the functionality of your code. Above all with includes, if you use line numbering, it's much preferred to use lineno-match over linenos with lineno-start because it "just works" without thinking and with less markup. Parsed literals¶ Parsed literals are used to render, for example, a specific version number of the application in code blocks. Use the directive parsed-literal. Note that syntax highlighting is not supported and code is rendered as plain text. .. parsed-literal:: $VENV/bin/pip install "docs-style-guide==\ |release|\ " The above code renders as follows. $VENV/bin/pip install "docs-style-guide==1.0" Feature versioning¶ Three directives designate the version in which something is added, changed, or deprecated in the project. The first argument is the version. An optional second argument must appear upon a subsequent line, without blank lines in between, and indented. Version added¶ To indicate the version in which a feature is added to a project, use the versionadded directive. If the feature is an entire module, then the directive should be placed at the top of the module section before any prose. .. versionadded:: 1.1 :func:`pyramid.paster.bootstrap` Renders as: New in version 1.1: pyramid.paster.bootstrap() Version changed¶ To indicate the version in which a feature is changed in a project, use the versionchanged directive. Its arguments are the same as versionadded. .. versionchanged:: 1.8 Added the ability for ``bootstrap`` to cleanup automatically via the ``with`` statement. Renders as: Changed in version 1.8: Added the ability for bootstrap to cleanup automatically via the with statement. Deprecated¶ Similar to versionchanged, deprecated describes when the feature was deprecated. An explanation may be given to inform the reader what should be used instead. .. deprecated:: 1.7 Use the ``require_csrf`` option or read :ref:`auto_csrf_checking` instead to have :class:`pyramid.exceptions.BadCSRFToken` exceptions raised. Renders as: Deprecated since version 1.7: Use the require_csrf option or read Checking CSRF Tokens Automatically instead to have pyramid.exceptions.BadCSRFToken exceptions raised. Admonitions¶ Admonitions are intended to bring special attention to the reader. Danger¶ Danger represents critical information related to a topic or concept, and should recommend to the user "don't do this dangerous thing". Use the danger or error directive. .. danger:: This is danger or an error. The above code renders as follows. Danger This is danger or an error. Warnings¶ Warnings represent limitations and advice related to a topic or concept. .. warning:: This is a warning. The above code renders as follows. Warning This is a warning. Notes¶ Notes represent additional information related to a topic or concept. .. note:: This is a note. The above code renders as follows. Note This is a note. See also¶ "See also" messages refer to topics that are related to the current topic, but have a narrative tone to them instead of merely a link without explanation. .. seealso:: See :ref:`Quick Tutorial section on Requirements <qtut_requirements>`. The above code renders as follows. See also See Quick Tutorial section on Requirements. Todo¶ Todo items designate tasks that require further work. .. todo:: This is a todo item. This renders as the following. Todo This is a todo item. To display a list of all todos in the entire documentation, use the todolist directive. .. todolist:: In this document, the above renders as the following. Todo This is a todo item. (The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/docs-style-guide/checkouts/latest/docs/index.rst, line 1386.) Tables¶ Two forms of tables are supported, simple and grid. Simple tables require less markup but have fewer features and some constraints compared to grid tables. The right-most column in simple tables is unbound to the length of the underline in the column header. ===== ===== col 1 col 2 ===== ===== 1 Second column of row 1. 2 Second column of row 2. Second line of paragraph. 3 * Second column of row 3. * Second item in bullet list (row 3, column 2). \ Row 4; column 1 will be empty. ===== ===== Renders as: Grid tables have much more cumbersome markup, although Emacs' table mode may lessen the tedium. +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | * Table cells | +------------------------+ span rows. | * contain | | body row 4 | | * body elements. | +------------------------+------------+---------------------+ The above code renders as follows. Topic¶ A topic is similar to a block quote with a title, or a self-contained section with no subsections. A topic indicates a self-contained idea that is separate from the flow of the document. Topics may occur anywhere a section or transition may occur. For example: .. topic:: Topic Title Subsequent indented lines comprise the body of the topic, and are interpreted as body elements. renders as: Topic Title Subsequent indented lines comprise the body of the topic, and are interpreted as body elements. Font styles¶ Roles and semantic markup¶ Keyboard symbols¶ Press :kbd:`Ctrl-C` (or :kbd:`Ctrl-Break` on Windows) to exit the server. The above code renders as follows. Press Ctrl-C (or Ctrl-Break on Windows) to exit the server. Grammar, spelling, and capitalization¶ Use any commercial or free professional style guide in general. Use a spell- and grammar-checker. The following table lists the preferred grammar, spelling, and capitalization of words and phrases for frequently used items in documentation. Sphinx extensions¶ We use several Sphinx extensions to add features to our documentation. Extensions need to be enabled and configured in docs/conf.py before they can be used. sphinx.ext.autodoc¶ API documentation uses the Sphinx extension sphinx.ext.autodoc to include documentation from docstrings. See the source of any documentation within the docs/api/ directory for conventions and usage, as well as the Sphinx extension's documentation. Live examples can be found in Pyramid's API Documentation. sphinx.ext.doctest¶ sphinx.ext.doctest allows you to test code snippets in the documentation in a natural way. It works by collecting specially-marked up code blocks and running them as doctest tests. We have only a few tests in our Pyramid documentation which can be found in narr/sessions.rst and narr/hooks.rst. The following is an example. .. testsetup:: group1 a = 1 b = 2 .. doctest:: group1 >>> a + b 3 And the rendered result. >>> a + b 3 When we run doctests, the output would be similar to the following. tox -e doctest # ... Document: index --------------- 1 items passed all tests: 1 tests in group1 1 tests in 1 items. 1 passed and 0 failed. Test passed. Doctest summary =============== 1 test 0 failures in tests 0 failures in setup code 0 failures in cleanup code build succeeded. Testing of doctests in the sources finished, look at the results in ../.tox/doctest/doctest/output.txt. sphinx.ext.intersphinx¶ sphinx.ext.intersphinx generates links to the documentation of objects in other projects. sphinx.ext.todo¶ sphinx.ext.todo adds support for todo items. sphinx.ext.viewcode¶ sphinx.ext.viewcode looks at your Python object descriptions. Live examples can be found in Pyramid's API Documentation. repoze.sphinx.autointerface¶ repoze.sphinx.autointerface auto-generates API docs from Zope interfaces. Script documentation¶ We currently use sphinxcontrib-autoprogram to generate program output of Pyramid's p* Scripts Documentation. Comments may appear in reST source, but they are not rendered to the output. Comments are intended for documentation authors. See also See also comments in Source code.
https://docs.pylonsproject.org/projects/docs-style-guide/index.html
CC-MAIN-2021-21
refinedweb
4,959
58.99
« Return to documentation listing MPI_Graph_create - Makes a new communicator to which topology informa- tion has been attached. #include <mpi.h> int MPI_Graph_create(MPI_Comm comm_old, int nnodes, int *index, int *edges, int reorder, MPI_Comm *comm_graph) INCLUDE 'mpif.h' MPI_GRAPH_CREATE(COMM_OLD, NNODES, INDEX, EDGES, REORDER, COMM_GRAPH, IERROR) INTEGER COMM_OLD, NNODES, INDEX(*), EDGES(*) INTEGER COMM_GRAPH, IERROR LOGICAL REORDER #include <mpi.h> Graphcomm Intracomm::Create_graph(int nnodes, const int index[], const int edges[], bool reorder) const comm_old Input communicator without topology (handle). nnodes Number of nodes in graph (integer). index Array of integers describing node degrees (see below). edges Array of integers describing graph edges (see below). reorder Ranking may be reordered (true) or not (false) (logical). comm_graph Communicator with graph topology added (handle). IERROR Fortran only: Error status (integer). MPI_Graph_create returns a handle to analogy to MPI_Cart_create and MPI_Comm_split. The call is erroneous if it speci- fies a graph that is larger than the group size of the input communica- tor. The three parameters nnodes, index, and edges define the graph struc- The definitions of the arguments nnodes, index, and edges are illus- trated with the following simple example. Example: Assume there are four processes 0, 1, 2, 3 with the following adjacency matrix: Process Neighbors 0 1, 3 1 0 2 3 3 0, 2 Then, the input arguments are: nnodes = 4 index = 2, 3, 4, 6 edges = 1, 3, 0, 3, 0, 2 Thus, in C, index[0] is the degree of node zero, and index[i] - index[i-1] is the degree of node i, i=1, . . . , nnodes-1; the list of neighbors of node zero is stored in edges[j], for 0 <= j <= index[0] - 1 and the list of neighbors of node i, i > 0 , is stored in edges[j], index[i-1] <= j <= index[i] - 1. In Fortran, index(1) is the degree of node zero, and index(i+1) - index(i) is the degree of node i, i=1, . . . , nnodes-1; the list of neighbors of node zero is stored in edges(j), for 1 <= j <= index(1) and the list of neighbors of node i, i > 0, is stored in edges(j), index(i) + 1 <= j <= index(i +_Graph_get MPI_Graphdims_get Open MPI 1.2 September 2006 MPI_Graph_create(3OpenMPI)
http://icl.cs.utk.edu/open-mpi/doc/v1.2/man3/MPI_Graph_create.3.php
CC-MAIN-2014-10
refinedweb
373
52.29
TitleBarKind Since: BlackBerry 10.0.0 #include <bb/cascades/TitleBarKind> A class that represents the different types of a TitleBar. The supported types of a TitleBar include Default, Segmented, FreeForm and TextField. The Default type supports title text, as well as the acceptAction and dismissAction elements. The Segmented type supports options, as well as the selectedIndex and selectedOption elements. The FreeForm type supports an indicator used to toggle between expanded and collapsed states. In addition, FreeForm supports an indicator toggle area, a content area where you can place controls, and an expandable area where you can place controls. The TextField type suports TextField, as well as the acceptAction and dismissAction. On this type suports the acceptAction and dismissAction both image icons and text but only one of them is visible at the same time and the image have precedence over text. All types support the appearance and scrollBehavior properties. Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/cascades/bb__cascades__titlebarkind.html
CC-MAIN-2017-34
refinedweb
165
50.53
tag:blogger.com,1999:blog-8712770457197348465.post2547230426084135704..comments2014-10-19T09:07:19.733-07:00Comments on Javarevisited: 10 Tips to override toString() method in Java - ToStringBuilder Netbeans EclipseJavin Paul: java.util.Calendar considers January as 0, ...@hame:<br />java.util.Calendar considers January as 0, February as 1, etc. up and until December which is 11.<br /><br />Fun times!<br /><br />anyway, string + string2 is just as fast now as new StringBuilder(string).append(string2).toString(), so it is now a matter of personal taste.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-91058156670271141042014-02-10T03:10:04.177-08:002014-02-10T03:10:04.177-08:00Many programmers doesn't realize value of toSt...Many programmers doesn't realize value of toString() method, its enormous on logging and debugging. If you watch or inspect a variable during Eclipse debugging session, what to you like to see Object@7884393 or something useful e.g. I once wrote a wrapper around Tibrv, to represent Tibco session, initially its toString() was like above, but once I put "network: , daemon: , service: "Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-24956338062642380692013-06-23T21:57:00.670-07:002013-06-23T21:57:00.670-07:00Good article ... there is a little problem Indepen...Good article ... there is a little problem Independence day should be "15/08/1947" instead of "15/07/1947"<br /><br />One doubt, toString() shouldn't print July because you are passing 07 as month. How come it has printed Aug.hame tips, One more tip, Which I like to add is u...Great tips, One more tip, Which I like to add is using String format method for creating formatted toString representation. It's clear, concise and powerful. Use String.format() to generate your toString() if you are storing key value pairs. Here is an implementation :<br /><br />public class Item {<br /> public final String item;<br /> public final double price;<br /><br /> public Anonymousnoreply@blogger.com
http://javarevisited.blogspot.com/feeds/2547230426084135704/comments/default
CC-MAIN-2014-42
refinedweb
329
50.33
This post was written by Stephen Toub, a frequent contributor to the Parallel Programming in .NET blog. He shows us how Visual Studio 2012 and an attention to detail can help you discover unnecessary allocations in your app that can prevent it from achieving higher performance.. Both of these cases apply to Visual Studio’s .NET memory allocation profiler. Many developers that could benefit from it don’t know it exists, and other developers have an incorrect expectation for its purpose. This is unfortunate, as the feature can provide a lot of value for particular scenarios; many developers will benefit from understanding first that it exists, and second the intended scenarios for its use. Why memory profiling? When it comes to .NET and memory analysis, there are two primary reasons one would want to use a diagnostics tool: - To discover memory leaks. Leaks on a garbage-collecting runtime like the CLR manifest differently than do leaks in a non-garbage-collected environment, such as in code written in C/C++. A leak in the latter typically occurs due to the developer not manually freeing some memory that was previously allocated. In a garbage collected environment, however, manually freeing memory isn’t required, as that’s the duty of the garbage collector (GC). However, the GC can only release memory that is provably no longer being used, meaning as long as there are no rooted references to the memory. Leaks in .NET code manifest then when some memory that should have been collected is incorrectly still rooted, e.g. a reference to the object occurs in an event handler registered with a static event. A good memory analysis tool might help you to find such leaks, such as by allowing you to take snapshots of the process at two different points and then comparing those snapshots to see which objects stuck around for the second point, and more importantly, why. - To discover unnecessary allocations. In .NET, allocation is often quite cheap. This cost is deceptive, however, as there are more costs later when the GC needs to clean up. The more memory that gets allocated, the more frequently the GC will need to run, and typically the more objects that survive collections, the more work the GC needs to do when it runs to determine which objects are no longer reachable. Thus, the more allocations a program does, the higher the GC costs will be. These GC costs are often negligible to the program’s performance profile, but for certain kinds of apps, especially those on servers that require high-throughput operation, these costs can add up quickly and make a noticeable impact to the performance of the app. As such, a good memory analysis tool might help you to understand all of the allocation being done by the program, in order to help spot allocations you can potentially avoid. The .NET memory profiler included in Visual Studio 2012 (Professional and higher versions) was designed primarily to address the latter case of helping to discover unnecessary allocations, and it’s quite useful towards that goal, as the rest of this post will explore. The tool is not tuned for the former case of finding and fixing memory leaks, though this is an area the Visual Studio diagnostics team is looking to address in depth for the future (you can see such an experience for JavaScript that was added to Visual Studio as part of VS2012.1). While the tool today does have an advanced option to track when objects are collected, it doesn’t help you to understand why objects weren’t collected or why they were held onto longer than was expected. There are also other useful tools in this space. The downloadable PerfView tool doesn’t provide as user-friendly an interface as does the .NET memory profiler in Visual Studio 2012, but it is a very powerful tool that supports both tasks of finding memory leaks and discovering unnecessary allocations. It also supports profiling Windows Store apps, which the .NET memory allocation profiler in Visual Studio 2012 does not currently support as of the writing of this post. Example to be optimized To better understand the memory profiler’s role and how it can help, let’s walk through an example. We’ll start with the core method that we’ll be looking to optimize (in a real-world case, you’d likely be analyzing your whole application and narrowing in on the particular offending areas, but for the purpose of this example, we’ll keep this constrained): purpose of this small method is to enable code to await a task in a cancelable manner, meaning that regardless of whether the task has completed, the developer wants to be able to stop waiting for it. Instead of writing code like: T result = await someTask; the developer would write: T result = await someTask.WithCancellation1(token); and if cancellation is requested on the relevant CancellationToken before the task completes, an OperationCanceledException will be thrown. This is achieved in WithCancellation1 by wrapping the original task in an async method. The method creates a second task that will complete when cancellation is requested (by Registering a call to TrySetResult with the CancellationToken), and then uses Task.WhenAny to wait for either the original task or the cancellation task to complete. As soon as either does, the async method completes, either by throwing a cancellation exception if the cancellation task completed first, or by propagating the outcome of the original task by awaiting it. (For more details, see the blog post “How do I cancel non-cancelable async operations?”) To understand the allocations involved in this method, we’ll use a small harness method: using System; using System.Threading; using System.Threading.Tasks; class Harness { static void Main() { Console.ReadLine(); // wait until profiler attaches TestAsync().Wait(); } static async Task TestAsync() { var token = CancellationToken.None; for(int i=0; i<100000; i++) await Task.FromResult(42).WithCancellation1(token); } } static class Extensions { TestAsync method will iterate 100,000 times. Each time, it creates a new task, invokes the WithCancellation1 on it, and awaits the result of that WithCancellation1 call. This await will complete synchronously, as the task created by Task.FromResult is returned in an already completed state, and the WithCancellation1 method itself doesn’t introduce any additional asynchrony such that the task it returns will complete synchronously as well. Running the .NET memory allocation profiler To start the memory allocation profiler, in Visual Studio go to the Analyze menu and select “Launch Performance Wizard…”. This will open a dialog like the following: Choose “.NET memory allocation (sampling)”, click Next twice, followed by Finish (if this is the first time you’ve used the profiler since you logged into Windows, you’ll need to accept the elevation prompt so the profiler can start). At that point, the application will be launched and the profiler will start monitoring it for allocations (the harness code above also requires that you press ‘Enter’, in order to ensure the profiler has attached by the time the program starts the real test). When the app completes, or when you manually choose to stop profiling, the profiler will load symbols and will start analyzing the trace. That’s a good time to go and get yourself a cup of coffee, or lunch, as depending on how many allocations occurred, the tool can take a while to do this analysis. When the analysis completes, we’re presented with a summary of the allocations that occurred, including highlighting the functions that allocated the most memory, the types that resulted in the most memory allocated, and the types with the most instances allocated: From there, we can drill in further, by looking at the allocations summary (choose “Allocation” from the “Current View” dropdown): Here, we get to see a row for each type that was allocated, with the columns showing information about how many allocations were tracked, how much space was associated with those allocations, and what percentage of allocations mapped back to that type. We can also expand an entry to see the stack of method calls that resulted in these allocations: By selecting the “Functions” view, we can get a different pivot on this data, highlighting which functions allocated the most objects and bytes: Interpreting and acting on the profiling results With this capability, we can analyze our example’s results. First, we can see that there’s a substantial number of allocations here, which might be surprising. After all, in our example we were using WithCancellation1 with a task that was already completed, which means there should have been very little work to do (with the task already done, there is nothing to cancel), and yet from the above trace we can see that each iteration of our example is resulting in: - Three allocations of Task`1 (we ran the harness 100K times and can see there were ~300K allocations) - Two allocations of Task[] - One allocation each of TaskCompletionSource`1, Action, a compiler-generated type called <>c_DisplayClass2`1, and some type called CompleteOnInvokePromise That’s nine allocations for a case where we might expect only one (the task allocation we explicitly asked for in the harness by calling Task.FromResult), with our WithCancellation1 method incurring eight allocations. For helper operations on tasks, it’s actually fairly common to deal with already completed tasks, as often times operations implemented to be asynchronous will actually complete synchronously (e.g. one read operation on a network stream may buffer into memory enough additional data to fulfill a subsequent read operation). As such, optimizing for the already completed case can be really beneficial for performance. Let’s try. Here’s a second attempt at WithCancellation, one that optimizes for several “already completed” cases: public static Task<T> WithCancellation2<T>(this Task<T> task, CancellationToken cancellationToken) { if (task.IsCompleted || !cancellationToken.CanBeCanceled) return task; else if (cancellationToken.IsCancellationRequested) return new Task<T>(() => default(T), cancellationToken); else return task.WithCancellation1(cancellationToken); } This implementation checks: - First, whether the task is already completed or whether the supplied CancellationToken can’t be canceled; in both of those cases, there’s no additional work needed, as cancellation can’t be applied, and as such we can just return the original task immediately rather than spending any time or memory creating a new one. - Then whether cancellation has already been requested; if it has, we can allocate a single already-canceled task to be returned, rather than spending the eight allocations we previously paid to invoke our original implementation. - Finally, if none of these fast paths apply, we fall through to calling the original implementation. Re-profiling our micro-benchmark while using WithCancellation2 instead of WithCancellation1 provides a much improved outlook (you’ll likely notice that the analysis completes much more quickly than it did before, already a sign that we’ve significantly decreased memory allocation). Now we have just have the primary allocation we expected, the one from Task.FromResult called from our TestAsync method in the harness: So, we’ve now successfully optimized the case where the task is already completed, where cancellation can’t be requested, or where cancellation has already been requested. What about the case where we do actually need to invoke the more complicated logic? Are there any improvements that can be made there? Let’s change our benchmark to use a task that’s not already completed by the time we invoke WithCancellation2, and also to use a token that can have cancellation requested. This will ensure we make it to the “slow” path: static async Task TestAsync() { var token = new CancellationTokenSource().Token; for (int i = 0; i < 100000; i++) { var tcs = new TaskCompletionSource<int>(); var t = tcs.Task.WithCancellation2(token); tcs.SetResult(42); await t; } } Profiling again provides more insight: On this slow path, there are now 14 total allocations per iteration, including the 2 from our TestAsync harness (the TaskCompletionSource<int> we explicitly create, and the Task<int> it creates). At this point, we can use all of the information provided by the profiling results to understand where the remaining 12 allocations are coming from and to then address them as is relevant and possible. For example, let’s look at two allocations specifically: the <>c__DisplayClass2`1 instance and one of the two Action instances. These two allocations will likely be logical to anyone familiar with how the C# compiler handles closures. Why do we have a closure? Because of this line: using(cancellationToken.Register(() => tcs.TrySetResult(true))) The call to Register is closing over the ‘tcs’ variable. But this isn’t strictly necessary: the Register method has another overload which instead of taking an Action takes an Action<object> and the object state to be passed to it. If we instead rewrite this line to use that state-based overload, along with a manually cached delegate, we can avoid the closure and those two allocations: private static readonly Action<object> s_cancellationRegistration = s => ((TaskCompletionSource<bool>)s).TrySetResult(true); … using(cancellationToken.Register(s_cancellationRegistration, tcs)) Rerunning the profiler confirms those two allocations are no longer occurring: Start profiling today! This cycle of profiling, finding and eliminating hotspots, and then going around again is a common approach towards improving the performance of your code, whether using a CPU profiler or a memory profiler. So, if you find yourself in a scenario where you determine that minimizing allocations is important for the performance of your code, give the .NET memory allocation profiler in Visual Studio 2012 a try. Feel free to download the sample project used in this blog post. For more on profiling, see the blog of the Visual Studio Diagnostics team, and ask them questions in the Visual Studio Diagnostics forum. Stephen Toub Follow us on Twitter (@dotnet) and Facebook (dotnet). You can follow other .NET teams, too: @aspnet/asp.net, @efmagicunicorns/efmagicunicorns, @visualstudio/visualstudio. Join the conversationAdd Comment This is something which now ,I can ask my customer to get us VS2012. Cool. Although I'd "discovered" the .NET memory allocation profiler and played around with it a bit, I soon felt lost in the profiling results, and really didn't know where to begin. Now I understand. Stephen, you have a gift for making the complicated easy. Thanks for a great post. Btw, there is a tiny typo in the section on interpreting and acting on the profiler results. After the declaration of WithCancellation2, the second bullet point is missing it's first character, and reads as: hen whether cancellation has already been requested; if it has, we can allocate a single already-canceled task to be returned, rather than spending the eight allocations we previously paid to invoke our original implementation. Can we get a method like System.Diagnostics.Debug.HasReferences(object abc) to return true if an object still has an event handler referring to it? This would greatly help in designing classes that clean up all of their member variable event handlers, such as collection changed handlers on an ObservableCollection member variable. We would use the diagnostic method to verify that our member variables are un-hooked correctly when closing an XAML based dialogue, for example. @santosh poojari: Great 🙂 @Jerome: Thanks for the nice words; I'm glad this helped. And thanks for pointing out the typo (the first word should be "Then"); we'll get this fixed in the post. @Ted: I'll pass along your request. In the meantime, you could try using something like this to see if there are any other references still keeping the object alive: static bool HasReference(ref object obj) { var wr = new WeakReference(obj); obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return wr.IsAlive; } @Ted: You can use WMemoryProfiler in your unit tests to achieve it in a more indirect way. You can get take a snapshot of the managed heap and check later if your expected objects are gone now (i.e. are no longer referenced). This ways you can check not only for one object but for all of them in e.g. your namespace to look out for strange artefacts. @Stephen: I have used the Visual Studio Memory Profiler but compared to commerical ones it is lacking a ton of features. E.g. the SciTech .NET Memory Profiler can examine memory dumps to analyze the managed heap which is very cool for tracking down issues on customer machines. You should also mention that PerfView from Vance Morrison can do similar stuff with a not so pretty UI but it can do lots of stuff to already running processes which were not started under a profiler at all. @Alois Kraus: Yes, thanks, I actually did mention PerfView in the post (see the last paragraph in the "Why memory profiling?" section). visual studio 2012 is awesome. You are mentioning "such as by allowing you to take snapshots of the process at two different points and then comparing those snapshots to see which objects stuck around for the second point, and more importantly" How can I make snapshots? Is this ability not included in the professional edition of 2012 and 213? @Vinculum: That paragraph you reference wasn't about any particular tool, it was simply stating the kinds of features developers typically look for in such profiling tools. However, the memory analysis tool in Visual Studio 2013 does allow you to compare snapshots… see Andrew Hall's posts at blogs.msdn.com/…/using-visual-studio-2013-to-diagnose-net-memory-issues-in-production.aspx and blogs.msdn.com/…/net-memory-analysis-enhancements-in-visual-studio-2013.aspx for more info. get a cup of coffee ?? I have waited 12 hours and after that the status bar shows 1/4, so will take 2 days! PS and created an 80 Gig File @Marcus: the memory profiler records and analyzes every single allocation in your application, and this turns out to be a significant amount of data to collect and process. For this reason it is best to use it for a short period of time on isolated workloads (such as the benchmark shown in this blog post), otherwise you will get large files and it will take a very long time to process. To collect a smaller set of data, you can start the memory profiler paused (Analyze -> Profiler -> Start with Profiling Paused) and then start profiling once your application is at the point that you want to analyze. We are also looking into improving the performance for future releases. When I perform the .NET memory allocation profiling I will get a different output. I won't get the three tables with functions allocating most memory, Types With Most Memory Allocated and Types With Most Instances. I will get two tables with "Hot Path" and "Functions Doing Most Individual Work". Do you know why ? @David: it sounds like you are looking at a CPU Sampling report. Did you forget to change the default from "CPU Sampling" to ".NET Memory Allocation" on the first page of the performance wizard? I selected the correct method in the Wizard (.NET memory allocation. What I am doing is starting my app by doubleclicking the exe in the bin, only then I start the Wizard and at the final step I uncheck the "Launch profiling after wizard finishes". After finishing the Wizard I open the Performance Explorer and attach the process I want to profile (my app) and the profiling will start. If you follow this procedure the output of the .NET memory allocation profiling is the same as the CPU sampling. I also tried with your sample application and it also behave this way. @David: the allocation profiler does not support attach/detach. I tried it out and it is falling back to CPU profiling when you click attach/detach. This is confusing, it should instead show you an error dialog or the option should be grayed out. If you right click on the session and click "start profiling" you do get the memory allocation report, but unfortunately there is no way to attach to a running process because of a limitation in the method used to collect the allocation data. Same tool is exist in Visual Studio 2010 and we had tried couple of time however could not reach conclusion so finally used redgate profiler. I find it rather ironic that the memory profiler, just about every time I try to use it, crashes with an out of memory exception (on any machine that I try to use it on). It seems it's only of any use when you have a small application with a small memory over-head. Its very cool
https://blogs.msdn.microsoft.com/dotnet/2013/04/04/net-memory-allocation-profiling-with-visual-studio-2012/
CC-MAIN-2016-44
refinedweb
3,437
50.57
I am new to React/RN and understand how navigation works, but don’t really see a best practices for how to trigger navigation from a trivial component, like a random button somewhere, that should trigger a route change. Let’s say this button is nested under a set of elements who are under a <Tab.Navigator> who are under a set of <Stack.Navigator>, etc. A couple screen layouts deep. This element cannot access this.props.navigation. So my idea is to send upwards. But this could mean passing an onPress handler like, 5 or 6 layers down. Is this the correct way? Should I only pass it from the parent closest to a navigator, or all the way to App.tsx? Answer If you can not use the <Link> component, then you should use the history object. For example, the useHistory hook will return it ( whenever you will import ), so your component can be nested as hell. import { useHistory } from 'react-router-dom' function HomeButton() { const history = useHistory() function handleClick() { history.push('/home') } return ( <button type="button" onClick={handleClick}> Go home </button> ) }
https://www.tutorialguruji.com/react-js/react-triggering-navigation-from-nested-components/
CC-MAIN-2021-39
refinedweb
184
58.18
Hi, Ive been trying this before posting for a long time now and i can't get my code to work. I have a collection wich include all sort of information about abandoned buildings (name, year of construction, pictures, age of the building, number of years abandonned, status etc) One of the page on my site is an index, with a repeater connected to the 'locations' collection where all the infos about the buldings are, in a list format. SO, what i want to acheive is the that the age of the buildings (and year of abandon too) will be calculated automatically, from the construction date wich is just the year, like 1934. ( but if i need it to be a in a date yyyy/mm/dd format i can change it) but would rather just use the year. I have tried folowing this : Ive so created a after querry hook from my collection and everything like stated in the how to but no luck... my reapeater end up being empty when i do the preview... I tried this other option wich worked, but its not meant for a repeater so the same year just repeat itselft: Here is my code in both of the .js file and the code on my index page. data.js : import {ageFromcons} from 'backend/calculations'; export function Locations_afterQuery(item, context) { item.age = ageFromcons(item.cons); return item; } calculation.js: export function ageFromcons(cons) { let now = new Date(); let age = now.getFullYear() - cons.getFullYear(); let months = now.getMonth() - cons.getMonth(); let days = now.getDate() - cons.getDate(); if (months < 0 || (months === 0 && days < 0)) { age--; } return age.toString(); } Code from my index page: // For full API documentation, including code examples, visit $w.onReady(function () { //TODO: write your page related code here... }); $w.onReady(function () { $w("#repeater1").onItemReady( ($w, itemData, index) => { $w("#text6").text = itemData.age; } ); } ); export function line3_viewportEnter(event, $w) { $w("#StickyMenu").hide(); } export function line3_viewportLeave(event, $w) { $w("#StickyMenu").show(); } import wixData from 'wix-data'; // ... export function button7_click(event, $w) { $w("#IndexDataset").setSort( wixData.sort() .ascending("construction") ); } export function button26_click(event, $w) { $w("#IndexDataset").setSort( wixData.sort() .ascending("nom") ); } I would probably need another code for sorting the age column too, because i dont know how i can sort it since it will not be part of the database schema. My code for sorting my column are example that, (button26 being example 'construction' button) export function button26_click(event, $w) { $w("#IndexDataset").setSort( wixData.sort() .ascending("nom") ); } Sorry for the long tread! haha Thanks to whoever can help me Guillaume Hi Guillaume, I would use the query function. Note that you need to set the sorted information to the repeater after receiving the results. You can follow the explanation here but instead of using the Array.filter function, you should change it to Array.sort function. I hope it's clear. Best, Tal. Hi, Thanks but i dont understand... what you just explain is for the sorting of the field that is created by the code? (my second question?) Because i dont undestand how this is explaining how to calculate the age from dates... Anyone else can help with some ideas? Maybe i dont understand but Tal explanation left me clueless lol Sorry im french too so its harder to understand sometimes. Hey, Sorry, I missed your first question. Firstly, I noticed that you've added this function which seem to calculate the age: What was the issue with this function? Moreover, you can check out this "Calculate age given the birth date in the format YYYYMMDD" stackoverflow thread. After calculating the date, you can get the year by using Date.getFullYear function. I hope it's clearer now. Best, Tal. I want a code to calculate the age from either a date field (yyyymmdd) or from just a year like 1934 ( just the year would be perfect since i just know the year of the locations) So i dont have to change the 'age' of the buildings in my database each year... The code ive shared just dont work, my repeater go blank, everything is gone , not just the age field, it looks like this when i do a preview: Up on my last question Ive change my reapaeter for my index to a table, but its the same thing, how can a have the age calculated from a year? Hi @Guillaume Clément, Can you please share with us the code you've written? Thanks, Tal. It's the smae thing as in the meaasges above, i dont get how to implement it.
https://www.wix.com/corvid/forum/community-discussion/calculate-age-from-date-from-collection
CC-MAIN-2019-47
refinedweb
758
64.1
8004/transactions-blockchain-from-remote-device-like-cell-phone In a private ethereum network you have ...READ MORE The spending conditions, i.e., who is able ...READ MORE There are two ways to actually do ...READ MORE You can very easily create a cryptocurrency having a ...READ MORE Summary: Both should provide similar reliability of ...READ MORE This will solve your problem import org.apache.commons.codec.binary.Hex; Transaction txn ...READ MORE The most obvious use case would be ...READ MORE There are two ways to solve this. ...READ MORE You cant access/embed real world data using ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/8004/transactions-blockchain-from-remote-device-like-cell-phone
CC-MAIN-2021-10
refinedweb
108
63.56
We can read all the content on websites, but wouldn't it be cool if we could automatically read specific data from websites whenever you wanted? If this interested you, this workshop is for you. I will be showing you how to use webscraping to create a tool that can gather current COVID data and displays it as text. Note: not all webpages can be read using this technique. If data is loaded in using ajax or after the inital page request this method may not work. Prerequisites You should have a basic understanding of HTML and Python and how to use variables and objects. Setup We will be using repl.it, an online code editor that allows you to write and run code from any computer! Spin up a Python3 repl by clicking here. Before we can start coding, we need to install a couple of external libraries. Follow the image below to find where to add the packages. Once in this menu you will need to install beautifulsoup4, requests, and lxml. What each package does requests is a Python library which makes it very easy to request a webpage. Requesting a webpage means we give the requests library a url and it returns all the HTML from the url we provide. lxml is a C package used by BeautifulSoup that parses the HTML. When we request the HTML it will just be a big block of text. When lxml parses the HTML this allows Python to understand the HTML and allows us the ability to search for and find things in the HTML. beautifulsoup4 is a Python library that uses the parsed HTML from lxml to search fo and find specific HTML elements and data. This allows us to easily get the information we want from a large webpage full of data. Learn more about the packages: Lets start coding! Once you've installed the packages, open the main.py file in the sidebar on the left. Then, import the packages you just installed. from bs4 import BeautifulSoup as bs import requests Now we can start webscraping! We will begin by requesting our webpage and extracting the HTML from the request object. url = '' # request the website r = requests.get(url) # get the HTML from the request page = r.text Next we will create the BeautifulSoup object and use lxml to parse the HTML. soup = bs(page, 'lxml') Now that we have our BeautifulSoup object we can go all of the HTML! Working with the parsed HTML In the next step, we'll be working with data from an HTML table. The website that contains the COVID data uses HTML tables. The structure of an HTML table can be a little confusing so lets break it down first. Here's an example of an HTML table: <table> <tr> <td>Country</td> <td>Cases</td> <td>Column</td> <td>Column 2</td> </tr> <tr> <td>United States</td> <td>1,000,000</td> <td>Column data</td> <td>Column 2 data</td> </tr> <tr> <td>Canada</td> <td>100,000</td> <td>Column data</td> <td>Column 2 data</td> </tr> </table> It first involves the table tag, within this table it contains rows ( tr), and lastly each row contains columns ( td). We just need to roughly understand the table to scrape it. Simply put, the table is made up of rows and within each row there are columns. Some tables can be really large, like the ones used on the COVID data website, but by utilizting for loops in Python we can easily traverse the tables. Python time! We're going to use BeautifulSoup to find an HTML table element. We want to find a specific table by ID sortable_table_world as seen in the picture. The code below finds the first table that matches that ID by using the find() function from the BeautifulSoup library. We are looking for a very specific table as shown in the picture below. We pass in 'table' to specify we want an HTML table and pass in a dictionary that specifiies we want the table with the ID sortable_table_world. # get world data table table = soup.find('table', attrs={'id':'sortable_table_world'}) After this code runs we now have a new BeautifulSoup object called table that contains the table and child elements within that table. With table we will use the findAll() function from the BeautifulSoup library. When we run the findAll() function on the variable table BeautifulSoup will only find items inside our table. This function allows us to all the HTML elements that fit our parameter. In this case we pass in 'tr' to get every row inside our table. This function will return a Python list with BeautifulSoup objects of every row in our table. # get table rows tableRows = table.findAll('tr') Now that we have all the table rows in a Python list ( tableRows), we can iterate through the list. Doing this will allow us to choose which countries' data we want. Before we start iterating, there are some things we need to adress regarding the data. The data doesn't come as simple text and numbers. For our project the website returns data with whitespacing as seen below. Included with our data are newlines and random spaces. The code below is an example that returns a piece of data from our table. tableCols = tableRows[1].findAll('td') tableCol = tableCols[0] tableCol.text > "\r\n TOTAL\r\n " With Python we can use the .strip() function on the string. The .strip() function clears away all whitespacing from the begining and end of a string. Below is an example of the code we can use to get clean data. tableCol.text.strip() > "TOTAL" Now that we got that handled lets get to proccessing the rest of our data! We begin with creaing a simple for loop to iterate over the data. Our loop will loop through every row in our table. This is also reffered to as a for each loop in other programming languages like Java. for row in tableRows[1:]: # Whatever is in here will run for every row in our table You may have noticed tableRows[1:] has a weird bracket thing attached to it. This is list splicing. In Python this allows a programmer to control how much of the list they want to use. The general structure looks like this [starting value (inclusive) : ending value (exclusive) : step (how many items skip)]. Each value is optional which is why in our example only includs a 1, no ending value, and no step value. By default when putting a list in a for loop the brakcet would be [::] meaning that it will start at the begining, stop at the end, and go up by one. For our for loop we want to skip the first row because the first row is the table header (column names). Next we add an if statment that checks if the current row is the United States. for row in tableRows[1:]: if 'United States' == row.find('td').text[2:].strip(): # Do something if the current row is the United States This if statment may seem long and complicated but lets break it down into small parts. The first part, 'United States' == checks if whatever is on the other side of the double equals is the words "United States". On the other side we have to get the country name. As you can remember from before, tableRows contains a list of BeautifulSoup objects that contains all the rows from our table. Within these rows are all the columns. For the table we are using the country name is in the first column or the first td element in the row. To get the current row's country we use BeautifulSoup to find the first column in the row with row.find('td'). This returns a weird string with whitespaces as we have seen before as well as some random characters. To get rid of these uneeded characters we use [2:] which is the same as list splicing except for strings, and we use .strip() to clear away excess whitespacing. Now we have code that finds the country we want from all the rows in our table, the last step is to display the data! for row in tableRows[1:]: if 'United States' == row.find('td').text[2:].strip(): columns = row.findAll('td') print(columns[0].text[2:].strip()) print(f'Confirmed Cases: {columns[1].text.strip()}') print(f'New Cases: {columns[3].text.strip()}') print(f'Critical Cases: {columns[5].text.strip()}') > United States > Confirmed Cases: 9,566,690 > New Cases: 28,845 > Critical Cases: 88,127 Once you find the row of the country we want information about we can display any data we want. To start we run row.findAll('td') to get all the columns in the row. We didn't do this before because if we did, the code would have been slower compared to just using row.find('td'). From there you can print any column data with this code: print(f'Anything you want here: {columns[any column number].text.strip()}'). If you are unsure what columns you want you can run print(columns) and select as many of the columns as you want. Our previous example showed how to find data on one country but as we know the world has hundreds of countries. Here is some similar code for multiple countries. countries = ['United States', 'Spain', 'Canada'] for row in tableRows[1:]: if row.find('td').text[2:].strip() in countries: columns = row.findAll('td') print(columns[0].text[2:].strip()) print(f'Confirmed Cases: {columns[1].text.strip()}') print(f'New Cases: {columns[3].text.strip()}') print(f'Critical Cases: {columns[5].text.strip()}\n') The only difference is we create a python list to store the names of the countries we want to view. Thats it! You can now get live COVID19 data, but more importantly you are now primed with knowledge to webscrape anything! Here is the final code you can view and edit: Final Result and Code Hacking You can check out more advanced/in depth projects here. In this project you will be shown how to use selenium to webscrape. This method will allow you to webscrape pages like Amazon or Google that use ajax to load data as you scroll. - (). This workshop by Realpython goes more in depth and includes links to other resources that can allow you to webscrape more complicated websites. - Check out some other webscraping projects Webscrape Github Webscrape Currency Exchange Rates Webscrape Hack Club Bank What now? Go out there and create your own project! I'm sure you will blow us away
https://workshops.hackclub.com/read_the_internet/
CC-MAIN-2022-33
refinedweb
1,786
73.47
Namespaces Namespaces are virtually identical to the core Function plugin. The only difference is that you can create more than one Namespace object. If you're using a lot of functions, you can break them up into multiple Namespace objects, helping organize your code and prevent name collisions. You add, call, and inspect Namespace objects exactly like you would the vanilla Function object. Namespaces are independent from one another ? calling a function from namespace A should never trigger a function in namespace B. A Very Simple Demo Downloads namespace.c2addon namespace_demo.capx Some notes: <font color=red><font size="4">IMPORTANT UPDATE (Edit: Problem resolved! See below)</font></font> After more testing, it appears that my plugin breaks when used with nested function calls. I'll update the original post accordingly. I guess I now know why there was such a song and dance with the func stack. Edit: Well, apparently I can't edit the OP because I don't have enough rep to post the hyperlinks that are already there? <font color=red><font size="5">UPDATE 2 - Problem resolved!</font></font> Well, it turns out that the bug I thought I had was nothing but a red herring. I'm a bit embarrassed to say that I missed converting a function call to a namespace call in some code I was converting, and erroneously assumed that the plugin was at fault. I now am quite sure that the plugin is working as intended! I've nonetheless updated the plugin download link to an new version of the plugin. The major change of note is that individual namespace objects now maintain their own function stacks. This will probably prevent weird collisions with nested namespace calls. I've also updated the demo to be much more extensive and easier to read. Be sure to clear your browser cache if you've looked at it before. Develop games in your browser. Powerful, performant & highly capable. Made a minor update to this plugin Changes in version 1.0.5 The demo has been updated to demonstrate the new error messages (in preview mode, of course)
https://www.construct.net/en/forum/construct-2/addons-29/plugin-function-like-70848
CC-MAIN-2022-40
refinedweb
354
66.54
I'm trying to write a class that has a generic member variable but is not, itself, generic. Specifically, I want to say that I have an List of values of "some type that implements comparable to itself", so that I can call sort on that list... I hope that makes sense. The end result of what I'm trying to do is to create a class such that I can create an instance of said class with an array of (any given type) and have it generate a string representation for that list. In the real code, I also pass in the class of the types I'm passing in: String s = new MyClass(Integer.class, 1,2,3).asString(); assertEquals("1 or 2 or 3", s); String s = new MyClass(String.class, "c", "b", "a").asString(); assertEquals("\"a\" or \"b\" or \"c\"", s); Originally I didn't even want to pass in the class, I just wanted to pass in the values and have the code examine the resulting array to pick out the class of the values... but that was giving me troubles too. The following is the code I have, but I can't come up with the right mojo to put for the variable type. public class MyClass { // This doesn't work as T isn't defined final List<T extends Comparable<? super T>> values; public <T extends Comparable<? super T>> MyClass (T... values) { this.values = new ArrayList<T>(); for(T item : values) { this.values.add(item); } } public <T extends Comparable<? super T>> List<T> getSortedLst() { Collections.sort(this.values); return this.values; } } error on variable declaration line: Syntax error on token "extends", , expected Any help would be very much appreciated. Edit: updated code to use List instead of array, because I'm not sure it can be done with arrays. @Mark: From everything I've read, I really want to say "T is a type that is comparable to itself", not just "T is a type that is comparable". That being said, the following code doesn't work either: public class MyClass { // This doesn't work final List<? extends Comparable> values; public <T extends Comparable> MyClass (T... values) { this.values = new ArrayList<T>(); for(T item : values) { this.values.add(item); } } public <T extends Comparable> List<T> getSortedLst() { Collections.sort(this.values); return this.values; } } error on add line: The method add(capture#2-of ? extends Comparable) in the type List<capture#2-of ? extends Comparable> is not applicable for the arguments (T) error on sort line: Type mismatch: cannot convert from List<capture#4-of ? extends Comparable> to List<T> Conclusion: What it comes down to, it appears, is that Java can't quite handle what I want to do. The problem is because what I'm trying to say is: I want a list of items that are comparable against themselves, and I create the whole list at once from the data passed in at creation. However, Java sees that I have that list and can't nail down that all the information for my situation is available at compile time, since I could try to add things to the list later and, due to type erasure, it can't guarantee that safety. It's not really possible to communicate to Java the conditions involved in my situation without applying the generic type to the class.
http://ansaurus.com/question/3191613-generic-instance-variable-in-non-generic-class
CC-MAIN-2018-09
refinedweb
564
63.9
Hello,I'm trying to concatenate 2 numpy arrays of features predicted by the convolution layers in a vgg16 model. Basically i have used the bottom layers of a vgg16 model to predict the features for my full dataset and now I want to load the parts of dataset dynamically based on some settings from a dict, to train some models with it. So, I have 2 array of shape: (724, 512, 6, 8) and (3376, 512, 6, 8) Basically the first one contains features predicted from 724 image files (each prediction has shape (512, 6, 8)).I want to concatenate these 2 arrays into one of shape (4100, 512, 6, 8) (724, 512, 6, 8) and (3376, 512, 6, 8) I have tried using: np.array([np.concatenate(arr, axis=0) for arr in false_train_list])where false_train_list is the list containing the 2 arrays with the above shapes. Also tried with np.stack, tf.stack, etc... All of these result in an array with shape (2,) Can someone explain why ? I haven't found any good resources to understand how exactly np.concatenate() works.. Thank you! I don't know If I completely understood your problem but I can do the following: import numpy as np foo = np.random.rand(10, 5, 4, 3) bar = np.random.rand(12, 5, 4, 3) res = np.concatenate((foo, bar), axis = 0) res.shape -> (22, 5, 4, 3) Solved using np.concatenate(--list containing my arrays--, axis=0);Thanks!
http://forums.fast.ai/t/solved-numpy-concatenate/6119
CC-MAIN-2017-51
refinedweb
247
72.46
This project is mirrored from. Pull mirroring updated . - 08 May, 2016 4 commits Report process output decoding errors in context Not all the exception handling, just for the case fixed by the previous patch. Turns out of course that this is sensitive to the locale encoding, so we just skip the test when the localeEncoding is not UTF-8. - 07 May, 2016 5 commits Adjustments for what deps we pick for legacy Setup scripts in new-build Add a lower bound of >= 1.18. Also improve the related comments. Using >= 1.18 since we currently have problems working with 1.16 as that version lacks support for named build targets. We ought to fix working with older versions though. Add transformers and old-time, and for ghc-compatible compilers also add ghc-prim and template-haskell. Have to double check if the old-time dep needs to be conditional, e.g. on ghc version. It turns out that in rawSystemStdInOut any IO errors, including text decoding, occurring while collecting the output (stderr or stdout) do not get reported immediately, but only later if/when the output is consumed. This is because the exceptions happened in the threads forked to force the output, but if the main thread looks at the output later then the exception is reported again. This leads to very confusing results. In particular we had a case where the configure process did not fail until writing out the LocalBuildInfo because that was the first point that forced the output. So the distance from when the exception really occurred and the fact that the exception message does not include the name of the program run means that this is then a pain to track down. This patch makes sure that any exceptions arising from forcing the program output occur immediately and with an error message that includes the name of the program in question. - 06 May, 2016 13 commits Unfortunately, it was too difficult to factor out the common code between ProjectBuilding and Install. Signed-off-by: Edward Z. Yang <ezyang@cs.stanford.edu> Move solver types to Distribution.Solver.* namespace - randen authored and Mikhail Glushenkov committed contents. Prior to the response file code, all of these details of the command line for haddock would have been logged (with level == Verbose), so this corrects an oversight and brings the information in the logging back to what it used to be for cabal's haddock invocations. * Cabal/Distribution/Simple/Haddock.hs * Restore the logging of the entire command line used when invoking haddock to what it used to be prior to adding the response-file creation. (cherry picked from commit 28bea0d7) - 05 May, 2016 2 commits - 04 May, 2016 12 commits Simplify `GoalChoice` It makes the build fail due to timeout. /cc @ezyang [ci skip] This commit looks somewhat bigger than it is because I moved some comments around so we can have longer comments for the constructors. The most important change is the documentation of the `QGoalReason` invariant on 'GoalChoice'. This commit doesn't change any actual code. OpenGoal contains a FlaggedDep which contains a lot more information than we actually need in the tree; we just need to know, which choice are we introducing: package, flag, or stanza? We don't need the full FlaggedDep tree. Pkg-config constraints are actually a part of 1.24. Add `conflictSetOrigin` debugging field Make `Validate` a proper monad Add missing exports This field is only added if the `debug-conflict-sets` flag is specified to `cabal config`; it adds a tree to `CallStack`s to a `ConflictSet`. This is very useful when trying to understand how a certain conflict set was constructed. This makes it a bit easier to modify it (for example, during debugging). - 03 May, 2016 1 commit - - 02 May, 2016 3 commits - Getty Ritter authored and Mikhail Glushenkov committed An outstanding bug in GHC pre-8 causes haddock comments on GADT constructors to fail, which in turn prevents the bootstrapping process from finishing. This works around it by skipping haddocks for hackage-security. (cherry picked from commit 02a313e9)
https://gitlab.haskell.org/ghc/packages/Cabal/-/commits/c0f8bbfbe94223c61c3f3881f299eae463084ebd
CC-MAIN-2022-27
refinedweb
681
62.17
How To Make a Letter / Word Game with UIKit and Swift: Part 1/3 This 3-part tutorial series will guide you through the process of building a board game for the iPad in Swift, where you create words with letters. You’ll also learn about best practices for creating solid, modular iOS apps. And as a bonus, you’ll get a crash course in audio-visual effects with UIKit! Version - Other, Other, Other Update note: This tutorial was updated for Swift and iOS 8 by Caroline Begbie. Original series by Tutorial Team member Marin Todorov. Update 04/10/15: Updated for Xcode 6.3 and Swift 1.2 Are you a seasoned iOS developer who is thinking of creating an iOS game, but have no experience programming games? Maybe learning OpenGL ES makes you uncomfortable, or maybe you’ve just never crossed paths with Cocos2d for iPhone? Well, good news! UIKit is a power tool for game developers. Its high-end frameworks provide you with the means to create all of your game logic, from creating animations (including frame-animation) to playing audio and video. This 3-part tutorial series will guide you through the process of building a board game for iPad, where you create words with letters. You’ll also learn about best practices for creating solid, modular iOS apps. And as a bonus, you’ll get a crash course in audio-visual effects with UIKit! This tutorial series is designed for readers who are already somewhat familiar with Swift, and thus won’t go over details like primitive types or syntax. If your knowledge of Swift is lacking, I recommend checking out our Swift Video Series. Click through to get your game on! Getting Started: Introducing Anagrams The letter / word game with UIKit you will be making in this tutorial is about anagrams. An anagram is a word or phrase formed by rearranging the letters of another word or phrase. For example, the word cinema can be rearranged into the word iceman. Your game will challenge the player to create anagrams from words and phrases you provide. The finished game will look something like this: As you can see, in the screenshot above there is a row of letter tiles at the bottom of the screen that makes up the initial phrase. In this example it is the word admirer, minus the M tile, which the player has dragged to the upper row. The player’s job is to drag the letters from admirer to form a different word, using the same letters. Can you guess what it is? I’ve already given you a hint… it starts with an M! [spoiler title=”Answer”] The correct answer is married. Did you figure it out? If so, give yourself a high-five! [/spoiler] So anyway, this is the game you will be making. As you build this game, you will learn about the following foundational topics: - Proper model-view-controller (MVC) game structure. - Organizing your game controller logic. - Writing a simple audio controller for UIKit with AV Foundation. - Using QuartzCore for static visual effects. - Using UIAnimation to smooth in-game movements. - Using UIKit particles to add visual effects. - Building separate layers for the heads-up display (HUD) and the gameplay. - Using custom fonts to improve the look and polish. - Upgrading default UIKit components to game-like components. - Also included: discussion of the software tools I use along the way when I’m creating a game. :] Oh, and there will be explosions. :] Let’s dig in! The Starter Project To get you straight to the good stuff – using UIKit to build an iOS game – this tutorial provides a ZIP file that includes a starter XCode project and all game assets (images, fonts, audio and config files). Download the Anagrams Part 1 Starter, unzip it and open it up in Xcode. Have a look at what’s bundled in the starter project. The project file browser on the left should look something like this: Here’s a quick summary of what you see: - Config.swift: Basic top-level configuration. - Levels: Folder containing three .plist files to define the game’s three difficulty levels. - Classes/Models: Folder for your data models. - Classes/Views: Folder for your custom view classes. - Classes/Controllers: Folder for your controllers. - Assets/Images: Images you’ll use to create the game. - Assets/Audio: Creative Commons-licensed audio files. - Assets/Particles: Contains a single PNG file to use for particle effects. - Assets/Fonts: A custom TTF font for the game HUD. - Main.storyboard: Open up the storyboard and you’ll see there’s only one screen with the background set to a faint woodgrain image, which is included in the project assets. - Credits.txt: Includes links to the sources of all the assets used in the project. Poke around, play the sounds and browse the images. Then run the project. It’s much better than an empty app window, isn’t it? In this first part of the series, your goal is to display the initial anagram and target boxes on the screen. In the next parts of this series, you’ll add the ability to drag the tiles and the gameplay logic. There’s a lot involved to get this first part working. But don’t worry, you’ll break down this epic task into 8 small steps: - Load the level config file. - Create a game controller class. - Create an onscreen view. - Create a tile view. - Deal the tiles on the screen. - Add the letters. - Slightly rotate the letters randomly. - Add the targets. Let’s go over these one step at a time. 1) Load the Level Config File Select the level1.plist file in the project file browser. Have a look what’s inside: There are three top-level keys: - pointsPerTile: the number of points awarded for each correctly-placed tile. - timeToSolve: The number of seconds the player will have to solve the puzzle. - anagrams: A list of anagrams. Each anagram contains two items: an initial and a final phrase. Don’t bother for the moment with the first two and focus on anagrams. It’s an array of array-elements and each element has two string elements. You’re now going to build a data model to load this configuration in Swift. Right-click (or control-click) on the Anagrams/Classes/Models folder in the project and select New File… to create a new file. Select the iOS\Source\Swift File template and click Next. Name the file Level.swift and click Create. Open up Level.swift and add the following struct definition: struct Level { let pointsPerTile: Int let timeToSolve: Int let anagrams: [NSArray] } The properties match the structure of the .plist file, so you are simply going to load the data and populate the properties. Next, add the code to initialize the Level data model inside the struct definition: init(levelNumber: Int) { //1 find .plist file for this level let fileName = "level\(levelNumber).plist" let levelPath = "\(NSBundle.mainBundle().resourcePath!)/\(fileName)" //2 load .plist file let levelDictionary: NSDictionary? = NSDictionary(contentsOfFile: levelPath) //3 validation assert(levelDictionary != nil, "Level configuration file not found") //4 initialize the object from the dictionary self.pointsPerTile = levelDictionary!["pointsPerTile"] as! Int self.timeToSolve = levelDictionary!["timeToSolve"] as! Int self.anagrams = levelDictionary!["anagrams"] as! [NSArray] } Given a difficulty level ranging from 1 to 3, the initializer will set up the struct and its properties. There are four small sections in the initializer body: - Determine the path to the appropriate level config file (level1.plist, level2.plist, etc), based on the levelNumbervalue passed into the method and the bundle path. - Load the file’s contents into an NSDictionary, explicitly defined as optional since the file may not exist if you pass in an invalid level number. Fortunately, the NSDictionaryclass knows how to parse .plist files! - Validate that there’s something loaded in levelDictionary. I use assertoften for errors that should never happen in a shipped app; if they EVER happen during development I want the app to stop and crash, so I can fix it before doing anything else. - Copy the values from the NSDictionaryto the Levelinstance’s properties. Open up ViewController.swift and at the end of viewDidLoad(), add: let level1 = Level(levelNumber: 1) println("anagrams: \(level1.anagrams)") Build and run, and in the Xcode console you will see the list of anagrams for Level 1. Nice! Now you can remove the println() line from viewDidLoad() to keep the console tidy. That’s one task knocked down. Ready to move ahead to the next one? 2) Create a Game Controller Class People who are not experienced with the model-view-controller (MVC) paradigm before jumping into iOS development often confuse a controller and a UIViewController. - A controller is simply a class that focuses on some part of your app’s logic, separate from your app’s data and the classes used to display that data. - A class that subclasses UIViewControlleris a controller managing the presentation of a particular UIView. (And UIViews are used to display something on the screen.) You can read up more on the MVC pattern here. For this tutorial, you are going to create a controller class to manage your game’s logic. Let’s try this out. Create a new Swift file in the Anagrams/Classes/Controllers folder. Call the new file GameController. Open GameController.swift and add the following: import UIKit class GameController { var gameView: UIView! var level: Level! init() { } func dealRandomAnagram() { } } I bet you’ve already spotted the building blocks of your current goal: gameView: The view you’ll use to display game elements on the screen. level: The Levelobject that stores the anagrams and other settings for the current game level. dealRandomAnagram(): The method you’ll call to display the current anagram on the screen. The variables are declared as implicitly unwrapped optionals, as they should never be nil, but you will not be creating the instances in the GameController’s initializer. The code so far is pretty simple. Change dealRandomAnagram() to have this placeholder implementation: func dealRandomAnagram () { //1 assert(level.anagrams.count > 0, "no level loaded") //2 let randomIndex = randomNumber(minX:0, maxX:UInt32(level.anagrams.count-1)) let anagramPair = level.anagrams[randomIndex] //3 let anagram1 = anagramPair[0] as! String let anagram2 = anagramPair[1] as! String //4 let anagram1length = count(anagram1) let anagram2length = count(anagram2) //5 println("phrase1[\(anagram1length)]: \(anagram1)") println("phrase2[\(anagram2length)]: \(anagram2)") } This method will fetch a random anagram, deal the letter tiles, and create the targets. Here’s what happening in the code, section by section: - You check to make sure this method is only called after the levelproperty is set and that its Levelobject contains anagrams. - You generate a random index into the anagram list, then grab the anagram at this index. This randomNumber()function is defined in Config.swift. - You store the two phrases into anagram1and anagram2. - Then you store the number of characters in each phrase into anagram1lengthand anagram2length. Even though the letters are the same between anagram1 and anagram2, there can be a different number of spaces so the overall number of characters can be different. - Finally, you print the phrases to the console. This will suffice for testing. Your app is already set up to load the storyboard Main.storyboard at start up. This storyboard creates a single screen using the ViewController class. Since your game will only have one screen, you will add all initialization inside the ViewController initializer. For games that include more than one view controller, you may want to do your initialization someplace else, such as the AppDelegate class. Open up ViewController.swift and add this property inside the ViewController class: private let controller:GameController Finally, add a new initializer to the class: required init(coder aDecoder: NSCoder) { controller = GameController() super.init(coder: aDecoder) } The app will use the init(coder:) initializer automatically when it instantiates a ViewController from the storyboard. There it is! You’ve created a GameController class and you have an instance of it in your ViewController class, ready to go off and spill some letter tiles on the screen at any moment. :] 3) Create an Onscreen View The next step is also quite easy: you need to create a view on the screen and connect your GameController to it. Open up Config.swift and look at the first two constants inside the file: ScreenWidth and ScreenHeight. You are going to use these constants to create your game view. Switch back to ViewController.swift and add the following code at the end of viewDidLoad(): //add one layer for all game elements let gameView = UIView(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight)) self.view.addSubview(gameView) controller.gameView = gameView Here, you create a new view with the dimensions of the screen and add it to the ViewController‘s view. Then you assign it to the gameView property of your GameController instance. This way the GameController will use this view for all game elements. You’ll create a separate view for the heads-up display (HUD) later. Having now created your model and controller classes, you’ve come to the point where you need your first custom view class for the Anagrams game to display the tiles. 4) Create a Tile View In this section, you are going to build a view to show tiles like these: For now, you’ll focus on just creating the tile squares with the background image. Later, you’ll add the letters on top. Inside the file group Anagrams/Classes/Views, create a new Swift file called TileView. Add the following to TileView.swift: import UIKit //1 class TileView:UIImageView { //2 var letter: Character //3 var isMatched: Bool = false //4 this should never be called required init(coder aDecoder:NSCoder) { fatalError("use init(letter:, sideLength:") } //5 create a new tile for a given letter init(letter:Character, sideLength:CGFloat) { self.letter = letter //the tile background let image = UIImage(named: "tile")! //superclass initializer //references to superview's "self" must take place after super.init super.init(image:image) //6 resize the tile let scale = sideLength / image.size.width self.frame = CGRect(x: 0, y: 0, width: image.size.width * scale, height: image.size.height * scale) //more initialization here } } There are a few different sections in the code: - Make the class a subclass of UIImageView. The UIImageViewclass provides you with the means to show an image, so you’ll only need to add a label on top of the image later on. letter: A property that will hold the letter assigned to the tile. isMatched: A property, initially set to false, that will hold a Boolean indicating whether this tile has already been successfully matched. - This is UIImageView‘s required initializer, which must be overridden even though you’ll never use it. init(letter:sideLength:): a custom initializer to set up an instance of the class with a given letter and tile size. It saves the letter to the tile’s variable and loads the tile.png image. - You then calculate by how much you need to scale the default tile so that you get a size that will fit your board for the given word or phrase. To do that, you just adjust the frameof the TileView. UIImageViewresizes its image automatically to match its frame size. Why do you need to set the size of the tile, you might ask? Look at the these two setups: The top example shows a short word that requires large tiles to fill the screen. The bottom example shows a phrase that requires smaller tiles because it has almost double the tile count. The tile view needs to be resizeable so that you can show different size tile depending on how many tiles there are on the screen at a time. Your controller will calculate the phrase length, divide the screen width by the number of characters and decide on a tile size. You’ll implement that soon, but this code is already enough to show tiles containing just the empty tile.png image. 5) Dealing the Tiles on the Screen Switch back to GameController.swift – your dealRandomAnagram() method already loads the data you need, but it still does not do much. Time to fix that! Add the following property to the GameController class: private var tiles = [TileView]() This is an array to hold the TileView objects that will display the tiles at the bottom of the screen. These tiles contain the initial phrase of the anagram. Later you will also create an array to hold the target views that will display the spaces at the top of the screen where the player has to drag the tiles to form the second phrase of the anagram. Before you continue, you also need a constant for the space between the tiles. Jump over to Config.swift and add the following: let TileMargin: CGFloat = 20.0 Some of you might already be protesting, “Can’t I just use 20 where I need it and be done?” It’s a good point, but there is a reason for predefining in the config file. My experience shows that you will have to tweak any numbers you have in your code when it comes time to fine-tune the gameplay. So best practice is to externalize all numbers to a config file and give those variables meaningful names. This will pay off especially well if you are working in a team and you need to hand the game to a game designer for fine-tuning. :] OK, back in GameController.swift, get ready to add some code to the end of dealRandomAnagram(). You have the number of characters in both phrases, so it’s easy to calculate what size tiles you need. Add this code at the end of the method: //calculate the tile size let tileSide = ceil(ScreenWidth * 0.9 / CGFloat(max(anagram1length, anagram2length))) - TileMargin You take 90% of the width of the screen and divide it by the number of characters. You use the length of the longer phrase – remember, the number of characters can vary! You decrease the result by TileMargin to account for spacing between tiles. Next find the initial x position of the first tile. It will depend on the length of the word and the tile size you just calculated. Once again, add the following at the end of dealRandomAnagram(): //get the left margin for first tile var xOffset = (ScreenWidth - CGFloat(max(anagram1length, anagram2length)) * (tileSide + TileMargin)) / 2.0 //adjust for tile center (instead of the tile's origin) xOffset += tileSide / 2.0 You take the screen width, subtract the calculated width of the word tiles and find where the first tile should be positioned on the screen. Wouldn’t it be nice if there were a simpler way to “center” the tiles! Continuing in the same method, add the following code to display the tiles: //1 initialize tile list tiles = [] //2 create tiles for (index, letter) in enumerate(anagram1) { //3 if letter != " " { let tile = TileView(letter: letter, sideLength: tileSide) tile.center = CGPointMake(xOffset + CGFloat(index)*(tileSide + TileMargin), ScreenHeight/4*3) //4 gameView.addSubview(tile) tiles.append(tile) } } Here’s what’s happening above: - First you initialize a fresh copy of your tilesarray. It’s important to start with an empty array here because this function will be called multiple times during a run of your app. Since spaces are skipped, if you didn’t clear out the array then there might be old tiles left over from a previous phrase where there should be spaces. - You then loop through the phrase. You will need both the letter from the phrase and the position of the letter, so use enumeratewhich returns a tuple of the index + the value. - You check each letter and if it is not a space, it’s a go! You create a new tile and position it using xOffset, tileSideand TileMargin. Here you are calculating the position based on that letter’s position in the phrase, which is represented by index. So if indexis 5, this math will figure out how much space five tiles take up and add the new tile to the right of that space. You position the tiles vertically at 3/4ths of the screen height. - Finally, you add the tile to the gameViewand to the tilesarray. The first actually shows the tile on the screen, while the latter helps you loop faster over the tiles later on. Alrighty! Time for the final touch – you need to load the level data and call dealRandomAnagram(). Switch to ViewController.swift and add these two lines at the end of viewDidLoad(): controller.level = level1 controller.dealRandomAnagram() Remember that you already have a Level object, so you just pass it on to your GameController and call dealRandomAnagram(). It’s been a long time coming, but build and run to check out the result! Your app should look something like this: Awesome, it works! It’s alive!!! Note: Your view probably won’t look exactly like this because the app is choosing a random anagram each time it runs. Run it a few times to see how the app sizes the tiles differently for different phrases. The console output will show you the phrases used. You are closing in on the finish line for the first part of this tutorial series! 6) Add the Letters Switch to TileView.swift. This is where you’re going to add letters to those tiles. Find init(letter:sideLength:) and add the following code to the end: //add a letter on top let letterLabel = UILabel(frame: self.bounds) letterLabel.textAlignment = NSTextAlignment.Center letterLabel.textColor = UIColor.whiteColor() letterLabel.backgroundColor = UIColor.clearColor() letterLabel.text = String(letter).uppercaseString letterLabel.font = UIFont(name: "Verdana-Bold", size: 78.0*scale) self.addSubview(letterLabel) The above code creates a new UILabel and adds it to the tile view. Because you want the letter to be as easy to read as possible, you create the label to be as large as the tile itself. You then align the letter to show up in the center of the tile. You ensure the letter is uppercase by setting the label text with String(letter).uppercaseString. Using capital letters will ease the game play, as they are easier to recognize, specifically by children. Always think about your game’s target audience! Finally you reuse the scale factor you calculated earlier. For the full-size tile a Verdana font with a size of 78 pts fits well, but for other sizes you need to scale the font size accordingly. Build and run the project. As I said, you’re now moving fast towards your goal. Good job! :] Once again, your screen probably won’t look just like this one. But that just means your game controller is doing what’s it’s supposed to do and dealing a random anagram. Nice! Have another look at the image above. Right now the tiles look like they were put on the board by a pedantic robot: they are perfectly aligned. Now comes the time to add a pinch of randomization! 7) Slightly Rotate the Letters Randomly Randomization is one of the keys to building a successful computer game. You want to randomize your game as much as possible. For example, no player enjoys enemies that all do the same thing every time the game runs. In the case of the Anagrams game, you can randomize the placement of each tile so that they look more natural on the game board, as if a human put them down without trying too hard to align them properly: In order to accomplish this randomization, add the following method to the TileView class in TileView.swift: func randomize() { //1 //set random rotation of the tile //anywhere between -0.2 and 0.3 radians let rotation = CGFloat(randomNumber(minX:0, maxX:50)) / 100.0 - 0.2 self.transform = CGAffineTransformMakeRotation(rotation) //2 //move randomly upwards let yOffset = CGFloat(randomNumber(minX: 0, maxX: 10) - 10) self.center = CGPointMake(self.center.x, self.center.y + yOffset) } This code does two things: - It generates a random angle between -0.2 and 0.3 radians (using the helper function randomNumberdefined in Config.swift). Then it calls CGAffineTransformMakeRotation()to create a new transform for the tile view that will rotate it around its center by that random angle. - It generates a random value between -10 and 0 and moves the tile up by that offset. Note: You might want to replace all of these numbers with constants you define in Config.swift so you can fine-tune the tile appearance more easily. Now you just need to call this method. Inside GameController.swift, edit dealRandomAnagram() by adding the following line of code just after the line that begins with tile.center = ...: tile.randomize() And that’s all it takes! Hit run again to see the randomized tiles on the board: Using what you’ve already achieved, you can also quickly add the targets to the game board. Let’s do that before wrapping up this part of the tutorial. 8) Add the Targets The target views are pretty similar to the tile views. They also subclass UIImageView and show a default image, and they also are assigned a letter. The difference is that they don’t show a label with that letter and can’t be dragged around. This means the code you need for the targets is similar to what you did before – but simpler! Inside the file group Anagram/Classes/Views, create a new Swift file called TargetView. Add the following to TargetView.swift: import UIKit class TargetView: UIImageView { var letter: Character var isMatched:Bool = false //this should never be called required init(coder aDecoder:NSCoder) { fatalError("use init(letter:, sideLength:") } init(letter:Character, sideLength:CGFloat) { self.letter = letter let image = UIImage(named: "slot")! super.init(image:image) let scale = sideLength / image.size.width self.frame = CGRectMake(0, 0, image.size.width * scale, image.size.height * scale) } } Yes, this uses exactly the same properties and function (aside from changing the image) as for the TileView! You resize the image according to the provided side length and assign the letter – that’s all. Now to display the targets on the screen. Open up GameController.swift and add the following property to the class: private var targets = [TargetView]() Then add the following code inside dealRandomAnagram(), just before the comment that reads “//1 initialize tile list”: //initialize target list targets = [] //create targets for (index, letter) in enumerate(anagram2) { if letter != " " { let target = TargetView(letter: letter, sideLength: tileSide) target.center = CGPointMake(xOffset + CGFloat(index)*(tileSide + TileMargin), ScreenHeight/4) gameView.addSubview(target) targets.append(target) } } This is almost the same code you used to deal the tiles on the board, except this time you grab the letters from the phrase stored in anagram2 and you don’t randomize their position. You want the target views to look nice and neat, after all! Why does the target initialization have to come before the tile initialization? Subviews are drawn in the order they are added to their parent view, so adding the target views first ensures that they will appear behind, or below, the tiles. If you did want to add the target views after the tile views, there are other ways to get them behind the tiles, such as UIView‘s sendSubviewToBack(view:) method. But adding them first is the most efficient solution. Build and run again to see that your board is already close to being finished! Remember, the anagrams consist of two phrases which have the same letters but might have different spacing. So everything is working as expected if you see something like the screenshot above with three tiles followed by four tiles, while the targets at the top are four tiles followed by three tiles. Where to Go from Here? Click here to download the full source code for the project up to this point. Congrats, you’ve achieved a lot today! Let’s see what you’ve done so far: - You’ve created a model to load the level configuration. - You’ve connected the game controller, game view and model. - You have two custom views, one for tiles and one for targets. - You’ve finished the initial board setup. You now have a sound foundation on which to build. Stay tuned for Part 2 of the series, where you’ll begin interacting with the player and building up the gameplay. In the meantime, if you have any questions or comments about what you’ve done so far, drop by the forums to contribute your two tiles’ worth. :]
https://www.raywenderlich.com/2187-how-to-make-a-letter-word-game-with-uikit-and-swift-part-1-3
CC-MAIN-2019-35
refinedweb
4,750
65.83
Learn Java in a day Learn Java in a day  ... and for) and branching statements (break, continue and return). The control statement... of java concepts through simple programs. We hope, "Learn java Java error missing return statement Java error missing return statement Java error missing return statement are those error in Java that occurred when a programmer forget to write The Switch statement . To avoid this we can use Switch statements in Java. The switch statement is used... of a variable or expression. The switch statement in Java is the best way to test... with the next case after executing the first statement. Here is an example Return Statement in PHP In PHP Return is a Statment that returns value back to the calling program. For example if the Return Statment is called from within a function it will end.... Output of return function call example 104 Java - Break statement in java Java - Break statement in java  ...; 2.The continue statement 3.The return statement Break: The break statement is used in many programming languages such as c, c++, java etc. Some JDBC Batch SQL Update Statement Example With Return Number of Effected Rows JDBC Batch SQL Update Statement Example With Return Number of Effected Rows: In this example, we are discuss about update statement with return number... SQL statements and execute on the created statement object and store return What is the difference between a break statement and a continue statement? and return statement etc. Other-then Java programming language the break... statement? Thanks, Hello, In Java programming language supports 3...What is the difference between a break statement and a continue statement Switch Statement in java 7 Switch Statement in java 7 This tutorial describes the if statement in java 7. This is one kind of decision making statement. Switch Statements... executed. Example : In this example we are using switch -case statement Switch Statement example in Java the switch statement. Here, you will learn how to use the switch statement in your java... Switch Statement example in Java   ... you an example with complete java source code for understanding more about JDBC Prepared Statement Example JDBC Prepared Statement Example  ... Prepared Statement Example. The code include a class JDBC... set is assigned in a result set. The select statement return you a record set if else statement in java if else statement in java if else statement in java explain with example Continue and break statement statement in java program? The continue statement restart the current loop whereas the break statement causes the control outside the loop. Here is an example of break and continue statement. Example - public class ContinueBreak if else statement in java if else statement in java explain about simple if else statement and complex if else statement in java with an example java if statement java if statement If statement in Java Switch Statement Switch Statement How we can use switch case in java program ?  ... switches to statement by testing the value. import java.io.BufferedReader; import... Enter the number 3 Tuesday Description: - In this example, we are using Control Statments top to bottom. We will learn how the different kinds of statement have... statements (break, continue, return) in Java programming language. Selection The if statement: To start with controlling statements in Java, lets have a recap over conditional statement in java conditional statement in java Write a conditional statement in Java Logical and comparison statements in OOPs are also know as conditional statements. You can learn "How to write conditional statement in Java " from Java - Continue statement in Java Java - Continue statement in Java Continue: The continue statement is used in many programming... and continue statement that the break statement exit control from the loop Java Method Return Multiple Values Java Method Return Multiple Values In this section we will learn about how a method can return multiple values in Java. This example explains you how... the steps required in to return multiple values in Java. In this example you will see Break statement in java Break statement in java Break statement in java is used to change the normal control flow of compound statement like while, do-while , for. Break...; loop. Within a loop if a break statement is encountered then control resume Java Import Statement Cleanup - Java Tutorials Java Import Statement Cleanup 2002-06-18 The Java Specialists' Newsletter [Issue 051] - Java Import Statement Cleanup Author: Dr. Cay S. Horstmann... to receive training in Design Patterns. Java Import Statement Cleanup GOTO Statement in java GOTO Statement in java I have tried many time to use java goto statement but it never works i search from youtube google but e the example on net are also give compile error. if possible please give me some code with example Summary - Control Flow Java: Summary - Control Flow Each control statement is one logical.... Another example of switch statement also shows how to use the switch... or some other statement (break or return) stops the loop. while Java Method Return Value Java Method Return Value  ... When it reaches a return statement throwing an exception, whichever occurred first. The return statement is used to return ... statement to do if condition is false Example 1 - true and false parts... is a statement? A statement is a part of a Java program. We have already Java Switch Statement Java Switch Statement In java, switch is one of the control statement which turns the normal flow control of the program as per conditions. It's like if-else statement but it can Strings in Switch statement Strings in Switch statement In this section, you will learn about strings in switch statements which is recently added feature in Java SE 7. Using JDK 7, you can pass string as expression in switch statement. The switch statement If statement in java 7 If statement in java 7 This tutorial describes the if statement in java 7. This is one kind of decision making statement. There are various way to use if statement with else - If Statement : If statement contains one boolean JDBC Prepared statement Close an example from JDBC Prepared Statement Close. In this program, the code describe how... the record set from a table. The select statement return you a result set... JDBC Prepared statement Close   sontrol statement - Java Beginners sontrol statement hi to all, can anybody send me program in which "break" and "continue" is used simultaneously.? plz its urgent. Hi Friend, You can try the following example code: public class ContinueBreak J Implementing Continue Statement In Java Implementing Continue Statement In Java In this Session you will learn how to use continue statement. First all of define class "Continue" The try-with-resource Statement The try-with-resource Statement In this section, you will learn about newly added try-with-resource statement in Java SE 7. The try-with-resource statement contains declaration of one or more resources. As you know, prior use of return statement use of return statement what is the use of return statement JDBC Prepared Statement Example successfully Using prepared statement............ Download this example code...; } JDBC Prepared Statement java.sql.PreparedStatement is enhanced version... and also add some extra feature to it. In is an enhanced version of statement which 'if' Statement - Braces Java Notes'if' Statement - Braces Braces { } not required for one... one statement to do if condition is false Example 1 - true and false... was expected. What is a statement? A statement is a part of a Java Java find prime numbers without using break statement Java find prime numbers without using break statement In this tutorial, you will learn how to find the prime numbers without using break statement. You all... this break statement transfer the control at the end of the loop. This tutorial switch statement switch statement i want to write a java program that computes Fibonacci,factorial,string reversal and ackerman using switch case to run as a single program JAVA statement - Java Beginners JAVA statement The import statement is always the first noncomment statement in a Java program file.Is it true? Hi Friend, No,it is not true.If your class belongs to a package, the package statement should 'while' Statement Java Notes'while' Statement Purpose - to repeat statements The purpose of the while statement is to repeat a group of Java statements many times. It's written just like an if statement, except that it uses JDBC Batch Example With SQL Delete Statement JDBC Batch Example With SQL Delete Statement: Learn How to use delete MySql statement with JDBC Batch processing. First of all, we will create a java class... in the database table. 1. Create Statement object using createStatement() method Break Statement in java 7 Break Statement in java 7 In this tutorial we will discuss about break statement in java 7. Break Statement : Java facilitate you to break the flow...-while, switch statement. Example : This is a simple example of unlabeled break Continue Statement the control to the enclosing labeled statement. A continue statement statement must... about Continue Statement click on the link http:/... Continue Statement   Java Control Statements Java Control Statements  ... and for) and branching statements (break, continue and return). Control Statements The control statement are used to controll the flow of execution Continue Statement in java 7 Continue Statement in java 7 In this tutorial we will discuss about continue statement in java 7. Continue Statement : Sometimes you need to skip block... statement in loops. In java 7, Continue statement stops the current iteration SQL And Statement with Example The Tutorial illustrates an example from SQL AND Statement... SQL AND Statement  .... The Select return you the records or row from table Stu_Table. Create Java callable statement Java callable statement What is callable statement? Tell me the way to get the callable statement Java switch statement Java switch statement What restrictions are placed on the values of each case of a switch statement JDBC Execute Statement JDBC Execute Statement JDBC Execute Statement is used to execute SQL Statement, The Execute Statement accept SQL object as parameter and return you the result set from Break Statement Java Break Statement  ... of java. It is used to terminate the loop coded inside the program. Example below demonstrates the working of break statement inside the program. This example if Statement - Overview Java Notesif Statement - Overview Purpose The purpose of the if statement is to make decisions, and execute different parts of your program depending... with if. [The other 1% of the decisions use the switch/case statement Prepared Statement Example is used to make the SQL statement execution efficient. In Java, when we use... the PreaparedStatement. In this example we will execute a SQL statement using PreparedStatement object. In this example we will use "INSERT INTO" SQL statement JDBC Update Statement Example .style1 { text-align: center; } JDBC Update Statement Example JDBC update statement is used to update the records of a table using java application program. The Statement object returns an int value that indicates how many Java IF statement problem Java IF statement problem Dear Sir/Madam i am using the following code. expected to not have any output but it still showing "welcome".. please help me why it showing "welcome". class c1 { int a=5; while(a>1 Understanding jQuery statement chaining Understanding jQuery statement chaining Understanding jQuery statement chaining JQuery provide statement chaining which can reduce the length of Prepared Statement Insert JDBC Prepared Statement Insert  ... Statement Insert. In this Tutorial the code describe the include a class... that enables you to communicate between front end application in java and database Executing Prepared Statement ; } Executing Prepared Statement Prepared Statement represents the pre-compiled query with parameter and no-parameter. An example given below is no-parameter prepared statement example. Example- At first create table named student MySQL Select Statement MySQL Select Statement In this lesson you will be learn how to use SELECT statement in MySQL and you can also learn how to use SELECT statement with WHERE Java Control Statements Java Control Statements  ... if The if statement: To start with controlling statements in Java, lets have a recap over... in C++. The if-then statement is the most simpler form of control flow statement The continue statement The continue statement is used in many programming languages such as C . There is the difference between break and continue statement that the break statement exit control...The continue statement The continue statement is used in many programming languages such as C. The continue statement The continue statement is used JDBC Training, Learn JDBC yourself programming language of java then fist learn our following two tutorials: Learn Java in a Day and Master... JDBC Connection Pooling Accessing Database using Java and JDBC Learn how For Loop Statement in java 7 For Loop Statement in java 7 In this section, we will discuss about for loop in java 7. This is one type of loop statement. For Loop Statements...) {....... ...... //Statements } Example : Here is simple for loop example. First we The UPDATE Statement The UPDATE Statement The UPDATE statement is used to modify the data in the database table through a specified criteria. In the given syntax of update statement the keyword SET in string how will write the return statement..........? in string how will write the return statement..........? import java.util.Scanner; class BinaryConversion12{ static int j=1; static int l=1; public static void main(String args[]){ int i=Integer.parseInt(args[0 PHP Return Statements to stop the eval() statement or script file. PHP Return Statement Example...PHP Returning Statement Values: PHP Return statement is used to return a value or control to the calling portion of the program. It is an optional statement Java Review: Control Flow Java Review: Control Flow Java uses the dominant imperative control flow.... Structured Programming control flow primitives within a method: Sequence......catch). Ways to exit or continue early (break, return, continue syntax error in SQL Insert Statement - Java Beginners ","",""); Statement stmt=con1.createStatement(); int i... change your field name 'date' to 'day' and run the following query: int i=stmt.executeUpdate("insert into newfresher(prn,day,lname,fname,mname,dob,address,city While loop Statement. While loop Statement. How to Print Table In java using While Loop Java - The switch construct in Java Java - The switch construct in Java Switch is the control statement in java which... flow of control quits from the Switch block whenever break statement occurs How to use 'if' statement in jsp page? conditions. You can understand use of this statement by a real world example. Suppose... How to use 'if' statement in jsp page? This is detailed java code that shows Java error unreachable statement Java error unreachable statement  ... exits the control of the expression from the loop, but continue statement put... a code that help you in understanding a unreachable statement. For this we Get first day of week Get first day of week In this section, we will learn how to get the first day of ..._package>java FirstDayOfWeek Day of week: 7 Sunday Use HANDLER Statement in Cursors The Tutorial illustrate an example from 'Use HANDLER Statement... Use HANDLER Statement in Cursors Use HANDLER Statement in Cursor is used to define SQL select statement doesn't return any rows, SQL select statement doesn't return any rows, When an SQL select statement doesn't return any rows, is an SQLException thrown 'if' Statement - 'else if' style Java Notes'if' Statement - 'else if' style Series of tests... contains only another if statement. If you use indentation for the else.... Example -- series of tests This code is correctly indented, but ugly prepare statement prepare statement sir i want example of prepare statement JDBC Batch Example With SQL Update Statement JDBC Batch Example With SQL Update Statement: In this tutorial, we are discuss about update SQL statement with the jdbc batch. Now we will create a java...;); Now we will create Statement object by using createStatement() method for statement for statement for(int i=0;i<5;i++); { system.out.println("The value of i is :"+i); } if i end for statement what will be the output got the answer.. it displays only the last iteration that is "The value of i Java get Next Day Java get Next Day In this section, you will study how to get the next day in java... day. cal.get(Calendar.DAY_OF_WEEK)+1- This will return the next day. Here Return Java Keyword Return Java Keyword The return is a keyword defined in the java programming language. Keywords... in java programming language likewise the return keyword indicates the following PHP Control Statement PHP Control Statement The PHP Conditional statements helps us to perform... and switch case. Example: php-control-stmt.html <!DOCTYPE html PUBLIC "... to control the flow of the program according to the requirement of the program How to use switch statement in jsp code How to use switch statement in jsp code switch is a type of control statement used... and that will be an error. The example below demonstrates how we can use switch statement in our JSP SELECT statement for SQL The SELECT statement for SQL SELECT key word is used to select data from a table. Syntax...) FROM table_name Example: To select Use if statement with LOOP statement with Example The Tutorial illustrate a example from if statement with LOOP statement. In this example we create a procedure display that accept... Use if statement with LOOP statement   Branching Statements in java 7 Branching Statements in java 7. This is one type of control flow statement. Branching... : break statement continue statement return statement Break Statement... statement provided by the java 7. Its functionality to stop the current SQL SELECT DISTINCT Statement statement to eliminate duplicate values from the column. Understand with Example...); Stu_Table The Select statement return you the records from... SQL SELECT DISTINCT Statement   While Loop Statement in java 7 While Loop Statement in java 7 This tutorial, helps you to understand the concept of while loop in java 7. While Loop Statements : While loop.... You can use any counter to iterate the loop. This type of control structure Java date add day Java date add day In this tutorial, you will learn how to add days to date... to add few days to current date and return the date of that day. For this, we... to the calendar and using the Date class, we have got the date of that day. Example Control Flow Statements in java 7 Control Flow Statements in java 7 In this section we will discuss Control Flow Statements in java 7. This is one type of Language Fundamentals. Control... continue statement return statement SQL SELECT DISTINCT Statement statement to eliminate duplicate values from the column. Understand with Example...,'Santosh',10); Stu_Table The Select statement return you... SQL SELECT DISTINCT Statement   Nested If Statement . Here we are providing you an example using Nested-If statement. In the example, we... Nested If Statement In this section you will study about the Nested-if Statement in jsp Ask Questions? If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://www.roseindia.net/tutorialhelp/comment/66286
CC-MAIN-2013-20
refinedweb
3,206
55.03
Method For A Staggered Restart Of A Rails Site Running Fcgid And Capistrano killing the dispatch processes too fast was triggering too many rails boots and making one of our sites thrash. This bit of bash can be used to kill them softly. (with it's song...) def dispatch_killer apache_user, seconds_between_kills=1 run <<-CMD pids=`ps -U #{apache_user} -o pid,command | grep #{current_path} | awk '{print $1;}'`;\ for pid in $pids ;do \ #{ sudo :as => remote_user } -u #{apache_user} kill $pid; \ sleep #{seconds_between_kills}; \ done CMD enda recipie could use this method like this: namespace :deploy do task :restart, :roles => :app do dispatch_killer 'www', 10 # as www issue kills 10 seconds apart end endwe came up with 10 seconds by timing the boots of script/console. no more thrashing! (props to James at for the idea)
https://dzone.com/articles/method-staggered-restart-rails
CC-MAIN-2015-40
refinedweb
132
66.88
In this Python Turtle tutorial, we will learn to work with Replit Python Turtle and we will also cover different examples related to Replit Turtle. And, we will cover these topics. - Replit python turtle - Replit Python turtle house Replit Python Turtle In this section, we will learn about Replit in Python Turtle. Replit is a coding Platform where we can write code and make projects. Here we can host the Apps with help of Replit. It is used in different ways which can be replaced by the following: - Code Editors (VS Code, Subline) - Build tools like NPM - Cloud Service Provider (AWS, Netlify) - Community Collabration Tool (Google, Github) Code: We import turtle module from turtle import *, import turtle as tur. - tur.pensize(8) is used to increase or decrease the thickness of the line. - tur.circle(100) is used for drawing the circle on the screen. from turtle import * import turtle as tur tur.pensize(8) tur.circle(100) tur.circle(50) tur.done() Output: Äfter running the above code we can see the following output which is done by using the pensize() and circle() functions in Replit. Read: Python Turtle Size Replit Python turtle house In this section, we will learn about how to build a Replit turtle house in Python. As we know replit is a coding platform where we can write our code and execute it and even we can host the apps over to that platform. In this, we make a code which we can execute on replit and host that app on a browser. Code: In the following code, we import the turtle module which helps to draw images of pictures. - speed(0) is used to give the speed to the turtle and 0 is the fastest speed. - color() is used to give color to the image for an attractive look. - forward() is the direction function that moves over the turtle pen to make a shape. - left() is the direction function that moves over the turtle pen to make a shape. - right() is the direction function that moves over the turtle pen to make a shape. from turtle import * import turtle speed(0) color('brown') forward(350) left(90) forward(100) color("alice blue") begin_fill() forward(250) left(90) forward(490) left(90) forward(250) left(90) forward(491) end_fill() color("brown") right(90) forward(100) right(90) forward(630) penup() left(180) forward(180) left(90) forward(45) color("dark green") begin_fill() right(385) forward(170) right(130) forward(170) right(115) forward(82) end_fill() penup() color("brown") right(180) forward(30) pendown() begin_fill() right(90) forward(45) right(90) forward(45) right(90) forward(45) right(90) forward(45) end_fill() penup() right(90) forward(45) right(90) forward(45) #pendown() color("brown") forward(110) color("brown") right(90) forward(105) color("blue") forward(105) color("blue") right(90) forward(300) right(180) pendown() circle(30,50) right(90) circle(30,50) penup() left(170) forward(200) pendown() color("yellow") begin_fill() circle(60) end_fill() penup() color("blue") right(90) forward(206) right(90) forward(125) pendown() color("black") begin_fill() forward(25) right(90) forward(40) right(90) forward(25) right(90) forward(40) end_fill() color("red") left(90) forward(50) left(90) forward(100) left(90) forward(125) left(90) forward(100) left(90) forward(50) right(180) forward(50) right(90) forward(100) right(45) forward(90) right(90) forward(90) right(45) penup() forward(100) right(90) turtle.done() Output: In the above code, we use the python turtle module and forward(), right() color(), left() functions to make a picture of the house using a python turtlepen. In Replit we can host our apps and run our code on a server that we can access from anywhere. Link: In this link, we can see how our code is working on Replit Platform and we can access that to see the output. You may also like to read the following articles. - Python Turtle Font - Python Turtle Tracer - Python Turtle Square - Python Turtle Triangle - Python Turtle Art - Python Turtle Circle - Python Turtle Speed - Python Turtle Colors - How to Draw Flower in Python Turtle So, in this tutorial, we discussed Replit Python Turtle and we have also covered different examples related to its implementation. Here is the list of examples that we have covered. - Replit python turtle - Replit Python turtle house Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.
https://pythonguides.com/replit-python-turtle/
CC-MAIN-2022-21
refinedweb
736
57.3
A few years ago a friend of mine showed me the hilarious Harry Potter and the Portrait of what Looked Like a Large Pile of Ash, created by Botnik, and subsequentially I've fallen in love with the idea of training machines to write. Since then I've been exploring the internet looking for funny/weird/awesome content generated by AIs, here's a taste of what I've found so far: - Sunspring - a short sci-fi film by Oscar Sharp and Ross Goodwin. - Speedgate - a sport where the rules were written by an AI. - Recipes that are written by an AI. There are lots of examples of these but my favourite was when Botnik created videos of people following the recipes. I've since decided it'd be a great side project to look into myself. So, how can you get started? You might think this could be a complicated, long process but trust me it's not! Thanks to the help of the amazing work done by Max Woolf and his Python module textgenrnn. Textgenrnn is a Python 3 module on top of Keras/TensorFlow for creating char-rnns. If none of that sentence made any sense, don't worry - it creates neural networks that learn based on input text you provide the model. First, we want to install Textgenrnn and TensorFlow using pip, like this: pip3 install textgenrnn tensorflow Now in your favourite Python IDE/text editor (I use Spyder) simply add the following 3 (yes only 3!) lines of Python: from textgenrnn import textgenrnn textgen = textgenrnn() textgen.generate() If you run the above, as per the Textgenrnn tutorial, you will see an output something like: [Spoiler] Anyone else find this post and their person that was a little more than I really like the Star Wars in the fire or health and posting a personal house of the 2016 Letter for the game in a report of my backyard. Now that didn't make much sense and the reason your output won't be the same as the above is that you have made an AI write text. That's right the output was that of an AI that has been trained on data inside the Textgenrnn module. How awesome is that? Well done on training your first AI text generator! Let's find some data We've got an AI to generate output based on pre-loaded data, all we need to do now is train the model on a new text. And as it turns out this only takes two lines of code: textgen.train_from_file('yourFileGoesHere.txt', num_epochs=1) textgen.generate() The hard part, as usual, is getting lots of data and data in the correct format. That's why I chose Harry Potter, I knew the fans would have me covered and they did: spells.csv, a CSV of different spells from the books! Thank you @Gulsah Demiryurek all credit to you! :) Note: you will want to be careful that data you find is clean and suitable for your use case, I tidied up the above (mainly removing " and additional ; from the values) and you can find that here. Now all we need to do is add our csv file to the train_from_file, right? Unfortunately not, Textgenrnn requires our data to be in a specific format, that is values on separate lines. We need to pick out the spells and effects from the csv and save them in separate text files like so: # Get spells and effects from csv with open('Spells.csv') as csvfile: spells = [] effects = [] spellsreader = csv.reader(csvfile, delimiter=';') next(spellsreader, None) # skip the headers for row in spellsreader: if not (row[1] == 'Unknown' or row[1] == ''): print(row[1]) spells.append(row[1]) effects.append(row[3]) # Write to single line text files ready for input to textgenrnn with open("spells.txt", "w") as output: output.write('\n'.join(spells)) with open("effects.txt", "w") as output: output.write('\n'.join(effects)) Now we have our data!! Putting it all together to Harry Potter-ify the output To generate spells, we can simply do the following: # Generate Spells spellgen = textgenrnn() spellgen.train_from_file('spells.txt', num_epochs=1) generated_spells = spellgen.generate(5, return_as_list=True) output: Evpaborrra Incendiarars Lomomorrius Flips Glandiren Skullus Similarly to generate spell effects: # Generate Spell Effects effectgen = textgenrnn() effectgen.train_from_file('effects.txt', num_epochs=1) generated_effects = effectgen.generate(5, return_as_list=True) output: Mends target Conjures sparks Turns water to splose she nothing the juckers Turns target to shee These outputs are, um, interesting? Generated content is never going to make perfect sense - we know that and it's part of the fun - but I'd like it more if the spells and effects were linked to one another. For example, "Incendiarars" should set something on fire, "Evpaborra" should evaporate something and "Flips" should well flip something. Let's try to generate effects based on the spell name. To do this is simple when we create our spells and effects arrays instead just create one where each element is a spell name and the effect: spell = "%s: %s" % (row[1],row[3]) print(spell) spells.append(spell) This way the data our model is trained on (and therefore the data our model outputs) will be a spell name followed by its corresponding effect. Now we only train from spells.txt, my output was the following: Flippers: Turns target Stuckus: Creates mess of things in the wand things Incardimo: Reveals doors Solor: Reveals objects of the flames Victimous: Transimotions target I'm not sure this fixed the problem but it does look better to me, Solor is fire/light related and this time Flippers is flipping something - flipping brilliant! If you have any ideas on further improvements, I'd love to hear from you in the comments :) Well, we did it! We generated new Harry Potter spells - though I'm not convinced J K Rowling will want to use them! Where to go from here? Hopefully, this example has shown how easy it is to generate text using Textgenrnn. From here, as long as you can find the data, you could generate anything you want. Kaggle Datasets are always a great source of data and are usually well documented. However, I would also encourage you to do something more personal/relevant to you, as this always helps with motivation. During a hackathon at my workplace, I generated Jira tickets based on all of the Jira tickets in our backlog (you can easily download a CSV of these), this was very amusing but also showed how poorly some of our tickets were written and how repetitive they could be. For example: "document project" was in a lot of our Jira ticket names, and so my neural network came up with "document document project document project" - a subtle reminder we devs often neglect to document our work. Please above all else have fun exploring the peculiar world of text generation! The full code for this post can be found on my GitHub. This is my first dev.to post and my first blog post ever, all feedback is hugely appreciated! I hope somebody has found this helpful and/or interesting. Thank you for reading! :) Posted on by: Ryan Joseph (he/him) Interested in learning and learning how to learn better! Currently looking into Machine Learning, using Python. I love running, reading, baking and hanging out with Lyra, my cat 🐈 Discussion While everyone else is social distracting you are productivity distracting, I love it! Haha, thanks! I'm always looking for more time to do the things I enjoy! AI generated Magic the Gathering cards are pretty amusing as well. Thanks for the interesting read. Oh cool, I'll have to look them up, I used to play a couple years back! Thanks for the suggestion 😊 Superb! My son loved this, and I'm feeling fired up to do some experiments! 🔥 🤖 🧠 🧙🏽♂️ Thanks @terkwood ! Glad to hear your son enjoyed the post 😁 One thing I didn't get into in this post is the temperaturevariable in textgenrnn, it allows you to generate between 'perfect grammar' and 'complete nonesense' – I was considering making a seperate post about it. Have fun playing around and get in touch if you'd like a hand 😊 🧙♂️
https://practicaldev-herokuapp-com.global.ssl.fastly.net/ryan_joseph/how-to-generate-harry-potter-spells-using-neural-networks-2bf6
CC-MAIN-2020-34
refinedweb
1,376
70.84
I need to randomly select a specific number of polygons from a feature class and create a new feature class with the randomly generated polygons. Is there a way to do this? Just ran into this same question, and ended up using the python random.sample function directly to create a subsequence of rows from the original search cursor, e.g. all_addresses = [row.getValue("FID") for row in arcpy.SearchCursor("survey_master_address_list_2018", fields="FID")] import random sample_set = random.sample(all_addresses, sample_size) I tried a few times to just use row objects directly and found that there were weird reference issues, so it works best to pull a list of FID values, sample those, and then you can loop back through the layer using an UpdateCursor and check for `row.FID in sample_set` to then perform operations on the sample. You may want to use Subset Features tool, provided you have Geostatisical Analyst extension. also, please look the following forum post: Hope this helps. Thank you.
https://community.esri.com/thread/49049-i-need-to-randomly-select-polygons-from-feature-class
CC-MAIN-2019-09
refinedweb
164
55.84
The community is working on translating this tutorial into Danish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info". If you are fluent in Danish, Danish video In the previous article, we used the MediaPlayer class to play an MP3 file, but the cool part about the MediaPlayer class is that it can work with video files as well. However, since a video actually needs to be displayed somewhere in the interface, as opposed to an audio file, we need a wrapper element to visually represent the MediaPlayer instance. This is where the MediaElement comes into play. The MediaElement The MediaElement acts as a wrapper around MediaPlayer, so that you can display video content at a given place in your application, and because of that, it can play both audio and video files, although the visual representation doesn't really matter in dealing with audio files. I want to show you just how easy you can show video content in your WPF application, so here's a bare minimum example: <Window x: <Grid> <MediaElement Source="" /> </Grid> </Window> And that's it - a single line of XAML inside your window and you're displaying video (this specific video is about the Hubble Space Telescope - more information can be found at this website) in your WPF application. Dealing with video size Our examples in this article so far has just used the same size for the MediaElement, not taking the dimensions of the video into consideration. This is possible because the MediaElement can stretch/shrink the content to fit the available width/height and will do so by default. This is caused by the Stretch property, which is set to Uniform by default, meaning that the video will be stretched, while respecting the aspect ratio. If your window is larger than your video, this might work just fine, but perhaps you don't want any stretching to occur? Or perhaps you want the window to adjust to fit your video's dimensions, instead of the other way around? The first thing you need to do is to turn off stretching by setting the Stretch property to None. This will ensure that the video is rendered in its natural size. Now if you want the window to adjust to that, it's actually quite simple - just use the ResizeToContent property on the Window to accomplish this. Here's a full example: <Window x: <Grid> <MediaElement Source="" Name="mePlayer" Stretch="None" /> </Grid> </Window> As you can see, despite the initial values of 500 for the Width and Height properties on the Window, the size is adjusted (down, in this case) to match the resolution of the video. Please notice that this might cause the window to have a size of zero (only the title bar and borders will be visible) during startup, while the video is loaded. To prevent this, you can set the MinWidth and MinHeight properties on the Window to something that suits your needs. Controlling the MediaElement/MediaPlayer As you can see if you run our previous examples, the video starts playing as soon as the player has buffered enough data, but you can change this behavior by using the LoadedBehavior property. We'll do that in the next example, where we'll also add a couple of buttons to control the playback: <Window x: <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <MediaElement Source="" LoadedBehavior="Manual" Name="mePlayer" /> <StackPanel Grid. > </Grid> </Window> using System; using System.Windows; using System.Windows.Threading; namespace WpfTutorialSamples.Audio_and_Video { public partial class MediaPlayerVideoControlSample : Window { public MediaPlayerVideoControlSample() { InitializeComponent(); DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += timer_Tick; timer.Start(); } void timer_Tick(object sender, EventArgs e) { if(mePlayer.Source != null) { if(mePlayer.NaturalDuration.HasTimeSpan) lblStatus.Content = String.Format("{0} / {1}", mePlayer.Position.ToString(@"mm\:ss"), mePlayer.NaturalDuration.TimeSpan.ToString(@"mm\:ss")); } else lblStatus.Content = "No file selected..."; } private void btnPlay_Click(object sender, RoutedEventArgs e) { mePlayer.Play(); } private void btnPause_Click(object sender, RoutedEventArgs e) { mePlayer.Pause(); } private void btnStop_Click(object sender, RoutedEventArgs e) { mePlayer.Stop(); } } } This example is much like the one we did in the previous article for audio, just for video in this case. We have a bottom area with a set of buttons for controlling the playback, a label for showing the status, and then a MediaElement control in the top area to show the actual video. Upon application start, we create and start a timer, which ticks every second. We use this event to update the status label, which will show the current progress as well as the entire length of the loaded file, as seen on the screenshot. The three buttons each simply call a corresponding method on the MediaElement control - Play(), Pause() and Stop(). Summary Once again it's clear how easy WPF makes even advanced things like playing a video. So far, we've worked with some basic examples, but in the next chapter, I'm going to combine all the stuff we've learned about audio and video playback into a single, media player with a lot more functionality than we've seen so far. Read on!
https://wpf-tutorial.com/da/100/audio-video/playing-video/
CC-MAIN-2020-34
refinedweb
870
51.38
Has anyone gotten info out of Ticket.users.full_name_or_email? I want my HTML tickets to show who is CC on the ticket. Reading from community.spiceworks.com/help/Ticket_Notifier_Template_Ref#Variables it said that: ticket.users - a list of users involved with this ticket (CC'ed users + Assignee + Creator). You'll need to iterate over these using {% for user in ticket.users%} ... {%endfor%}. - ticket.users.full_name - The full names of the users involved with the ticket, or empty if there is no full name (as is most often the case) - ticket.users.full_name_or_email - Output the full names if there are any, or the email addresses otherwise - ticket.users.email - The email addresses of the users involved with the ticket So I have this as part of my HTML template: Mailed : {% for user in ticket.users%} {{ticket.users.email | escape}} <br/> {%endfor%} But it doesn't work.. Feb 17, 2010 at 5:29 UTC Try this: Mailed : {% for user in ticket.users%} {{user.email | escape}} {%endfor%} 6 Replies Feb 17, 2010 at 5:29 UTC Try this: Mailed : {% for user in ticket.users%} {{user.email | escape}} {%endfor%} Feb 17, 2010 at 5:49 UTC That did it! Thanks! Feb 17, 2010 at 5:54 UTC Sure thing! The key is ticket.users -> user. Within that "for loop" you want to use user.xxxx instead of ticket.users.xxxx. Feb 17, 2010 at 6:26 UTC You should see the great lengths I went to to get this done (I added in CC'd users below the asignee and creator, but I had to test that the user wasn't either of those too) Perhaps I'll post my solution (ya never know, you might find it useful). It's also shown only to admins if I recall correctly. Feb 17, 2010 at 6:35 UTC Sure I'd like to see it. I'm not filtering the list, showing the Creator there is ok with me. Here is what I have for the Admin block now: {% if recipient.is_admin %} <div style="width:410px; padding:8px; border:1px solid #CCCCCC; background-color: #EFEFEF; font-size:11px;"> <h2 style="margin-bottom:5px; margin-top:0px; font-size:11px;">Ticket Overview</h2> Priority: {{ticket.priority | escape}}<br/> Creator : {{ticket.creator.full_name_or_email | escape}}<br/> Assignee: {{ticket.assignee.full_name_or_email | escape}}<br/> Dept : {{ticket.c_dept | escape}}<br/> Status : {{ticket.c_status | escape}}<br/> Mailed : {% for user in ticket.users%} {{user.email | escape}} {%endfor%} <br/> Ticket URL: <a href="{{ticket.url | escape}}">{{ticket.url | escape}}</a><br/> App: <a href="{{app_url | escape}}">{{app_url | escape}}</a><br/> <br/> Don't forget you can use Tickets Anywhere<br>Examples:<tt>#close, #add 5m, #assign to bob, #priority high</tt> </div> {% endif %} No if we can just get category to work. It's not pure custom so ticket.c_category won't work but ticket.category.{field} won't either. Feb 17, 2010 at 6:51 UTC This is what my admin section looks like: {% if recipient.is_admin %} <div style="padding:8px; border:1px solid #CCCCCC; background-color: #EFEFEF; font-size:11px; line-height:110%;"> <h2 style="margin-bottom:5px; margin-top:0px; font-size:11px;">Ticket Overview</h2> Priority: {{ticket.priority | escape}}<br/> Requested Priority: {{ticket.c_priority | escape}}<br/> Creator: {{ticket.creator.full_name_or_email | escape}}<br/> Assignee: {{ticket.assignee.full_name_or_email | escape}}<br/> {% for user in ticket.users%} {% if user != ticket.creator and user != ticket.assignee %} CC'd User: {{ user.full_name_or_email | escape }}<br/> {% endif %} {%endfor%} Ticket URL: {{ticket.url | escape}}<br/> App: {{app_url | escape}}<br/> <br/> Ticket Commands let you take control of your help desk remotely. Check the Spiceworks community for a full list of available commands and usage:<br/> http:/ <br/> Examples: <tt>#close, #accept, #created by user@formashape.com, #priority high</tt> </div> {% endif %}
https://community.spiceworks.com/topic/89205-ticket-users-in-html-email
CC-MAIN-2017-09
refinedweb
622
52.26
Difference between revisions of "XUL" Revision as of 11:23, 6 October 2006 Contents Description XUL which is pronounced zool stands for XML User Interface Language is a Mark-up language used primarily in Mozilla applications. XUL is used to define what the user interface will look like such as buttons and other widgets but it is not used to define how those item will. Currently, an application named XULRunner is being developed that will offer a runtime environment for XUL applications. Common Usages - Textboxes and inputs - Toolbars and buttons - Navigation menus - Tabbed windowing systems - Keyboard Mnemonics and input handling Supported Technologies - Sample Code <?xml version="1.0"?> <?xml-stylesheet <description>Is XUL cool or what?</description> <radiogroup> <radio id="yes" selected="true" label="Yes!"/> <radio id="no" label="No wai"/> </radiogroup> <button id="dpsbutton" label="DPS909 is fun" /> </window> Paste the above sample code inside your favourite editor and save it with a file extension of .XUL. Open the file in a Mozilla-based browser to view it. - Line 1: Declares that it is an XML file - Line 2: Used to reference the stylesheets. In this case, the global/skin chrome directories' default global.css file is used. global.css is used to declare all of the XUL elements. - Line 3: Describes a new window to be drawn, using the namespace. All children of this window are XUL. - Line 5: Description tag is like a label, but can wrap many lines. - Lines 6-9: Describes a radio button group. - Line 10: Draws a button. Example Applications - Mozilla Amazon Browser (MAB) - Rich web application that allows for searching of Amazon's content across their 6 websites (US, Canada, UK, Japan, Germany and France). Can be used through the web or downloaded to the desktop. - XUL Periodic Table - Demonstrates many of the visual capabilities of XUL. Newsgroups, Mailinglists, IRC Channels - mozilla.dev.tech.xul newsgroup (alternatively, use Google Groups) - dev-tech-xul mailinglist (manually use dev-tech-xul@lists.mozilla.org) - #xul on irc.mozilla.org
https://wiki.cdot.senecacollege.ca/w/index.php?title=XUL&diff=prev&oldid=4827&printable=yes
CC-MAIN-2021-39
refinedweb
335
58.08
I am running a bare metal embedded system with an ARM Cortex-M3 (STM32F205). When I try to use snprintf() with float numbers, e.g.: float f; f = 1.23; snprintf(s, 20, "%5.2f", f); I get garbage into s. The format seems to be honored, i.e. the garbage is a well-formed string with digits, decimal point, and two trailing digits. However, if I repeat the snprintf, the string may change between two calls. Floating point mathematics seems to work otherwise, and snprintf works with integers, e.g.: snprintf(s, 20, "%10d", 1234567); I use the newlib-nano implementation with the -u _printf_float linker switch. The compiler is arm-none-eabi-gcc. I do have a strong suspicion of memory allocation problems, as integers are printed without any hiccups, but floats act as if they got corrupted in the process. The printf family functions call malloc with floats, not with integers. The only piece of code not belonging to newlib I am using in this context is my _sbrk(), which is required by malloc. caddr_t _sbrk(int incr) { extern char _Heap_Begin; // Defined by the linker. extern char _Heap_Limit; // Defined by the linker. static char* current_heap_end; char* current_block_address; // first allocation if (current_heap_end == 0) current_heap_end = &_Heap_Begin; current_block_address = current_heap_end; // increment and align to 4-octet border incr = (incr + 3) & (~3); current_heap_end += incr; // Overflow? if (current_heap_end > &_Heap_Limit) { errno = ENOMEM; current_heap_end = current_block_address; return (caddr_t) - 1; } return (caddr_t)current_block_address; } As far as I have been able to track, this should work. It seems that no-one ever calls it with negative increments, but I guess that is due to the design of the newlib malloc. The only slightly odd thing is that the first call to _sbrk has a zero increment. (But this may be just malloc's curiosity about the starting address of the heap.) The stack should not collide with the heap, as there is around 60 KiB RAM for the two. The linker script may be insane, but at least the heap and stack addresses seem to be correct.
http://www.howtobuildsoftware.com/index.php/how-do/Q64/c-arm-embedded-printf-newlib-snprintf-prints-garbage-floats-with-newlib-nano
CC-MAIN-2017-09
refinedweb
339
65.73
“You’re going to learn quite a bit from Burt,” Burt said. “He’s one of the best.” Davide blinked. He wondered if his new boss spoke about himself in the third person as a matter of course. Cautiously, he said, “Well… I hope so?” “Burt’s been with us since the beginning,” Burt continued. “Nobody but nobody knows our systems and our environment better than he does. He’s one of those… whatchacallits…” Burt glanced around his desk, and found what he was looking for- a glossy trade-mag with a cover story about the most productive developers. “A Ten-X developer. We’re really lucky to have him, and you’re really lucky to work with him.” Burt was not speaking in the third person. Burt, the CTO of the company, was a huge fan of Burt, the lead developer at the company. When Davide was hired on, CTO-Burt spent a lot of time praising the genius of Dev-Burt. Once David started working, he didn’t see CTO-Burt very much, but Dev-Burt also was eager to talk about what a genius he was. “Not just anybody can manage a system with 100KLOC, mostly by themselves,” Dev-Burt said. “But stick with me, and maybe you’ll learn.” Dev-Burt’s genius was questionable. Five minutes skimming the code-base made it clear that Dev-Burt had the coding conventions of a drunken lemur. The only thing that made the code even slightly readable was that most of it was in Python, and thus had to be indented logically. That was the only logical thing about it. Some variables were named in camelCase, others in snake_case. Half of them were just alwayslowercase. Function names were generally more consistent, only because there were fewer of them: Dev-Burt was the kind of developer that just loved to write 5,000 line functions. There were plenty of global variables, plenty of spaghettified code, and plenty “god” objects that mashed together thirty unrelated behaviors into one mess that behaved differently depending on which specific flags you set. Dev-Burt was too busy being a 10x developer to give Davide any guidance about what he was supposed to do. The only coding conventions appeared to be “Dev-Burt does whatever Dev-Burt wants.” From time to time, Davide would pick up tickets as they came through, tracking down and patching bugs, but mostly he tried to find opportunities to refactor the code and add some unit tests. This radical behavior lead to a tense meeting with the Burts. “Burt tells me you’re causing problems,” CTO-Burt said. “He’s making a mess out of my code,” Dev-Burt complained. “He’s making it more complicated!” “I was just refactoring it so-” “There he goes,” Dev-Burt said, throwing a hand in the air, “using his made up buzzwords. Look, we’ve got product to ship, and your refractioning isn’t getting us anywhere. I wouldn’t mind so much, but it’s eating into my own time, and making it harder for me to get work done!” “That’s bad,” CTO-Burt chimed in. “Because Burt’s a Ten-X developer. His time’s ten more times as valuable as yours.” At least, after the meeting, Davide had clear rules to follow: Dev-Burt does whatever he wants, Davide does whatever Dev-Burt tells him to, and Davide was not to touch any code unless it was to deal with a ticket assigned to him by CTO-Burt. This gave Davide a lot of downtime, during which he could watch the codebase grow. It was true, Dev-Burt was a 10x developer, in the sense that he could write ten times as much code as necessary and he’d often write the same code ten times, in different places in the application. One day, while wondering if this made Dev-Burt the first 100x developer, Davide received a new ticket. One of the automated jobs had failed, dumping a stack trace to the log, and it kept failing every hour. It didn’t seem to be having any other effects, but CTO-Burt wanted it fixed. Davide assumed there was an un-handled error, and dug through the stack trace to find the offending code. He was half right. Once he cut away the bulk of the logic, the basic structure of the method was this: def manage_expectations(*args,**kwargs): try: #about 1,200 lines of code except Exception, e: raise e So, Dev-Burt had handled the exception… by re-throwing it. A few hours picking apart the function, and it was clear that the underlying problem was a FileNotFoundError when scanning a logfile for messages- there was no guarantee that the logfile would exist. It was easy enough to make the code fail gracefully when it encountered the exception, but that might be considered “refractioning”, and so Davide needed to ask Dev-Burt for permission first. “Hey, Burt,” Davide asked, “can you pull up some code for me?” He pointed to the raise e and said, “Why are you doing that? Why is that there?” Dev-Burt nodded, stroking his chin thoughtfully. “That’s an exception handler,” he said. “Yes, I know that. Why is that raise there?” “Hmm… I guess I’m not sure. What does the raise command do?” Davide went back to his desk, fixed the exception handler, and then started sending out resumes. He’d learned everything he needed to from Dev-Burt, and was now ready to fail gracefully out of this job.
http://thedailywtf.com/articles/the-10x-developer
CC-MAIN-2017-34
refinedweb
932
73.07
I need to convert B to a 1-D array I have a matrix which I am trying to turn to a 1-D array. However I am getting an array with 1 cell which holds the 1-D array. How do I fix it ? Python CODE: import numpy as np def computecoreset(): a = np.matrix('1 2 19 22; 3 4 28 11') B = a.ravel() cal = np.random.choice(B, 3) return cal print(computecoreset()) B = [[ 1 2 19 22 3 4 28 11]] [ 1 2 19 22 3 4 28 11] a.ravel() being a method of NumPy matrix would still keep it as a matrix and NumPy matrices can't be 1D. So, instead we can use NumPy's ravel() method to convert into a flattened 1D NumPy array, like so - np.ravel(a) Sample run - In [40]: a Out[40]: matrix([[ 1, 2, 19, 22], [ 3, 4, 28, 11]]) In [41]: np.ravel(a) Out[41]: array([ 1, 2, 19, 22, 3, 4, 28, 11])
https://codedump.io/share/dqtMVujM4SYK/1/python-from-matrix-to-1-d-array
CC-MAIN-2017-09
refinedweb
170
82.95
Introduction to the Rule Editor This chapter introduces the Rule Editor in the Management Portal. It is divided into the following sections: Business Rule List The Interoperability > List > Business Rules page displays a list of the business rule classes defined in the active interoperability-enabled namespace. Navigate to this page from the Business Rules item of the InterSystems IRIS® List menu. Select a rule class to be the target of one of the following commands in the ribbon bar: Edit — Click to change or view the rule definition using the Business Rule Editor. Delete — Click to permanently delete the rule definition class. Export — Click to export the selected rule class as an XML file. Import — Click to import an XML file into a rule class. You can also export and import rule classes as you do any other class in InterSystems IRIS. You can use the System Explorer > Globals page of the Management Portal or use the Export and Import commands on the Tools menu in Studio. Business Rule Editor The Interoperability > Build > Business Rules page page is where you create and edit business rule class definitions for all types of business rule. The page opens with the last rule you had open in the namespace. The tab at the left of the title bar contains the name of the business rule definition class. If this is the first time on the page for this namespace, the working pane is empty and you must either create a new rule or open an existing one. The “Creating and Editing Rule Sets” chapter describes the details of how to use the editor to define business and routing rules; the rest of this chapter describes how the user interface works with the rule structure. The ribbon bar of the Rule Editor page contains the following elements: New button — Click to launch the Business Rule Wizard to create a new business rule definition. Open button — Click to launch the Finder Dialog to choose an existing business rule definition to edit. Save button — Click to save and compile any changes you have made to the rule definition. Save As button — Click if you have been editing a rule definition and wish to save your changes as a new business rule class. Contract — Click to contracts the display of all of the rules in the rule set. You can then individually expand the rule you want to view or edit. Expand — Click to expand the display of all of the rules in the rule set. Open new windows check box — If checked, the New and Open commands open the rule editor in a new window or browser tab. Zoom drop-down—Specifies the zoom percentage to view the rule. Once you have a rule definition in the working pane you see tabs of information. The general tab contains the summary information for the rule definition: Class description of the rule definition and its purpose. Each rule type has an associated rule assist class which controls the constraints of the rule and provides information in the right pane of the page to guide you when editing rules. The table shows the four rule types and their associated Ens.Rule.Assist Opens in a new window class: The class that contains the information to tell the Rule Editor which object properties to provide as choices in the Value editor while you are editing a rule. For general rules, it is generated from the business process BPL class and ends in .Context. For routing rules without a BPL process, it is usually the routing engine business process class. Deprecated. Do not use. You can specify temporary variables in this field. You can use these temporary variables in the business rule. Each variable specification is separated by commas. For example: FreeShippingValue,ShipMethod,PremierMember Temporary variables are used in a rule by preceding the variable name with an @ (at sign). For example, @FreeShippingValue. Temporary variables are available only within the rule. If you want to pass information to the transformation using the rule, use the RuleUserData property. See “Selecting the Transformation and Target of a Send Action” for details. (Only for routing rules) This optional, informational setting makes it easier for you to define rules because the rule editor uses this setting to select configuration items to display when you are defining rules. The production configuration actually specifies that a rule is used for a production. List of Rule Sets with the following information: Rule Set Name —Name to identify the particular set. Beginning Date and Time — The time from which the rule becomes active. The exact time is included in the active interval. The format is YYYY-MM-DDTHH:MM:SS. The time portion is optional and defaults to 00:00:00. Ending Date and Time — The time when the rule stops being active. The exact time is excluded from the active interval. The format is YYYY-MM-DDTHH:MM:SS. The time portion is optional and defaults to 24:00:00 Each rule set has its own tab for editing its list of rules. For details, see the “Creating and Editing Rule Sets” chapter. Both tabs contain following set of icons. The following icons are available to edit the rule definition, rule sets, rules, and clauses within a rule set: The specific action may differ depending on the entity you are editing; the following table describes the action of each icon in general. If an action is not available, its icon appears dimmed. You can hide or show the Rule Assistant using the double-arrow in the right pane of the Rule Editor. When you are editing a rule set, the expanded Rule Assistant pane provides you with help throughout the editing process. It describes the item you have selected and provides a list of options based on your assist class. Business Rule Wizard This wizard helps you create a new business rule definition based on the Ens.Rule.Definition Opens in a new window class with an XData block named RuleDefinition. Enter values for the following fields: Enter a package name or use the arrow to select an existing package name. Enter the name of the business rule class. (Optional) Enter the alias name for this rule. Do not use any of the following characters: ; , : | ! * - $ ‘ “ < > & Deprecated. Do not use. (Optional) Enter a description for this rule definition. This becomes the class description. Enter one of four rule types: General Business Rule General Message Routing Rule Virtual Document Message Routing Rule Each rule type has an associated rule assist class which provides information in the right pane of the page to guide you in entering rules and controls which options the editor presents. (Optional) This field tells the Rule Editor which object properties to provide as choices in the Value field when you are editing a rule. For general rules, this class is generated from the BPL business process class that invokes the <rule>. The naming convention of the class is the business process class name plus the .Context extension.
https://docs.intersystems.com/healthconnectlatest/csp/docbook/DocBook.UI.Page.cls?KEY=EBUS_RULES
CC-MAIN-2021-25
refinedweb
1,171
63.29
Based on IRC logs for 31 July, 1 August Present: Asir Vedamuthu, WebMethods Yves Lafon, W3C Martin Gudgin, Microsoft Colleen Evans, Progress (scribe, p.m.) Carine Bournez, W3C Noah Mendelsohn, IBM David Fallside, IBM (chair) Volker Wiechers, SAP Anish Karmarkar, Oracle (scribe, a.m.) Herve Ruellan, Canon Gerd Hoelzing, SAP Ryuji Inoue, Matsushita Kazunori Iwasa, Fujitsu Mark Jones, ATT Present by Phone (Partial): Mark Baker, Idokorro Glen Daniels, Macromedia Excused: Camilo Arbelaez, webMethods John Ibbotson, IBM Henrik Nielsen, Microsoft Jeff Mischkinsky, Oracle Jean-Jacques Moreau, CanonResearchCentreFrance Paul Cotton, Microsoft Michah Lerner, ATT Masahiko Narita, Fujitsu Regrets: Highland Mountain, Intel Pete Wenzel, SeeBeyond David Orchard, BEASystems Paul Denning, MITRE Oisin Hurley, IONA [Mark Baker, IdokorroMobile, Inc.] Stuart Williams, Hewlett-PackardLabs Marc Hadley, SunMicrosystems Amr Yassin, Philips Jacek Kopecky, Systinet Nilo Mitra, Ericsson [Glen Daniels, Macromedia] Murali Janakiraman, RogueWaveSoftware Don Mullen, TIBCOExtensibility Michael Champion, SoftwareAG Yin-Leng Husband, Hewlett-Packard Bob Lojek, Intalio Ray Whitmer, Netscape Absent: Jin Yu, MArtsoft Mario Jeckle, Daimler Chrysler Andreas Riegg, Daimler Chrysler Brad Lund, Intel Eric Newcomer, IONA Simeon Simeonov, Macromedia Marwan Sabbouh, MITRE Vidur Apparao, Netscape Yasser alSafadi, Philips Patrick Thompson, Rogue Wave Dietmar Gaertner, Software AG Miroslav Simek, Systinet Frank DeRose, TIBCO Lynne Thompson, Unisys Nick Smilonich, Unisys [RRSAgent] RRSAgent has joined #xmlprotocol [GlenD] hi :) and hokey dokey [Yves] zakim, this is xmlp [Zakim] sorry, Yves, I do not see a conference named 'xmlp' [Yves] zakim, this will be xmlp [Zakim] ok, Yves [GlenD] silly time restricted conferences [Yves] yep :/ [GlenD] My apologies, btw, I haven't had time to finish wording on #219 yet. Looking at it now. [GlenD] The problem of course is defining what a module actually is.... [DavidF2F] DavidF2F has joined #xmlprotocol [Mark_J] Mark_J has joined #xmlprotocol [GlenD] How about: [GlenD] "The term "SOAP Module" refers to the set of syntax and semantics associated with implementing a particular piece of functionality as SOAP headers, generally described in a Module Specification. [GlenD] (perhaps insert "and is" before "generally described") [herve] herve has joined #xmlprotocol [scribemjg] scribemjg has joined #xmlprotocol [carine] "piece of functionality" has been removed from text (issue 211) [carine] not sure it's a good idea to introduce it somewhere else [GlenD] hm [GlenD] ...associated with implementing a particular extension of the SOAP messaging framework...? [GlenD] yuk [anish_ca] anish_ca has joined #xmlprotocol [GlenD] I hope we say somewhere what "an extension of the SOAP messaging framework" means.... [GlenD] I guess we do in 3.1 [carine] it's a SOAP feature :) [GlenD] yup [GlenD] The thing I'm trying to avoid is the necessity of a Module writer to come up with a separate URI for a Feature which the Module implements in order to write the spec. [carine] wht not using "implementing a particular SOAP feature? [reagleHOM] reagleHOM has joined #xmlprotocol [reagleHOM] howdy [asir] asir has joined #xmlprotocol [reagleHOM] Yves, what was the URI to the issue again? [Gudge] Hi Joseph [GlenD] While one common pattern is going to be two specs - an abstract Feature spec and a concrete Module spec which implements that Feature - I don't think that's necessary. [colleen] colleen has joined #xmlprotocol [Yves] joseph: [Yves] would you be around in the next hour or two? [Zakim] WS_XMLP(f2f)12:00PM has now started [noah] noah has joined #XMLProtocol [Zakim] +G_Daniels [Zakim] + +1.650.849.aaaa [Yves] zakim, code XMLPF [Zakim] I don't understand 'code XMLPF', Yves. Try /msg Zakim help [Gudge] zakin, aaaa is F2FRoom [reagleHOM] Yves, I'm sort of around... plan on lunch soon, what are you proposing? Do you have a call coming up? [Gudge] zakim, aaaa is F2FRoom [Zakim] +F2FRoom; got it [Yves] we plan to tackle Glen's issue first [Yves] if yuo're around after lunch, it would be nice [GlenD] brb! (2 min) [GlenD] back [GlenD] it's a bit static-y, some people come through better than others [scribe_ak] Noah presents the changes to the AF doc [scribe_ak] Noah: key features - purpose it to allow someone to create bindings and not features [scribe_ak] Noah: changes made to terminology section: "secondary parts are also referred to as attachments" [herve] Noah's edited version is at: [scribe_ak] Mark_J: do we define part at this point in the doc? [scribe_ak] Mark_J: does 'data stream' to skirt calling it encapsulation? Or what is the sum and substance of everything that travel together? [scribe_ak] Noah: [scribe_ak] more discussion about 'data stream' between Mark and Noah.... [scribe_ak] DF: Suggestion - this doc should be published as WD. We should then take this WD to LC WD. [scribe_ak] Noah: Glen found typos in the abstract which were fixed. [scribe_ak] Asir: issue about consistent use of the word 'Message' [scribe_ak] Noah: I found the following sentence baffling in section 6: "Note that in some cases, an encapsulation mechanism may also provide the functionality of the underlying protocol, but this is not a requirement. [scribe_ak] Mark: suggested change - Note that in some cases, the underlying protocol may also provide the functionality of the encapsulation mechanism [scribe_ak] DF: To wrap up - couple of more ed. changes. We pretty much agreed to Noah's changes. [scribe_ak] Asir: Last sentence in section 3 - it might be easier to replace it with "informally secondary parts are referred to as attachments" [scribe_ak] Asir: removing the "also" would be useful as well. [scribe_ak] DF: is 'data stream' ok? [noah] noah has joined #XMLProtocol [scribe_ak] DF: suggestion - get all the changes that we discussed, incorporate those in another version tonight. Tomorrow we will make a decision to publish the doc as a WD. We also send an email to the member ML that we are going to do this. [scribe_ak] DF: if we get a 'yes' for publishing the WD, then Herve please work with Yves to get it published as a WD [noah] zakim, who is here? [Zakim] On the phone I see F2FRoom, G_Daniels [Zakim] On IRC I see noah, colleen, asir, reagleHOM, scribe_ak, Gudge, herve, Mark_J, DavidF2F, RRSAgent, Zakim, GlenD, HFN_away, MarkB, carine, Loggy, Yves [GlenD] "The term "SOAP Module" refers to the set of syntax and semantics associated with implementing a particular piece of functionality as SOAP headers, generally described in a Module Specification. [scribe_ak] discussion on issue 219.... [Yves] attendance: [noah] Did we minute the possible concern that the SOAP Rec itself is inconsistent in the definition of the word message? [scribe_ak] issue 219 - [Yves] Colleen Evans, [Yves] Mark Jones, Anish Karmarkar, Kazunori Iwasa, Ryuji Inoue, Noah Mendelsohn [scribe_ak] scribe - Noah, the concern was noted only for the AF doc, but it should be noted for the SOAP spec itself as well [Yves] Asir Vedamuthu, Gerd Hoelzing, Herve Ruellan, Volker Wiechers [Yves] Carine Bournez, Yves Lafon, Marting Gudgin, David Fallside [Yves] GLend Daniels (remotely) [Yves] s/nd/n/ [scribe_ak] Glen: Modules are about headers. [scribe_ak] Noah: I agree with Glen. We talk about features and talk about Modules are being embodiment of features. [scribe_ak] Noah: clearly an intermediary can do things that are not defined in the header, but it is not in the architecture. [scribe_ak] Noah: Is it a weakness of our arch., but independent of modules. [scribe_ak] Mark: not ever module inserts a header (could consume one) [GlenD] +q [GlenD] q+ [scribe_ak] Glen: another comment - another example is that an intermediary at the boundary of an enterprize, and can restrict what headers are allowed. [scribe_ak] Glen: we don't want to say anything about it. [scribe_ak] Mark: It seems strange not to say anything about it. We should at least ack. that such a thing may exist [scribe_ak] Glen: I don't have a problem 'ack'ing such a scenario. [scribe_ak] DF: Glen when will we see the text? [scribe_ak] Glen: a few minutes. [Zakim] +Reagle [anish_ak] I won't be able to make it to the impl. con call at 10 [anish_ak] nick scribe_ak [Yves] [Zakim] -G_Daniels [scribe_ak] JosephR explains issue 241.... [scribe_ak] JosephR: problems - default namespace, xml:base when inserting/deleting fragments. [scribe_ak] Noah: My question is what is SOAP's responsibility in dealing with this. SOAP is a wire format. [scribe_ak] Noah: An intermediary can remove a header, but all it's children are removed as well. [scribe_ak] Noah: one exception is that SOAP allows one to do some things such as signing - an intermediary can take in a soap message and encrypt/sign specific parts. So designer of such intermediary would be well adviced to take your concerns into account. [scribe_ak] JosephR: I can accept the arg that this is out of scope for SOAP to specify, but some verbage/warning about these issue would not hurt. [reagleHOM] [reagleHOM] [scribe_ak] DF: our mission was to allow people to build additional features. The general concern is that we don't want our document to contain warnings for all possible scenarios. Is this a fundamental issue? [scribe_ak] JosephR: I understand your argument, but I think it is important to a lot of applications. [JacekK] JacekK has joined #xmlprotocol [Zakim] -Reagle [scribe_ak] DF: we will take it under advisement and we will provide you with a response. We think that we do understand your concern [noah] I think we should note that Joseph's concern center on constructs such as default namespaces, xml base, etc. and warnings that may be needed when inserting/deleting parts of the document [noah] zakim, who is here? [Zakim] On the phone I see F2FRoom [Zakim] On IRC I see JacekK, noah, colleen, reagleHOM, scribe_ak, herve, Mark_J, DavidF2F, RRSAgent, Zakim, GlenD, HFN_away, MarkB, carine, Loggy, Yves [scribe_ak] Scribe: Noah - that concern has been noted in IRC. [scribe_ak] discussion of what to do with issue 241.... [scribe_ak] issue about should prefixes be made part of our infoset.... [noah] Right, the prefix issue is the one that Gudge and I have been asked to discuss, and that the WG will bring up when David puts it on the agenda [scribe_ak] DF: proposal - we maintain status quo and do not make any changes to the spec. [scribe_ak] Colleen: should we put this in the primer? [reagleHOM] reagleHOM has left #xmlprotocol [scribe_ak] Mark: do we have an example in the primer where a header gets padded in the primer? [scribe_ak] DF: Any object to closing 241 by doing nothing? [scribe_ak] s/object/objection [scribe_ak] no objection [scribe_ak] Action: Carine to send email to xlmpcomment and cc Joseph wrt issue 241 [Yves] ACTION: Carine to send email to xlmpcomment and cc Joseph wrt ssue 241 [scribe_ak] ===== beak until 10:45 PDT ===== [scribe_ak] DF: please look at Glen's text during the break. [scribe_ak] zakim, who is on the phone [Zakim] I don't understand 'who is on the phone', scribe_ak. Try /msg Zakim help [scribe_ak] zakim, who is on the phone? [Zakim] On the phone I see F2FRoom [DaveO] DaveO has joined #xmlprotocol [scribe_ak] === break is over, we are back === [scribe_ak] ==== Issue 263 ==== [scribe_ak] DF: since Gudge is not here, lets postpone 263 till he is back [scribe_ak] DF: I have the response for P3P's comments [scribe_ak] response at [scribe_ak] agreement on the text - modulo typos [scribe_ak] ==== Issue 266 ==== [Yves] [scribe_ak] DF: one option is to go back and allow mixed content in the encoding and the other option is to say that this is optional and not meant to do everything. [scribe_ak] MarkJ: programming languages were the driving force for soap data model. [asir] asir has joined #xmlprotocol [scribe_ak] Asir: Mixed content is a XML concept and I don't see why we should put this in soap datamodel [Gudge] Gudge has joined #xmlprotocol [scribe_ak] Noah: we should not be too insensitive to this concern. I don't know how much of a problem this is. [scribe_ak] Noah: This might be a problem with Ruby. [scribe_ak] Gudge: I am concerned as to what the graph will look like with mixed content [scribe_ak] Noah: This might be a bigger problem, i.e, they may want attributes which soap encoding disallows. [scribe_ak] MarkJ: I don't see why soap datamodel should be applicable for all possible cases [noah] [scribe_ak] Asir: Why is Ruby is concern? [scribe_ak] Gudge: Ruby allows one to annotate text/sub-part/sentence [scribe_ak] MarkJ: Ruby can be mapped to something like a "struct" [scribe_ak] general discussion about Ruby and soap encoding [scribe_ak] Noah: Is Ruby the right example? [scribe_ak] Gudge: Ruby has attributes that we don't allow [scribe_ak] Gudge: we can come up with work arounds/mappings, but I18N may want mixed content as a first class citizen [scribe_ak] Noah: concern - how much of a restriction is this? [scribe_ak] DF: 2 options - we go back to I18N and say we created soap encoding which is limited and we are going to stick with it. It is not a generalized scheme. Other option is to go back to I18N and have more discussion/negotiation and make sure that we got this right and understand if it is a 'lie-in-the-middle-of-the-road' issue. [scribe_ak] Gerd: We could say that this is not a part of our requirements. Is it part of our charter? [scribe_ak] DF: reads the relevant part of the charter [scribe_ak] Noah: we could say something like - this is legitimate concern, but this has been implemented by plenty of implementations and such changes cannot be handled by these implementation. Further more, SOAP is designed to carry pretty much anything. [Zakim] +G_Daniels [scribe_ak] MarkJ: we could move this requirement to the next version. [scribe_ak] DF: Proposal - we close this issue by doing nothing and we write a carefully worded response to I18N. [scribe_ak] DF: the response would contain something like - we have a specialized target for the encoding and the implementations that exist in that environment. [scribe_ak] DF: we should also include the fact that soap encoding is optional and other encodings are possible. [scribe_ak] no objection from the WG [scribe_ak] DF: issue 266 is closed [scribe_ak] ACTION: DavidF to draft a response for issue 266 and bring it back to the WG [scribe_ak] ==== Issue 267 ==== [scribe_ak] s/267/268 [herve] herve has joined #xmlprotocol [scribe_ak] MarkJ: in this case, there is no recourse [scribe_ak] DF: does Ruby apply here again? [scribe_ak] Herve: in our spec inbound messages and outbound messages are not typed [scribe_ak] DF: why do we say property values are simple types? [scribe_ak] Noah: IMO this is a bug [scribe_ak] Gudge: the reason for using QNames is so that they are unique [scribe_ak] Noah: the reason for using types was so that we do not reinvent the wheel [scribe_ak] Gudge: Why don't we say "where appropriate properties should have a xml simple type" [scribe_ak] Glen: why should it be simple? [scribe_ak] Gudge: ok. remove 'simple' [Gudge] Proposal: Change second bullet to read 'Where appropriate properties should have an XML Schema type' [DavidF2F] DavidF2F has joined #xmlprotocol [Gudge] Proposal: And update our property tables to include a Type column [Gudge] Proposal: Change second bullet to read 'Where appropriate properties should have an XML Schema type' [Gudge] Proposal: Change second bullet of Part 2 5.1.1 to read 'Where appropriate properties should have an XML Schema type' [Gudge] Proposal: And update our property tables to include a Type column [scribe_ak] DF: any discussion on the proposal? [colleen] colleen has joined #xmlprotocol [Mark_J] Mark_J has joined #xmlprotocol [scribe_ak] DF: proposal is to change the spec to what is in IRC and close issue 266 by saying that we do not limit property types to xml schema simple types. [scribe_ak] DF: any objections? [scribe_ak] DF: issue 268 is closed. [scribe_ak] ACTION: Gudge to send a response for issue 268 [scribe_ak] ACTION: editors to make the changes proposed for resolving issue 268 [scribe_ak] ==== Issue 257 ==== [scribe_ak] DF: Nilo is going to fix all the ed. issue. For issue that lie in the grey area, he will bring it back to the WG with suggestions. [scribe_ak] DF: issue 257 is such a issue, so we will not deal with it right now. [scribe_ak] DF: issue 259 is also editorial [scribe_ak] ==== Issue 267 ==== [scribe_ak] ACTION: editors to resolve issue 267 with ed. changed [scribe_ak] ==== Issue 269 ==== [scribe_ak] DF: suggestion - someone send an email to Martin to get a clarification as to what issue 269 exactly is [scribe_ak] ACTION: Noah to send an email to Martin and get a clarification on issue 269 and 'cc' distapp [scribe_ak] ==== Issue 270 ==== [asir] asir has joined #xmlprotocol [asir] [scribe_ak] Asir: the last 2 subissues in 270 are not covered in the URL that I posted to IRC [Glen-brb] You guys are lunching 12:30-1:30PDT? [scribe_ak] Asir: 2nd last subissue is editorial [scribe_ak] Asir: the last subissue is also editorial [Yves] glen: that's the original plan, we will soon know if the plan will be applied ;) [scribe_ak] ACTION: editors to take on the last 2 items in issue 270 [scribe_ak] ACTION: editors to use the URL posted by Asir in IRC as the starting point for the editorial changes to appendix A (issue 270) [scribe_ak] ==== Issue 263 ==== [scribe_ak] Noah: if we want to support prefixes then we will have to scan the complete spec [scribe_ak] Gudge: We only need to only support namespace decl. [scribe_ak] Gudge: we don't need to say anything about prefixes except xml [scribe_ak] discussion between Noah and Gudge about preserving prefixes.... [asir] - No other prefix may be bound to this namespace name - applies to XML 1.0 [scribe_yl] gudge: answering 263 can be only "prefix of lang must be xml:" [scribe_yl] markJ: what is the problem in saying that intermediaries should rpeserve the prefix? [scribe_yl] gudge: we will have to care with default declaration namespaces [scribe_yl] asir: return value in rpc struct needs prefix [MGudgin] MGudgin has joined #xmlprotocol [scribe_yl] noah: are the prefixes signed in dsig? [scribe_yl] option 1 : intermediaries preserv prefixes [scribe_yl] option 2 : prefixes are not significant, so no need say what to do with them [scribe_yl] straw poll: preservation 3 [scribe_yl] straw poll: non-significant 4 [scribe_yl] couldn't live with 1: 0 [Gudge] Gudge has joined #xmlprotocol [scribe_yl] couldn't live with 2: 0.5 [scribe_yl] decision: go with "preserve" option [scribe_yl] resolution B is above [scribe_yl] resolution A is acnkowledge prefix existence in infoset [scribe_yl] resolution C prefix of lang must be xml: per namespaces in XML errata #5 [scribe_yl] the resolution of part2 is reason with multiple text elements with different xml:lang [scribe_yl] part 4: conneg is out of scope for us [scribe_yl] 2 solves the problem of xml:lang optional [scribe_yl] 263 is closed with the proposed resolution [scribe_yl] ACTION: Inoue san to send resolution text to xmlp-comments (Cc: martin) to close issue 263 [scribe_yl] ====break for lunch====== [Zakim] -G_Daniels [MarkB] what time does work resume? [GlenD] GlenD has joined #xmlprotocol [DavidF2F] DavidF2F has joined #xmlprotocol [DavidF2F] resuming in a couple of minutes [Zakim] +GlenD [DavidF2F] DavidF2F has joined #xmlprotocol [DavidF2F] zakim, who is here? [Zakim] On the phone I see F2FRoom, GlenD [Zakim] On IRC I see DavidF2F, GlenD, Gudge, RRSAgent, Zakim, HFN_away, MarkB, carine, Loggy, scribe_yl [colleen] colleen has joined #xmlprotocol [Zakim] +MarkB [herve] herve has joined #xmlprotocol [scribe_ce] === back from lunch == [scribe_ce] ==== issue 219 ==== [DavidF2F] [Gudge] zakim, who's talking? [Zakim] Gudge, listening for 14 seconds I heard sound from the following: GlenD (82%), F2FRoom (20%) [DavidF2F] [scribe_ce] considering Glen's proposed resolution text at above URL [scribe_ce] Two parts. Discussion on first part re wording in 3.1 regarding modules. [scribe_ce] DF: would people be happy with these two proposed changes? [scribe_ce] Glen: concern regarding interpretation that two URIs or two complete specs required [asir] asir has joined #xmlprotocol [scribe_ce] VW: Should SOAP headers be SOAP header blocks in proposed text? [scribe_ce] follow on email from Glen at [scribe_ce] DF: close 219 with three proposed text changes proposed in Glen's email 163 [scribe_ce] no objection [scribe_ce] ACTION: Glen to send closing text on issue 219 [scribe_ce] ACTION: editors to incorporate the text for issue 219 [scribe_ce] ==== issue 230 ==== [scribe_ce] Glen: proposal to add line stating a feature has to have a URI [scribe_ce] Glen: applicable section is 3.1.1 [scribe_ce] DF: proposal to take enumerated first bullet out of 3.2 and copy into enumerated list in 3.1.1 changing module to feature and possibly some other gramatical changes to make it fit. [scribe_ce] DF: any objection to closing issue 230 with that resolution? [scribe_ce] no objection [scribe_ce] ACTION: Glen to send resolution text to xmlp comment for 230 [scribe_ce] ACTION: editors to incorporate text changes for 230 [asir] asir has joined #xmlprotocol [scribe_ce] == WS Arch comments == [scribe_ce] === issue 329 === [DavidF2F] [Gudge] [scribe_ce] Noah: posted email with response to this issue [scribe_ce] DF: Is there a clarification that would be useful to add to the processing model? [Gudge] Section 2.6: [Gudge] Bullet 3: If one or more of the body MUST NOT be generated in this step. [Gudge] mustunderstand faults are at [Gudge] <env:Header> [Gudge] <flt:Misunderstood [Gudge] <flt:Misunderstood [Gudge] </env:Header> [noah] noah has joined #XMLProtocol [scribe_ce] MarkJ: so we allow it, we don't prescribe it [scribe_ce] Noah: it's working as designed - only question is whether there's anything editorial to do. [scribe_ce] DF: Propose resolution to issue is to point to Noah's email, endorsing it. [scribe_ce] no objection [scribe_ce] ACTON: Volker will send closing email for issue 329 referencing first part of Noah's email. [Mark_J] Mark_J has joined #xmlprotocol [scribe_ce] ==== Issue 330 ==== [Yves] ACTION: Volker will send closing email for issue 329 referencingfirst part of Noah's email. [Yves] ACTION 14= Volker will send closing email for issue 329 referencing first part of Noah's email. [scribe_ce] Noah: this particular layering of the approach is intentionally there rather than by oversight - discussed at length in the WG a year or so ago [scribe_ce] DF: proposal to respond to issue 330 saying we are closing without action. Reference the second part of Noah's xmlp comment email above. Add statement that design is explicit following discussion on concept 'mustHappen'. [scribe_ce] DF: mustHappen mechanism could be embodied in a header which would work along side the existing mU mechanism in the spec. [scribe_ce] no objections [scribe_ce] ACTION: Volker will send email to xml comments closing issue 330. [scribe_ce] ==== Issue 331 ==== [scribe_ce] Glen: we can pull out related text in 3.3 since it will be covered in the features [Zakim] -MarkB [scribe_ce] MarkJ: should 'in general' be deleted [scribe_ce] agreed [scribe_ce] Noah: take out URI bullet as it will be covered in features (make MUST under feature) [scribe_ce] MarkJ and Noah: redundantly do it here too [scribe_ce] Noah: an MEP as a feature must follow all the rules of the features (for example, must be named by a URI)... [scribe_ce] Noah: delete first bullet in section 3.3, remove 'in general'. [scribe_ce] ACTION: Editors clarify that specifications for MEPs inherit requirements for features. [scribe_ce] ACTION 16 = Editors clarify that specifications for MEPs inherit requirements for features. Also note text in 3.1.1 sub 4. [scribe_ce] DF: propose to close 331 by stating that per clarification of the spec and our resolution to issue 230, we now state that MEPs are identified by URIs [scribe_ce] no objections [scribe_ce] ACTION: Gerd will send note to xmlp comment and cc mike champion to close 321 [scribe_ce] ==== issue 332 ==== [scribe_ce] Gudge: we discussed, it's application defined [scribe_ce] Noah: we have work on attachments that could apply here...point out we're actively working on something in this space. [scribe_ce] DF: proposal we close by responding that where external references are to attachments we actvely have work ongoing. [scribe_ce] no objections [scribe_ce] ACTION: Colleen will send note to xmlp comment closing issue 332 [scribe_ce] MarkJ: do these responses go to WS-A as a whole or to individuals? [scribe_ce] DF: Just copy Mike Champion and he can gateway the WS-A mailing list. [scribe_ce] ==== issue 333 ==== [scribe_ce] Noah: appears what they object to where we QNames as content, e.g. fault code declared as a QName in section 5.4.6. Just capitulate and make them URIs. [scribe_ce] Gudge: the TAG finding referenced in the email seems fine. Accepts it is reasonable to use QNames in a string. [scribe_ce] MarkJ: does it make other things we've done (e.g., None) more consistent if we use URIs? [scribe_ce] DF: proposal is to close issue 333 by taking no action - maintain status quo. [scribe_ce] no objections [scribe_ce] ACTION: Colleen will send email to xmlp comments cc Mike Champion closing issue 333, referencing draft tag findings that it's okay to use QNames in this way. [Gudge] Tag finding conclusion is at [scribe_ce] ==== issue 336 ==== [carine] it's related to issue 358 [scribe_ce] Yves: Not just a SOAP context. Many implementations of proxies have this issue. [scribe_ce] MarkJ: is the issue that it should handle URIs of arbitrary lengths (rather than 2048 chars)? [scribe_ce] Yves: this indication is in the context of deployment of HTTP software. [scribe_ce] DF: encouraged to handle URIs of arbitrary length SHOULD in any case be able to deal with URIs 2048 chars in length. [scribe_ce] DF: proposal that we close 336 without changing our spec and we believe that the spec in its current form provides the appropriate motivation for handling arbitrary length URIs [scribe_ce] no objection [scribe_ce] ACTION: MarkJ to send email to xmlp comment and cc Mike Champion closing issue 336. [Zakim] -GlenD [GlenD] Good luck with the rest of the day, folks [Mark_J] Mark_J has joined #xmlprotocol [DavidF2F] DavidF2F has joined #xmlprotocol [scribe_ce] scribe_ce has joined #xmlprotocol [scribe_ce] DF: attachment feature doc updated draft sent to the WG this afternoon. Unless we get substantive comments back, we'll send to w3c as a WD. [scribe_ce] ==== Issue 338 ==== [scribe_ce] DF: two questions in this issue related to state. Regarding the first, should they be separate states? Or should the condition for init be modified? [scribe_ce] MarkJ: does this also apply at an intermediary? [scribe_ce] DF: when we designed these was it done to handle case of streaming, in which case we don't say they're sequential or imply time constraints? [herve] herve has joined #xmlprotocol [scribe_ce] Noah: what are the criteria we apply about when state changes or not? [scribe_ce] DF: three proposals: (1) message exchange context initialized, control passed to local binding instance (2) transition condition is the initiation of the transmission (3) status quo [scribe_ce] Noah: state is split because actions are on arcs? [scribe_ce] Yves: way to read the table: if condition, go to next state and perform the action [scribe_ce] MarkJ: boolean condition that gates your leaving a state [scribe_ce] MarkJ: precondition to go to requesting state is existence of the beginning of the message (in streaming) [scribe_ce] DF: proposal transition condition in init state from 'unconditional' to 'initialization of message transmission' [scribe_ce] Yves: counter proposal to maintain status quo [scribe_ce] Yves: streaming and timing issues, when we start to send a request, have errors, etc. [scribe_ce] MarkJ: two questions - what to put in the box and how to explain unconditional to those who don't understand our usage of it. [scribe_ce] no objection to proposal for maintaining status quo in table [scribe_ce] ACTION: Asir to send email to xmlp comment and cc Mike Champion to close issue 338 by taking no action. [scribe_ce] ==== Issue 342 ==== [scribe_ce] ! [scribe_ce] ==== Continue with second part of issue 338 ==== [scribe_ce] Noah: the first sentence is backwards [scribe_ce] Yves: state table indicates transmission failure goes to fail state [scribe_ce] discussion of three interpretations of problem scenario [scribe_ce] Noah: once responder has started sending a response, is it clear what to do if you later decide you don't like the request (streaming scenario)? Is there something in state machine? [scribe_ce] Yves: go to fail mode and send fault [scribe_ce] Noah: but fault should be ruled out in this case because responder started sending a successful soap response and in the middle aborted. [scribe_ce] change last bullet "A requesting SOAP node MAY enter the Fail state, and thus abort transmission of the outbound SOAP request, based on information contained in an incoming streamed SOAP response. [scribe_ce] correction to proposed change above: change to "A requesting or responding SOAP node...." [anish_ca] anish_ca has joined #xmlprotocol [scribe_ce] MarkJ: responding SOAP node doesn't switch from sending response to sending a fault - just goes to fail and requesting soap node doesn't issue a fault, just aborts and goes to fail. [carine] responding SOAP node doesn't switch from sending response [carine] to sending a fault - just goes to fail and requesting soap node [carine] oops [scribe_ce] Noah: can you report a binding level error as a soap fault? [scribe_ce] Noah: if the answer is yes, do we have something in the MEP that the requestor gets to send out one soap message, and the responder gets to send out one soap message. Neither can send 2 messages so if they've already initiated one they can't start a fault [scribe_ce] MarkJ: table 20 has binding generated faults [scribe_ce] VW: 6.2.4 third paragraph "This MEP makes no claims about the disposition or handling of SOAP faults generated by the requesting SOAP node during any processing of the response message that follows the Success state in the requesting SOAP node's state transition table " [scribe_ce] MarkJ: table 20 binding generated faults are not SOAP faults. Suggests that binding level stuff isn't going to result in a soap fault but rather a binding level fault. [scribe_ce] Noah: State diagram responds to the first question in the second part of issue 338 (responding node sending a fault) [scribe_ce] DF: Proposal, no to first question in second part of issue 338. [scribe_ce] DF: proposal re second question in second part of issue 338 the situations in which a response results in a soap fault generated from the requestor are already specified. [scribe_ce] Noah: generate a fault if and only if the 'normal' soap rules say generate a fault. Even if you generate a fault, there no conformance requirements that say it needs to be transmitted (ref section y6.2.4) [scribe_ce] Noah: same case as if not streaming [Yves] wrt init state, see [Yves] ACTION 21= Asir to draft email to xmlp comment to close issue 338 by taking no action. [carine] zakim, who's here [Zakim] carine, you need to end that query with '?' [carine] zakim, who's here? [Zakim] On the phone I see F2FRoom [Zakim] On IRC I see anish_ca, herve, scribe_ce, DavidF2F, Mark_J, asir, Gudge, RRSAgent, Zakim, HFN_away, MarkB, carine, Loggy, Yves [Zakim] -F2FRoom [Zakim] WS_XMLP(f2f)12:00PM has ended [noah] noah has joined #XMLProtocol [noah] test [scribe_ce] ==== issue 342 ==== [Yves] wrt init state (issue 338 part 1) real URI is [noah] Before table 17:. [MarkB] right [Gudge] right what? [MarkB] was that a proposal? [carine] it seems to be already in the editors'copy [scribe_ce] Herves: reference paragraph before table 17 - missing in lc draft [scribe_ce] oops - Herve sorry [scribe_ce] Gudge: issue 224 resolved to remove the text - issue 342 is a dupe [MarkB] re 338 - it's moot because we just forgot to include text in the lc draft? [carine] s/remove/add [scribe_ce] df: proposal to close 342 as a dupe [scribe_ce] ACTION: Asir will send email to originator indicating this is handled as a dupe. [scribe_ce] ==== issues 348 and 349 go to Nilo ==== [scribe_ce] ==== issue 339 ==== [MarkB] oops, never mind 338 question, I meant 342. doh. [scribe_ce] Yves and Gudge: a binding generated fault not a soap generated fault [scribe_ce] df: inconsistency between tables 20 and 23 [scribe_ce] Herve: two kinds of malformed message, one at the binding level and one at the soap level [scribe_ce] ACTION: Herve look at section 7.5.2 and come back tomorrow with interpretation / clarification for the group [scribe_ce] ACTION 23 = Herve to look at 7.5.2 and come back tomorrow to the group with interpretation to understand context of issue 339. [scribe_ce] ==== Issue 340 ==== [Yves] herve: see [Yves] issue 338 again [MarkB] break time? [Yves] adjourned [Yves] so the break will be of several hours ;) [MarkB] cool [MarkB] talk to you tomorrow then ======= SUMMARY OF DAY'S ACTION ITEMS ============ [RRSAgent] I see 23 open action items: [RRSAgent] ACTION: Carine to send email to xlmpcomment and cc Joseph wrt ssue 241 [1] [RRSAgent] recorded in [RRSAgent] ACTION: DavidF to draft a response for issue 266 and bring it back to the WG [2] [RRSAgent] recorded in [RRSAgent] ACTION: Gudge to send a response for issue 268 [3] [RRSAgent] recorded in [RRSAgent] ACTION: editors to make the changes proposed for resolving issue 268 [4] [RRSAgent] recorded in [RRSAgent] ACTION: editors to resolve issue 267 with ed. changed [5] [RRSAgent] recorded in [RRSAgent] ACTION: Noah to send an email to Martin and get a clarification on issue 269 and 'cc' distapp [6] [RRSAgent] recorded in [RRSAgent] ACTION: editors to take on the last 2 items in issue 270 [7] [RRSAgent] recorded in [RRSAgent] ACTION: editors to use the URL posted by Asir in IRC as the starting point for the editorial changes to appendix A (issue 270) [8] [RRSAgent] recorded in [RRSAgent] ACTION: Inoue san to send resolution text to xmlp-comments (Cc: martin) to close issue 263 [9] [RRSAgent] recorded in [RRSAgent] ACTION: Glen to send closing text on issue 219 [10] [RRSAgent] recorded in [RRSAgent] ACTION: editors to incorporate the text for issue 219 [11] [RRSAgent] recorded in [RRSAgent] ACTION: Glen to send resolution text to xmlp comment for 230 [12] [RRSAgent] recorded in [RRSAgent] ACTION: editors to incorporate text changes for 230 [13] [RRSAgent] recorded in [RRSAgent] ACTION: Volker will send closing email for issue 329 referencing first part of Noah's email. [14] [RRSAgent] recorded in [RRSAgent] ACTION: Volker will send email to xml comments closing issue 330. [15] [RRSAgent] recorded in [RRSAgent] ACTION: Editors clarify that specifications for MEPs inherit requirements for features. Also note text in 3.1.1 sub 4. [16] [RRSAgent] recorded in [RRSAgent] ACTION: Gerd will send note to xmlp comment and cc mike champion to close 321 [17] [RRSAgent] recorded in [RRSAgent] ACTION: Colleen will send note to xmlp comment closing issue 332 [18] [RRSAgent] recorded in [RRSAgent] ACTION: Colleen will send email to xmlp comments cc Mike Champion closing issue 333, referencing draft tag findings that it's okay to use QNames in this way. [19] [RRSAgent] recorded in [RRSAgent] ACTION: MarkJ to send email to xmlp comment and cc Mike Champion closing issue 336. [20] [RRSAgent] recorded in [RRSAgent] ACTION: Asir to draft email to xmlp comment to close issue 338 by taking no action. [21] [RRSAgent] recorded in [RRSAgent] ACTION: Asir will send email to originator indicating this is handled as a dupe. [22] [RRSAgent] recorded in [RRSAgent] ACTION: Herve to look at 7.5.2 and come back tomorrow to the group with interpretation to understand context of issue 339. [23] [RRSAgent] recorded in
http://www.w3.org/2000/xp/Group/2/08/f2f-minutes-day2.html
CC-MAIN-2015-18
refinedweb
5,801
63.43
Been on a new job for a few months now. One of the first things I noticed is we were getting a huge bill for AmazonCloudWatch PutLogEvents and we weren’t quite sure what was the primary culprit. So, ended up creating a small tool to tag all of our log groups and then in Cost Explorer it allowed us to filter by those tags to narrow things down. Just requires python and the boto3 library: import sys import boto3 from botocore.exceptions import ClientError region = ‘us-east-1’ “””Tag all log groups Since many log groups are auto created by other functionality, there is no means to add tagging. This will tag each of our cloudwatch log groups so we can keep track of each from a cost perspective “”” cwlogs = boto3.client(‘logs’, region) response = cwlogs.describe_log_groups() for logGroup in response[‘logGroups’]: logGroupName = logGroup[‘logGroupName’] print “Tagging ” + logGroupName + “with Key:log_group, Value: ” + logGroupName.replace(“/”, ““) print cwlogs.tag_log_group(logGroupName=logGroupName,tags={‘log_group’:logGroupName.replace(“/”,”“)})
http://ricktbaker.com/2018/12/04/tag-your-aws-log-groups/
CC-MAIN-2020-29
refinedweb
164
55.03
#include <AIStateMachine.h> Defines a simple AI state machine that can be used to program logic for an AIAgent in a game. A state machine uses AIState objects to represent different states of an object in the game. The state machine provides access to the current state of an AI agent and it controls state changes as well. When a new state is set, the stateExited event will be called for the previous state, the stateEntered event will be called for the new state and then the stateUpdate event will begin to be called each frame while the new state is active. Communication of state changes is facilitated through the AIMessage class. Messages are dispatched by the AIController and can be used for purposes other than state changes as well. Messages may be sent to the state machines of any other agents in a game and can contain any arbitrary information. This mechanism provides a simple, flexible and easily debuggable method for communicating between AI objects in a game. Creates and adds a new state to the state machine. Adds a state to the state machine. The specified state may be shared by other state machines. Its reference count is increased while it is held by this state machine. Returns the active state for this state machine. Returns a state registered with this state machine. Removes a state from the state machine. Changes the state of this state machine to the given state. If no state with the given ID exists within this state machine, this method does nothing. Changes the state of this state machine to the given state. If the given state is not registered with this state machine, this method does nothing.
http://gameplay3d.github.io/GamePlay/api/classgameplay_1_1_a_i_state_machine.html
CC-MAIN-2017-17
refinedweb
285
73.27
This action might not be possible to undo. Are you sure you want to continue? 144/440 MHz FM DUAL BANDER TH-D7A TH-D7E 144/430 MHz FM DUAL BANDER STA CON 5 7 PACKET96BCONDUP 9 KENWOOD CORPORATION © B62-1004-00 (K,E) (A) 09 08 07 06 05 04 03 02 01 00 THANK YOU! We are grateful you decided to purchase this KENWOOD FM Dual Bander. KENWOOD always provides Amateur Radio products which surprise and excite serious hobbyists. This transceiver is no exception. This time KENWOOD presents a handheld with a built-in TNC to make data communications much more convenient than before. KENWOOD believes that this product will satisfy your requests on both voice and data communications. FEATURES This transceiver has the following main features. • Has a built-in TNC which conforms to the AX.25 protocol. With a portable computer, allows you to enjoy Packet operation quite easily. • Includes a program for dealing with data formats supported by Automatic Packet/ Position Reporting System (APRS®) . • Is capable of receiving packet data on one band while receiving audio on another band. • Contains a total of 200 memory channels to program frequencies and other various data. Allows each memory channel to be named using up to 8 alphanumeric and special ASCII characters. • If programmed, the built-in Continuous Tone Coded Squelch System (CTCSS) rejects unwanted calls from other stations. • Equipped with an easy-to-read large LCD with alphanumeric display capability. • Employs a 4-way cursor key so that you can program most of the functions with only one hand. • Enhances the functions of an optional VC-H1 Interactive Visual Communicator designed for plug-and-play color slow-scan television (SSTV). • Utilizes Sky Command System 2 designed to control a KENWOOD HF transceiver at a remote location (TH-D7A only). MODELS COVERED BY THIS MANUAL The models listed below are covered by this manual. TH-D7A: 144/440 MHz FM Dual Bander (U.S.A./ Canada) TH-D7E: 144/430 MHz FM Dual Bander (Europe) NOTICES TO THE USER ATTENTION (U.S.A. Only) Nickel-Cadmium batteries must be replaced or disposed of properly. State laws may vary regarding the handling and disposal of Nickel-Cadmium batteries. Please contact your authorized KENWOOD dealer for more information. PRECAUTIONS Please observe the following precautions to prevent fire, personal injury, or transceiver damage: • • • Do not transmit with high output power for extended periods. The transceiver may overheat. Do not modify this transceiver unless instructed by this manual or by KENWOOD documentation. When using a regulated power supply, connect the specified DC cable (option) to the DC IN jack on the transceiver. The supply voltage must be between 5.5 V and 16 V to prevent damaging the transceiver. When connecting the transceiver to a cigarette lighter socket in a vehicle, use the specified cigarette lighter cable (option). Do not expose the transceiver to long periods of direct sunlight nor place the transceiver close to heating appliances. Do not place the transceiver in excessively dusty areas, humid areas, wet areas, nor on unstable surfaces. If an abnormal odor or smoke is detected coming from the transceiver, turn OFF the power immediately and remove the battery case or the battery pack from the transceiver. Contact your authorized KENWOOD dealer, customer service, or service station. One or more of the following statements may be applicable: FCC WARNING This equipment generates or uses radio frequency energy. Changes or modifications to this equipment may cause harmful interference unless the modifications are expressly approved in the instruction manual. The user could lose the authority to operate this equipment if an unauthorized change or modification is made. INFORMATION TO THE DIGITAL DEVICE USER REQUIRED BY generate for technical assistance. • • • • i ............ 11 CURSOR KEYS .... 5 CONNECTING WITH A CIGARETTE LIGHTER SOCKET ........................................................................................... 7 ADJUSTING SQUELCH ................................................................................... 21 Selecting Offset Frequency ....... 10 INDICATORS ............................................................. 24 TONE FREQ......................................................... 28 NAMING A MEMORY CHANNEL .... 3 INSTALLING ALKALINE BATTERIES ............................ 1 CONVENTIONS FOLLOWED IN THIS MANUAL .. 9 Selecting Output Power ......... 2 CHARGING THE NiCd BATTERY PACK ...................................................................................................................................... 16 MENU CONFIGURATION ........................................................ 17 OPERATING THROUGH REPEATERS CHAPTER 6 PROGRAMMING OFFSET .........CONTENTS SUPPLIED ACCESSORIES .............................................................. 25 CHAPTER 7 MEMORY CHANNELS SIMPLEX & REPEATER OR ODD-SPLIT MEMORY CHANNEL? ................. 13 KEYPAD DIRECT ENTRY .. 23 REVERSE FUNCTION ............................................................................................... 7 ADJUSTING VOLUME ... 5 FIRST QSO CHAPTER 2 CHAPTER 3 OPERATING BASICS SWITCHING POWER ON/OFF ........... 30 Reprogramming the Call Channel .............................................................................. 9 CHAPTER 4 GETTING ACQUAINTED ORIENTATION ............... 8 TRANSMITTING ................... 21 Activating Tone Function ............ 27 RECALLING A MEMORY CHANNEL ........ 15 CHAPTER 5 MENU SET-UP MENU ACCESS ............. 7 SELECTING A BAND ............ 2 INSTALLING THE ANTENNA ....................... 26 STORING SIMPLEX FREQUENCIES OR STANDARD REPEATER FREQUENCIES ...... 1 CHAPTER 1 PREPARATION INSTALLING THE NiCd BATTERY PACK ...................... 27 STORING ODD-SPLIT REPEATER FREQUENCIES ........... 22 Selecting a Tone Frequency ............................................................................................................................................... 30 MEMORY-TO-VFO TRANSFER ................................ 28 CLEARING A MEMORY CHANNEL ......................................... 7 SELECTING A FREQUENCY ....... 31 CHANNEL DISPLAY ..................................... 31 PARTIAL OR FULL RESET? ......................... 29 CALL CHANNEL (TH-D7A ONLY) ..... 32 ii .................. 4 CONNECTING WITH A REGULATED POWER SUPPLY ..................... 21 Selecting Offset Direction ................................................................................................... 12 BASIC TRANSCEIVER MODES .............................................................. ID ................................................................................. 24 AUTOMATIC SIMPLEX CHECK (ASC) .......... 30 Recalling the Call Channel ....................... 22 AUTOMATIC REPEATER OFFSET .......... 12 BAND A & B .............................................. 3 INSTALLING THE HAND STRAP/ BELT HOOK ................................................. .............................................................................. 46 TONE ALERT .......................... 35 Locking Out a Memory Channel .......... 39 USING CTCSS .............................. 46 PROGRAMMABLE VFO ............. 48 AUTOMATIC POWER OFF (APO) ....... 51 PACKET OPERATION CHAPTER 13 CONNECTING WITH A PERSONAL COMPUTER ....................... 36 MHz SCAN . 42 Storing a DTMF Number in Memory ...................... ID ....................................... 53 OPERATING TNC ............................................................... 38 CALL/VFO SCAN (TH-D7A ONLY) .......................... 43 CHAPTER 11 MICROPHONE CONTROL CHAPTER 12 AUXILIARY FUNCTIONS DIRECT FREQUENCY ENTRY .................................................................... 48 LAMP FUNCTION .................................. 35 MEMORY SCAN ......................... 51 SWITCHING TX DEVIATION (TH-D7E ONLY) ...........................................................CHAPTER 8 SCAN SELECTING SCAN RESUME METHOD ... 55 FULL DUPLEX ...................... 55 CHAPTER 14 DX PACKETCLUSTERS MONITOR 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 iii ....... 47 BEEP ON/OFF ....... 47 ADJUSTING VOLUME BALANCE ................. 38 CALL/MEMORY SCAN (TH-D7A ONLY) ...................................................................... 49 BATTERY SAVER .............................................................................. 51 SWITCHING AM/FM MODE (TH-D7A ONLY) ... 50 TRANSCEIVER LOCK ............. 48 ADJUSTING DISPLAY CONTRAST .................... 42 Transmitting a Stored DTMF Number ..... 34 VFO SCAN ................ 54 SELECTING DATA BAND .......................................................................................................................... 45 CHANGING FREQUENCY STEP SIZE .................................... 51 ADVANCED INTERCEPT POINT (AIP) ... 40 CHAPTER 10 DUAL TONE MULTI-FREQUENCY (DTMF) FUNCTIONS MANUAL DIALING ........................................................ 37 Setting Scan Limits ... 41 TX Hold .................................................................................... 48 BLANKING A BAND DISPLAY ......................................................................... 49 POWER-ON MESSAGE ............................................................................. 53 PREPARATION FLOW ...... 40 CTCSS FREQ.......................... 37 Using Program Scan ......................... 41 AUTOMATIC DIALER .............. 36 PROGRAM SCAN ................................................................................................. 38 CONTINUOUS TONE CODED SQUELCH CHAPTER 9 SYSTEM (CTCSS) SELECTING A CTCSS FREQUENCY .............................................................................................................. 50 TX INHIBIT .............. .................................................... 90 OPTIONAL ACCESSORIES CHAPTER 21 CHAPTER 22 EQUIPMENT CONNECTIONS CONNECTING EQUIPMENT FOR REMOTE CONTROL .................................................... 76 RECEIVING A MESSAGE ........... 89 SERVICE ....................................................... 89 CLEANING .................. 80 iv 15 CHAPTER CHAPTER WIRELESS REMOTE CONTROL (TH-D7A ONLY) PREPARATION ........................................... 67 ENTERING LATITUDE/ LONGITUDE DATA . 96 CONNECTING OTHER EXTERNAL EQUIPMENT ................. 79 TRANSMITTING A MESSAGE ............................................................................................................................................ 59 EXECUTING SUPERIMPOSITION ......... 71 PROGRAMMING A PACKET PATH .............................................. 68 SELECTING A POSITION COMMENT ....................................................... 63 ACCESSING RECEIVED APRS DATA ..................................................................................................... 85 PROGRAMMING CALL SIGNS ............................... 74 SELECTING BEACON TRANSMIT INTERVAL ............................................................ 78 ENTERING A MESSAGE ............. 75 APRS® MESSAGE CHAPTER 17 OPERATION FLOW ...................................................... 82 CHAPTER 19 SKY COMMAND 2 (TH-D7A ONLY) CONNECTING THE TRANSPORTER WITH THE HF TRANSCEIVER .............. 89 TROUBLESHOOTING . 75 RESTRICTING RECEPTION OF APRS DATA .......................... 70 PROGRAMMING A GROUP CODE ....................... 58 SELECTING COLOR FOR CALL SIGN/ MESSAGE/ RSV ............................ 72 SELECTING BEACON TRANSMIT METHOD ................... 89 SERVICE NOTE ... 66 SELECTING YOUR STATION ICON ...................................... 64 PROGRAMMING A CALL SIGN ............... 86 PROGRAMMING A TONE FREQUENCY .. 81 CONTROL OPERATION ......... 69 ENTERING STATUS TEXT ................................................................SLOW-SCAN TELEVISION (SSTV) WITH VC-H1 ENTERING CALL SIGN/ MESSAGE/ RSV ............................... 86 CONTROL OPERATION ........... 84 PREPARATION FLOW ......... 87 CHAPTER 20 MAINTENANCE GENERAL INFORMATION ........................ 59 VC-H1 CONTROL ............................................................ 60 AUTOMATIC PACKET/ POSITION REPORTING CHAPTER 16 SYSTEM® OPERATION FLOW ............................... 77 ACCESSING RECEIVED APRS MESSAGES ................................ 62 RECEIVING APRS DATA..... 96 CHAPTER 23 SPECIFICATIONS APPENDIX QUICK REFERENCE GUIDE INDEX 18 .............................................................. then press the POWER switch. Press [KEY1]+[KEY2]. Press and hold KEY for 1 second or longer. Press [KEY1]. Instruction Press [KEY]. With transceiver power OFF. What to Do Press and release KEY. release KEY1. Press KEY1 momentarily. Press [KEY]+ POWER ON. then press KEY2. 650 mAh) Use this accessory to modify the cable end of your GPS receiver {page 61}. 1 . press and hold KEY.5 mm (1/10") 3-conductor plug 3 Warranty card Instruction manual 1 2 3 CONVENTIONS FOLLOWED IN THIS MANUAL Part Number T90-0634-XX W09-0911-XX W09-0909-XX W08-0437-XX W08-0440-XX J29-0631-XX J69-0342-XX E30-3374-XX — B62-1004-XX Quantity 1 1 The writing conventions described below have been followed to simplify instructions and avoid unnecessary repetition. 600 mAh) PB-38 (6 V. Press and hold KEY1. then press KEY2.6 V. [KEY2]. 1 1 1 1 1 1 Press [KEY] (1 s). PB-39 (9.SUPPLIED ACCESSORIES Accessory Antenna NiCd battery pack For TH-D7A 1 For TH-D7E 2 Battery charger For TH-D7A For TH-D7E Belt hook Hand strap Cable with a 2. Release latch Exceeding the specified charge period shortens the useful life of the NiCd battery pack. push up the release 19 20 21 22 23 Guide 10 2 Slide the battery pack along the back of the INSTALLING THE NiCd BATTERY PACK 1 Position the two grooves on the inside bottom corners of the battery pack over the corresponding guides on the back of the transceiver. The battery pack is provided uncharged. • Charging starts and will take approximately 16 hours for PB-38 or 15 hours for PB-39. remove the charger DC plug from the transceiver DC IN jack. 1 Confirm that the transceiver power is OFF. DC IN jack transceiver until the release latch on the base of the transceiver locks the battery pack in place. 5 Remove the charger AC plug from the AC wall outlet. 4 After 16 hours (PB-38) or 15 hours (PB-39). CHARGING THE NiCd BATTERY PACK After installing the NiCd battery pack. x x latch. 2 Insert the DC plug from the charger into the DC IN jack on the transceiver. The provided charger is designed to charge only the provided PB-38 or PB-39 NiCd battery pack. charge the battery pack. Charging other models of battery packs will damage the charger and battery pack. 3 Insert the charger AC plug into an AC wall outlet. 2 . leave the transceiver power OFF. • While charging the battery pack.PREPARATION 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 3 To remove the battery pack. then slide the battery pack back. the battery life is over. pull the belt hook downward while pushing its tabs from both sides. and screw the antenna into the connector on the top panel of the transceiver until it is snug. or almost fully charged pack.5 L 6 7 EL 9 10 H 3 4 L 6 7 EL 9 10 UHF Band INSTALLING THE HAND STRAP/ BELT HOOK If desired. To remove the belt hook. attach the provided hand strap and/ or belt hook. Charging outside this range may not fully charge the pack. position the 17 cable over the right groove. 18 19 20 PC PC PC GPS GPS GPS 21 22 23 3 . x Repeatedly recharging a fully charged NiCd battery pack.The following table shows the approximate battery life (hours) relative to the transmit output power. Last. VHF Band Batteries H PB-39 NiCd PB-38 NiCd 3 4. x If the operating time of a fully charged NiCd battery pack is much shorter than before. Replace the pack. shortens its operating time. Then install the belt hook. use the pack until it is completely discharged. To resolve this problem. Then recharge the pack to full capacity. 8 9 10 11 12 13 14 INSTALLING THE ANTENNA Hold the provided antenna at its base. Belt hook Hand strap 1 2 3 4 5 6 7 Note: x Charge the NiCd battery pack within an ambient temperature of between 5°C and 40°C (41°F and 104°F). 15 To lock the cable of an optional speaker microphone. first position the cable over the left groove on the 16 transceiver. then pull the cover. Do not use commercially available NiCd batteries. replace all four old batteries with new ones. 1 To open the battery case cover. follow steps 1 to 3 for INSTALLING THE NiCd BATTERY PACK {page 2}. 12 13 14 15 16 17 18 3 Align the two tabs on the battery case cover. x Do not use different kinds of batteries together. Tab 4 . x x Do not install the batteries in a hazardous environment where sparks could cause an explosion. x The following table shows the approximate battery life (hours) relative to the transmit output power. Note: It is recommended to use high quality alkaline batteries rather than manganese batteries to enjoy longer periods of battery life. Locking tab 4 To install the battery case onto (or remove from) the transceiver. then 19 20 21 22 23 With an optional BT-11 battery case. you can use commercially available alkaline batteries in such occasions as camping or emergency operations. Never discard old batteries in fire because extremely high temperatures can cause batteries to explode. push on the locking tab. x When the battery voltage is low. • Be sure to match the battery polarities with those 11 marked on the bottom of the battery case. VHF Band Batteries H Alkaline 14 L 22 EL 33 H 14 UHF Band L 22 EL 30 close the cover until the locking tab clicks. x If you will not use the transceiver for a long period.INSTALLING ALKALINE BATTERIES 1 2 3 4 5 6 7 8 9 10 2 Insert four AA (LR6) alkaline batteries. remove the batteries from the battery case. 5 . If input voltage exceeds approximately 18 V. warning beeps sound and a warning message appears. warning beeps sound and a warning message appears. CONNECTING WITH A CIGARETTE LIGHTER SOCKET To connect the transceiver with the cigarette lighter socket in your vehicle. DC IN jack Cigarette lighter socket 24V 12V PG-3J DC-DC converter 24V 12V PG-2W Note: x Only use the power supplies recommended by your authorized KENWOOD dealer. x The supply voltage must be between 5.5 V and 16 V to prevent damaging the transceiver. 1 Confirm that the power switches of both the transceiver and power supply are OFF. DC IN jack To cigarette lighter socket 1 2 3 4 5 6 7 8 Black Red 9 To connect with an external 24 V power source via a DC-DC converter. use an optional PG-3J Cigarette Lighter cable. only use the optional PG-3J Cigarette Lighter cable. use an optional PG-2W DC cable. Note: If input voltage exceeds approximately 18 V.CONNECTING WITH A REGULATED POWER SUPPLY To connect the transceiver with an appropriate regulated power supply. and black lead to negative (–) terminal. 2 Connect the optional PG-2W DC cable to the power supply. red lead to positive (+) terminal. DC-DC converter 24V 12V PG-3J 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Fuse Regulated power supply 3 Connect the barrel plug on the DC cable to the DC IN jack on the side of the transceiver. Using the PG-2W DC cable in this situation may cause a fire. also hear background noise. 5 Press and hold the PTT switch. 2 Turn the VOL control clockwise to the 11 o’clock position. 6 Release the PTT switch to receive. 6 . 1 4 Press [UP]/ [DWN] or turn the Tuning control to select a frequency. then speak into the microphone in a normal tone of voice. Press the POWER switch for 1 second or longer. You will. however. The 7 steps given here will get you on the air in your first QSO right away. you can enjoy the exhilaration that comes with opening a brand new transceiver. press and hold [MONI] to hear clearer signals.FIRST QSO 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Note: When received signals are too weak to recognize. 3 Press [A/B] to select band A or B. 7 Repeat steps 5 and 6 to continue communication. So. • To change frequencies in steps of 1 MHz.OPERATING BASICS SWITCHING POWER ON/OFF 1 Press the POWER switch (1 s) to switch ON the transceiver. • You can also select frequencies by directly entering digits from the keypad. press and hold [MONI]. 1 2 3 4 5 6 7 8 9 2 To switch OFF the transceiver. press the POWER switch (1 s) again. See “DIRECT FREQUENCY ENTRY” {page 45}. • Pressing and holding [UP]/ [DWN] causes the frequency to step repeatedly. While pressing [MONI]. • The cursor indicates the current band. SELECTING A FREQUENCY Press [UP]/ [DWN] or turn the Tuning control to select a frequency. • If background noise is inaudible because of the Squelch function. press [MHz] first. 7 . 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ADJUSTING VOLUME Turn the VOL control clockwise to increase the audio level and counterclockwise to decrease the audio level. The 1 MHz digit blinks. • A double beep sounds. Pressing [MHz] again cancels this function. SELECTING A BAND Press [A/B] to select band A or B. then adjust the VOL control. you will hear background noise. the stronger the signals must be to receive. • Select the level at which the background noise is just eliminated when no signal is present. You can program a different level for band A and B. • The SQL meter indicates the current squelch level. (Squelch opened) No speaker output Audio (Squelch opened) The current squelch level is incorrect. 3 Press [OK] to complete the setting. Noise 1 Press [F]. 4 segments are visible. 2 Press [UP]/ [DWN] to select from 6 squelch levels. • The higher the level selected. Selecting the correct squelch level relieves you from listening to background noise output from the speaker when no signals are present. The appropriate squelch level depends on ambient noise conditions.ADJUSTING SQUELCH 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 (Squelch closed) The current squelch level is correct. [MONI]. The default is level 2. 8 . if communication is still reliable. low. press and hold the PTT switch and speak into the microphone in a normal tone of voice. may cause the power supply to output an extremely high voltage. release the PTT switch. may increase distortion and reduce intelligibility of your signal at the receiving station.TRANSMITTING 1 To transmit. Press [F]. or “EL” appears to show the current selection. [MENU] to select high (default). • “H”. STA CON 5 x x 7 PACKET96BCONDUP 9 The recommended duty cycle is 1 minute of transmission and 3 minutes of reception. STA CON 5 7 PACKET96BCONDUP 9 9 . that is not recommended by KENWOOD. • The battery meter appears to show the current relative battery charge. Selecting lower transmit power is a wise method to reduce battery consumption. then press the PTT switch to resume transmitting. “L”. This voltage could damage both your transceiver and any other equipment connected to the power supply. You cannot switch this function OFF. Extended transmissions in the high power mode may cause the back of the transceiver to get hot. You can program a different power for band A and B. warning beeps sound and a warning message appears. Transmitting with the supplied antenna near other electronic equipment can interfere with that equipment. s Selecting Output Power • Speaking too close to the microphone. 2 When you finish speaking. Time-Out Timer: Holding down the PTT switch for more than 10 minutes causes the transceiver to generate a beep and stop transmitting. Release. transmitting near a poorly regulated power supply. • Indicator A or B lights red depending on which band you have selected. Also. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Note: If input voltage exceeds approximately 18 V while using an external power source. or economic low power (lowest). or too loudly. GETTING ACQUAINTED 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 DC IN jack LAMP key MONI key Cursor keys Speaker/ Microphone PTT switch POWER switch Display SP jack MIC jack PC jack GPS jack Tuning control VOL control Antenna TX/RX indicator ORIENTATION Keypad 10 . the display will typically return to normal operation within a couple of minutes. Note: Electromagnetic fields. may occasionally cause the display to function abnormally.INDICATORS On the upper section of the display you will see various indicators that show what you have selected. shows the current relative battery charge. However. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 TH-D7E only 5 18 7 9 19 20 21 22 23 Shows the strength of received signals. such as those produced by static electricity. While transmitting. 11 . 10 memory channels. This transceiver is capable of simultaneously receiving on 2 bands (A and B). In band B you can also recall a VHF (144 MHz) sub-band. 18 ESC key 19 Press to move back to the previous step or to quit the 20 setting in various selection modes such as Function 21 Select or Menu mode. UP/ DWN keys The UP/ DWN keys function in the exact same way as the Tuning control. 11 You can use the Tuning control instead of 12 Note:operation step. “ ” indicates the current data band {page 55}. depending on the current transceiver mode. This transceiver employs 4 cursor keys so that you can program most of the functions with only one hand. for example. 14 15 OK key Press to move to the next step or to complete the setting TH-D7A only 16 in various selection modes such as Function Select or 17 Menu mode. These keys change frequencies. To transmit. The band A default is VHF (144 MHz) and the band B default is UHF. or other selections. First press [VFO] to select VFO mode.CURSOR KEYS 1 2 3 4 5 6 7 8 9 BAND A & B In this manual. This manual often omits the the UP/ DWN keys in each Tuning control to 13 simplify descriptions. x The 118 MHz band cannot be used for transmitting. So. it is possible to receive packet data on one VHF frequency while receiving audio on another VHF frequency. 12 . you must select either band. 22 23 Note: x You cannot recall another band by pressing [F]. [A/B] in Memory Recall mode. bands recalled beside “ ” and “ ” are referred to as band A and band B. The following diagram should help you understand how to select or recall the desired band. In band A you can also recall a 118 MHz sub-band (TH-D7A only). press [OK]. refer to “MEMORY CHANNELS” {page 26}. After accessing the desired function. STA CON 5 1 2 3 4 5 6 7 8 9 10 7 PACKET96BCONDUP 9 Memory Recall mode Press [MR] to select. Last. For further information.BASIC TRANSCEIVER MODES This section introduces you to the basic modes you can select on this transceiver. VFO mode Press [VFO] to select. After recalling a memory channel. In this mode you can recall the desired memory channel by pressing [UP]/ [DWN] or entering digits directly from the keypad {page 28}. press [OK] again to complete the setting. STA CON 5 11 15 16 17 18 19 7 PACKET96BCONDUP 9 20 21 22 23 13 . pressing [F]. For example. [0] ~ [9] is a much simpler method than the above. refer to “MENU SET-UP” {page 16}. to access F–6. [1] switches the Tone 12 function ON or OFF. On the TH-D7E you cannot access F–6. In this mode you can change the operating frequency by pressing [UP]/ [DWN] or entering digits directly from the keypad {page 45}. first select the 118 MHz band {page 51}. Pressing [F]. In this mode you can access the desired menu item by pressing [UP]/ [DWN] and [OK] or entering digits directly from the keypad. This method is described in the 13 appropriate sections in this manual. 14 Menu mode Press [MENU] to select. Function Select mode Press [F] to select. then press [UP]/ [DWN] to select the desired parameter. For further information. In this mode you can scroll F–1 through F–8 (except F–6) by pressing [UP]/ [DWN]. you can also access F–0 and F–9. refer to “FULL DUPLEX” {page 55}. So. In this mode. For further information. {page 54}.Full Duplex mode 1 2 3 4 5 6 7 8 9 10 Packet mode 11 Press [TNC] twice to select. In this mode the transceiver is capable of simultaneously transmitting and receiving signals. you can send 12 commands to the built-in TNC from a personal computer 13 14 15 16 17 18 19 20 21 22 23 Press [DUP] to select. it is possible to transmit audio on the current band while receiving packet data on another band. 14 . use the keypad to select a menu item. B. c. C. then press the keys on the keypad {page 41}. > . Press [DUAL] to switch 0 and space. press and hold the PTT switch. pressing [1]. [1] in sequence selects Menu 1–4–1 (DATA BAND). Press [ENT] to switch among the special ASCII characters. [4]. . 1 2 3 4 5 6 7 8 The selectable special characters are listed below: In Menu mode. Press [ENT] first. – : / " & @ # 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Note: Pressing [UP]/ [DWN] allows you to select more special ASCII characters than above. a. In VFO or Memory Recall mode. 15 . For example. or other character strings. b. To manually send a DTMF number. For example. each press of [TNC] switches entry as A. Power-ON message {page 50}. use the keypad to select a frequency {page 45} or memory channel number {page 28}. You can also use the keypad to program a memory channel name {pages 29 and 42}. then 2.KEYPAD DIRECT ENTRY The keypad allows you to make various entries depending on which mode the transceiver is in. ? ( ! ) ’ < . STA CON • To move back to level 1. [1] in sequence selects Menu 1–4–1 (DATA BAND). 7 PACKET96BCONDUP 9 13 14 15 16 2 Press [UP]/ [DWN] to select the appropriate level 1 No. to quickly select a menu item. blinks.MENU SET-UP 1 2 3 4 5 6 7 8 9 10 11 12 5 The Menu system on this transceiver consists of 3 levels. • To exit Menu mode. See the appropriate sections in this manual. blinks. After pressing [MENU] in step 1. • The procedure in this step differs depending on which menu item you selected. 17 18 19 20 21 22 23 5 6 For Menu 1–1 to 1–5. • The current level 1 No. you can also enter level Nos. 9 Press [MENU] to exit Menu mode. 3 Press [OK]. This method is described in the appropriate sections in this manual. press [MENU]. 8 Press [OK] to complete the setting. pressing [1]. • The current level 2 No. [4]. STA CON 7 PACKET96BCONDUP 9 16 . 5 Press [OK]. 7 Press [UP]/ [DWN] to select a parameter. For example. STA CON 5 Level 3 1 2 1 2 1 2 3 4 1 2 1 2 3 4 5 6 7 Menu 1–3–1 7 PACKET96BCONDUP 9 MENU ACCESS 1 Press [MENU] to enter Menu mode. repeat steps 4 and 5 to select level 3. press [ESC] instead. Level 1 Level 2 1 2 3 1 4 5 2 1 2 3 4 4 Press [UP]/ [DWN] to select the appropriate level 2 No. 2/ 0. 63. Band A Data band only ON TimeOperated ALL OFF OFF OFF Ref.MENU CONFIGURATION Level 1 1 Level 2 DISPLAY 1 2 1 2 1 2 3 DTMF 3 4 1 RADIO 4 TNC 1 2 1 2 3 4 5 6 Level 3 Power-ON Message Contrast Battery Saver Interval Selections See reference page./ OFF See reference page.0/ 4.77 50 51 51 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 2 SAVE Automatic Power Off (APO) 30/ 60 minutes/ OFF Number Store TX speed TX Hold Pause Data band select DCD sense Automatic Repeater Offset Scan Resume Beep function Tuning Enable TX Inhibit Advanced Intercept Point (TH-D7A) 5 AUX 17 .0/ 2. Fast/ Slow ON/ OFF 100/ 250/ 500/ 750/ 1000/ 1500/ 2000 msec.0 sec. 30 minutes — Fast OFF 500 msec.0/ 5.0/ 3.56. page 50 48 49 49 42 43 41 43 55 55 23 34 47.8/ 1. Band A/ Band B Both bands/ Data band only ON/ OFF Time-Operated/ Carrier-Operated/ Seek OFF/ KEY/ KEY+NEW DATA/ ALL ON/ OFF ON/ OFF ON/ OFF Default HELLO !! Level 8 1.4/ 0. Level 1 (min.) 0.6/ 0.0 sec.) ~ 16 (max. 10 ~ 2500 in steps of 10/ OFF Mile and °F/ Kilometer and °C Default OFF — OFF OFF — Default — Not used — — — — 5 minutes — Manual — OFF Mile and °F Ref. . See reference page. page 66 62 68 69 67 70 75 72 74 71 75 65 1 RADIO 5 AUX 7 8 9 Level 1 1 2 3 4 5 6 2 APRS 7 8 9 A B C 18 My call sign GPS receiver Latitude/ longitude data Position comment Station icon Status text Beacon transmit interval Packet path Beacon transmit method Group code Reception restriction distance Unit .5/ 1/ 2/ 3/ 5/ 10/ 20/ 30 minutes See reference page.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Level 1 Level 2 6 7 Level 3 TX Hold. page 22 32 51 51 32 Ref. See reference page. Manual/ PTT/ Auto See reference page. See reference page. 1750 Hz (TH-D7E) Reset (TH-D7A) VHF band narrow TX deviation (TH-D7E) Advanced Intercept Point (TH-D7E) Reset (TH-D7E) Level 2 Selections ON/ OFF Partial (VFO)/ Full/ No ON/ OFF ON/ OFF Partial (VFO)/ Full/ No Selections See reference page. Not used/ NMEA See reference page. See reference page. Commander/ Transporter/ OFF Default — White — White — White — — OFF — — — OFF Ref. page 58 59 58 59 58 59 59 57 60 86 86 86 85 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 2 3 4 19 . White/ Black/ Blue/ Red/ Magenta/ Green/ Cyan/ Yellow See reference page.Level 1 1 2 3 4 3 SSTV 5 6 7 8 9 1 4 SKY CMD (TH-D7A only) Level 2 My call sign Color for call sign Message Color for message RSV report Color for RSV report Superimposition Execute SSTV mode VC-H1 Control Commander call sign Transporter call sign Tone frequency select Sky Command mode select Selections See reference page. See reference page. ON/ OFF See reference page. White/ Black/ Blue/ Red/ Magenta/ Green/ Cyan/ Yellow See reference page. See reference page. White/ Black/ Blue/ Red/ Magenta/ Green/ Cyan/ Yellow See reference page. (Only when programming odd-split repeater frequencies) t Activate the Tone function. 11 12 13 14 15 16 17 18 19 20 21 22 23 TX: 144.325 MHz 20 . which are often installed and maintained by radio clubs. See “MEMORY CHANNELS” {page 26}. For details. This combination of elevation and high ERP allows communications over much greater distances than communications without using repeaters. Offset Programming Flow q Select a band. TX: 144. consult 10 your local repeater reference. are usually located on mountain tops or other elevated locations. (If necessary) y Select a tone frequency. In addition.OPERATING THROUGH REPEATERS 1 2 3 4 5 6 7 8 Repeaters. e Select an offset direction. some repeaters must receive a tone from the 9 transceiver to allow it to access.725 MHz TX tone: 88.5 Hz RX: 145. (If necessary) Most repeaters use a receive and transmit frequency pair with a standard or non-standard offset (odd-split).325 MHz If you store the above data in a memory channel. r Select an offset frequency.5 Hz RX: 145.725 MHz TX tone: 88. you need not reprogram every time. Generally they operate at higher ERP (Effective Radiated Power) than a typical station. w Select a receive frequency. change the offset frequency from the default which is used by most repeaters. The default offset frequency on the VHF band is 600 kHz no matter which market version. 3 Press [OK] to complete the setting.95 MHz 13 in steps of 50 kHz. • The selectable range is from 0. Press [F].00 MHz to 29. STA CON 5 s Selecting Offset Frequency To access a repeater which requires an odd-split frequency pair. you cannot change the offset direction. the new offset frequency will also be used by Automatic Repeater Offset. Use one of the following methods to bring the transmit frequency within the band limits: • Move the receive frequency further inside the band. transmitting is inhibited. [5] to select “F–5 (OFFSET)”. repeatedly press [F]. s Selecting Offset Direction Select whether the transmit frequency will be higher (+) or lower (–) than the receive frequency.6 MHz offset on the TH-D7E (UHF only). [MHz] until “ ” appears. you 15 16 17 18 19 20 21 22 23 Note: After changing the offset frequency. Note: While using an odd-split memory channel or transmitting. 21 . • “+” or “–” appears to indicate which offset direction is selected. • To program –7. STA CON 5 1 2 3 4 5 6 7 8 9 10 11 7 PACKET96BCONDUP 9 7 PACKET96BCONDUP 9 2 Press [UP]/ [DWN] to select the appropriate offset 12 frequency. Then. if necessary. • Change the offset direction.PROGRAMMING OFFSET First select band A or B by pressing [A/B]. [A/B] to recall the sub-band. ” for the offset direction.6 MHz (TH-D7E). [MHz] to switch the offset direction. 14 If the offset transmit frequency falls outside the allowable range. the default on the UHF band is 5 MHz (TH-D7A) or 1.6 MHz). press [F]. 1 Press [F]. TH-D7E Only: If you have selected “ cannot change the default (7. 4 77.5 91. No matter which selection you make here. 22 .9 173. simply pressing [CALL] without pressing the PTT switch causes the transceiver to transmit a 1750 Hz tone.5 107.2 167.7 82.6 241.1 225.4 156. No. Switching the Tone function ON after activating the CTCSS deactivates the CTCSS. simply press [CALL] without pressing the PTT switch.8 No. • “ ” appears when the Tone function is ON.4 100.0 127. 31 32 33 34 35 36 37 38 Freq.9 114. Release [CALL] to quit transmitting.5 85.3 131.3 s Selecting a Tone Frequency 1 Press [F]. 21 22 23 24 25 26 27 28 29 30 Freq.7 218.7 162. (Hz) 97. [2] to select “F–2 (TONE FREQ)”. STA CON 7 PACKET96BCONDUP 9 17 18 19 20 21 22 23 TH-D7E Only: To transmit a 1750 Hz tone.8 203. TH-D7E Only: When you access repeaters that require 1750 Hz tones.5 141. Note: You cannot use the Tone and CTCSS functions simultaneously. 01 02 03 04 05 06 07 08 09 10 Freq.0 71.9 186. You can also make the transceiver remain in the transmit mode for 2 seconds after releasing [CALL].8 No.9 74.4 88.8 123.0 103.8 179. Access Menu 1–5–6 (1750 Hz HOLD) and select “ON”.5 94.7 233. (Hz) 192.5 210.2 151. STA CON 5 2 Press [UP]/ [DWN] to select the appropriate tone frequency. [1] to switch the Tone function ON (or OFF). (Hz) 136.0 79.2 110.8 118.2 No.3 146. you need not activate the Tone function. STA CON 5 7 PACKET96BCONDUP 9 7 PACKET96BCONDUP 9 3 Press [OK] to complete the setting.s Activating Tone Function 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 5 Press [F]. (Hz) 67. 11 12 13 14 15 16 17 18 19 20 Freq.8 250. To obtain an up-to-date band plan for repeater offset direction. exchanges the receive and transmit frequencies.A. 144.S.AUTOMATIC REPEATER OFFSET This function automatically selects an offset direction. 1 2 3 4 5 6 7 8 9 10 11 12 3 Press [UP]/ [DWN] to switch the function ON (default) or OFF.6 145.6 147. 144. [5]. 23 .6 145. pressing [REV] after Automatic Repeater Offset has selected an offset (split) status. 2 Press [1]. and Canada versions This complies with the standard ARRL band plan.0 145. S: Simplex European versions 4 Press [OK] to complete the setting.0 MHz S – S + S – + S – 1 Press [MENU] to enter Menu mode.4 148.0 147.5 146.0 MHz – S 5 Press [MENU] to exit Menu mode.8 146.4 147. according to the frequency that you select on the VHF band.1 146. contact your national Amateur Radio association. [1] to select “1–5–1 (AUTO OFFSET)”. U. 13 14 15 16 17 18 19 20 21 22 23 145. The transceiver is programmed for offset direction as shown below.0 146. However.0 S S: Simplex Note: Automatic Repeater Offset does not function when Reverse is ON. z MH 144.725 MHz TX: 144. x ASC does not function while scanning. 14 • 15 16 17 18 “R” appears when the function is ON. Note: x Pressing the PTT switch causes the ASC indicator to quit blinking.REVERSE FUNCTION 1 2 3 4 5 6 7 8 9 10 AUTOMATIC SIMPLEX CHECK (ASC) While using a repeater. while using a repeater.7 25 MH z 11 TX: 144. You cannot switch Reverse ON or OFF while transmitting. the ASC indicator on the display begins blinking. STA CON 5 The reverse function exchanges a separate receive and transmit frequency.725 MHz 7 PACKET96BCONDUP 9 REV ON • While direct contact is possible. x ASC causes receive audio to be momentarily intermitted every 3 seconds. 25 5. STA CON 5 19 Note: 20 x If pressing [REV] places the transmit frequency outside the allowable 21 22 23 x x x range. x ASC does not function if your transmit and receive frequencies are the same (simplex operation).325 MHz 12 RX: 145. both stations should move to a simplex frequency and free up the repeater. ASC periodically monitors the strength of a signal that you receive directly from the other station.325 MHz RX: 145. If the station’s signal is strong. you can manually check the strength of a signal that you receive directly from the other station. transmission is inhibited. So. x Activating ASC while using Reverse switches Reverse OFF. • “ ” appears when the function is ON. 7 PACKET96BCONDUP 9 24 . Automatic Repeater Offset does not function while Reverse is ON.325 MHz RX: 144.3 14 14 4. Press [REV] (1 s) to switch the function ON. the ASC indicator blinks. If pressing [REV] places the receive frequency outside the allowable range. an error beep sounds and no reversal occurs.325 MHz RX: 145. If the station’s signal is strong enough to allow direct contact without a repeater.725 MHz TX: 144. x If you recall a memory channel or the Call channel that contains Reverse ON status.725 MHz TX: 145. • To quit the function. ASC is switched OFF.725 MHz Press [REV] to switch the Reverse function ON (or 13 OFF). press [REV] momentarily. then pressing the PTT switch causes an error beep to sound. You may use the function to find which tone frequency is required by your local repeater. • Press [ESC] if you do not want to program the identified frequency. the identified frequency appears and blinks. • To reverse scan direction. You may press [F]. 25 . press [OK] (1 s) to activate the function. • The previous frequency display is restored with the Tone function remained ON. press [UP] (upward scan) or [DWN] (downward scan). 11 12 13 14 15 16 17 18 19 20 21 22 23 2 Press [OK] to program the identified frequency in place of the currently set tone frequency. • Press [UP]/ [DWN] while the identified frequency is blinking. • To quit the function. • The Tone function is switched ON. to resume scanning. 1 Press [F].TONE FREQ. press [ESC]. [2] (1 s) to activate the function. [1] to switch the Tone function OFF. ID This function scans through all tone frequencies to identify the incoming tone frequency on a received signal. STA CON 5 1 2 3 4 5 6 7 8 9 10 7 PACKET96BCONDUP 9 • If you access “F–2 (TONE FREQ)” using [UP]/ [DWN] in Function Select mode. • When the tone frequency is identified. A total of 200 memory channels are available for bands A and B. 13 14 15 16 Simplex & repeater channel allows: • Simplex frequency operation • Repeater operation with a standard offset (If an offset direction is stored) 17 Odd-split channel allows: 18 • Repeater operation with a non-standard offset 19 Note: 20 21 22 23 x x Not only can you store data in memory channels. Select either application for each channel depending on 12 the operations you have in mind. Then you need not reprogram those data every time. You can quickly recall a programmed channel by simple operation. but you can also overwrite existing data with new data. you can store frequencies and related data that you often use. You can use each memory channel as a simplex & repeater channel or odd-split channel. If you have recalled a memory channel on the non-current band (A or B). The data listed below can be stored in each memory channel: Parameter Receive frequency Simplex & Repeater Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Odd-split Yes Yes Yes Yes Yes Yes N/A N/A N/A Yes Yes Yes Yes SIMPLEX & REPEATER OR ODD-SPLIT MEMORY CHANNEL? Transmit frequency Tone frequency Tone ON CTCSS frequency CTCSS ON Offset direction Offset frequency Reverse ON Frequency step size Memory channel lockout Memory channel name AM/FM mode selection (TH-D7A only) Yes: Can be stored in memory. N/A: Cannot be stored in memory. you cannot select the same channel on the current band to program data. Store only one 10 frequency to use as a simplex & repeater channel or two 11 separate frequencies to use as an odd-split channel.MEMORY CHANNELS 1 2 3 4 5 6 7 8 9 In memory channels. 26 . 2 Press [UP]/ [DWN] to select the desired transmit frequency.). • A memory channel number appears and blinks. 2 Press [VFO]. 5 Press [PTT]+[OK]. [MR]. if the channel contains data. [MR]. To confirm the transmit frequency. if necessary {page 22} • Tone frequency. 4 Press [UP]/ [DWN] to select the memory channel programmed in step 1.. 3 Press [UP]/ [DWN] to select the desired frequency. you may select other related data (CTCSS ON. “ instead. 1 Store the desired receive frequency and related data by using the procedure given for simplex or standard repeater frequencies. • “ ” indicates the current channel is empty. “+” and “–” appear on the display. if necessary {page 22} If storing a simplex frequency. you can operate on those repeaters without programming the offset frequency and direction. STA CON 5 ” appears • The transmit frequency is stored in the memory channel. • You can also directly enter digits from the keypad. etc. 27 . Transmit Offset status and Reverse status are not stored in an oddsplit memory channel. STORING ODD-SPLIT REPEATER FREQUENCIES Some repeaters use a receive and transmit frequency pair with a non-standard offset. 1 2 3 4 5 6 7 8 9 10 11 12 4 If storing a standard repeater frequency. CTCSS freq. 5 Press [F]. 3 Press [F]. 13 14 Note: x x 7 PACKET96BCONDUP 9 When you recall an odd-split memory channel. 15 16 17 18 19 20 21 22 23 6 Press [UP]/ [DWN] to select the desired memory channel. See page 45.STORING SIMPLEX FREQUENCIES OR STANDARD REPEATER FREQUENCIES 1 Select the desired band. 7 Press [OK]. press [REV]. select the following data: • Offset direction {page 21} • Tone ON. If you store two separate frequencies in a memory channel. 3 Press [MR]+ POWER ON. are cleared once you select another channel or the VFO mode. [0]. you may program data such as Tone or CTCSS. [0]. • To restore VFO mode. • The memory channel used last is recalled. Press [REV] to display the transmit frequency. 1 Select the desired band. for 15 16 17 18 19 20 21 22 23 Note: x When you recall an odd-split memory channel. overwrite the channel contents {page 27}. • You cannot recall an empty memory channel. In Memory Recall mode press [ENT]. press [ENT]. press [VFO]. 2 Switch OFF the power to the transceiver. [3]. You can also recall a memory channel by direct entry example. 1 Recall the desired memory channel. • To quit clearing the memory channel. press [ESC]. 14 then enter the channel number. x After recalling a memory channel. you cannot select the same channel on the current band to clear.RECALLING A MEMORY CHANNEL 1 2 3 4 5 6 7 8 9 10 11 12 CLEARING A MEMORY CHANNEL Use the following procedure to clear an individual memory channel. 3 Press [UP]/ [DWN] to select the desired memory channel. 28 . 4 Press [MR] again. To permanently store the data. • The contents of the memory channel are erased. These settings. “+” and “–” appear on the display. Full Reset {page 32} is a quick way to clear all memory channels. 2 Press [MR] to enter Memory Recall mode. 13 from the keypad. • A confirmation message appears. To recall channel 3. however. Note: If you have recalled a memory channel on the non-current band (A or B). [9] to select “F–9 (MEMORY NAME)”. 4 Press [OK]. When you recall a named memory channel. x You can assign names only to memory channels in which you have stored frequencies and related data. x The stored names can be overwritten by repeating steps 1 to 5. Press [ENT] to switch among the special ASCII characters. Names can be call signs. After storing a memory name. Press [DUAL] to switch 0 and space. C. b. c. For example. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 3 Press [UP]/ [DWN] to select the first digit. • The first digit blinks. 5 Repeat steps 3 and 4 to enter up to 8 digits. • To complete programming after entering less than 8 digits. pressing [MN<->f] switches the display between the memory name and frequency. B. but you cannot name the Call channel {page 30}. You can also use the keypad to enter alphanumeric characters in step 3. names of people. • The cursor moves to the next digit. 2 Press [F]. each press of [TNC] switches entry as A. Note: x You can also name the Program Scan {page 37} and DTMF {page 42} channels. a. then 2. cities. • Each press of [ESC] causes the cursor to move backward. • Pressing [A/B] deletes the digit at which the cursor is blinking. 1 Recall the desired memory channel.NAMING A MEMORY CHANNEL You can name memory channels using up to 8 alphanumeric characters. x The stored names also are erased by clearing memory channels. repeater names. its name appears on the display instead of the stored frequency. 29 . • You can enter alphanumeric characters plus special ASCII characters. • Pressing [OK] after selecting the 8th digit completes the programming. etc. press [OK] twice. you may use the Call channel as an emergency channel within your group. select a receive frequency. x To store data other than frequencies. In this case. [CALL]. select the data in step 3 not step 5. 7 Press [PTT]+[CALL]. 2 Press [CALL] to recall the Call channel.000 MHz for the UHF band. • The selected frequency and related data are stored in the Call channel. 2 Press [VFO]. etc. • The previous mode is restored. s Recalling the Call Channel 1 Select the desired band. press [CALL] again. The default frequency stored in the Call channel is 144. s Reprogramming the Call Channel 1 Select the desired band. Note: Unlike channels 0 to 199 the call channel cannot be cleared. 5 Select the desired transmit frequency.). The Call channel can always be selected quickly no matter what mode the transceiver is in. For instance. 3 Select the desired frequency and related data (Tone. proceed to the next step. • “C” appears. Note: x Transmit Offset status and Reverse status are not stored in an odd-split Call channel. The Call channel can be reprogrammed either as a simplex & repeater or odd-split channel. 4 Press [F]. • When you program the Call channel as an odd-split channel. 6 Press [F].000 MHz for the VHF band and 440.CALL CHANNEL (TH-D7A ONLY) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 • To restore the previous mode. 30 . • The transmit frequency is stored in the Call channel. CTCSS. To also store a transmit frequency. the Call/VFO scan {page 38} will be useful. and the previous mode is restored. x If you recall the Call channel in step 1. 1 2 3 4 5 6 7 8 Note: You cannot switch this function ON if you have not used both bands A and B to store frequencies. you can use only the following functions: • The entire contents of the memory channel or the Call channel are copied to the VFO. then press [F]. To transfer a transmit frequency. press [REV]. x Lockout status and memory names are not copied from a memory channel to the VFO. near the frequency stored in a memory channel or the Call channel. the transceiver displays only memory channel numbers (or memory names if stored) instead of frequencies. [VFO]. In this case first transfer the contents of a memory channel or the Call channel to the VFO. 1 Recall the desired memory channel or the Call channel. 2 Press [F]. 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 When in Channel Display mode. however. CHANNEL DISPLAY When in this mode. Note: x A transmit frequency from an odd-split memory channel or odd-split Call channel is not transferred to the VFO. The frequency. [VFO]. is changed by one step.MEMORY-TO-VFO TRANSFER You may sometimes want to search for other stations or a clear frequency. Power ON/OFF Squelch Level Adjust Transmit Memory Channel Select Lamp ON Offset Direction Select Full Duplex Partial/ Full Reset Transceiver Lock Band Display Blank DTMF Number (Stored) Transmit Band Select Monitor Transmit Power Select Direct Memory Channel Entry Lamp ON Latch Reverse Memory Scan Tone Alert Audio Balance Select 1750 Hz Tone (TH-D7E) 31 . simply pressing [UP]/ [DWN] also transfers the contents to the VFO. Press [A/B]+ POWER ON to switch the function ON (or OFF). TH-D7A TH-D7E 144. Freq. Use Full Reset to initialize all settings that you have customized.PARTIAL OR FULL RESET? 1 2 3 4 5 6 7 8 9 10 11 Partial Reset nor Full Reset. Partial (VFO) Reset does not initialize the following settings: Memory channels Call channel DTMF channels Memory channel lockout Power-ON message Menu 3–1 ~ 3–6 (SSTV) Menu 2–1/ 2–3 ~ 2–8/ 2–A/ 2–B (APRS) Menu 4–1 ~ 4–3 (SKY CMD)(TH-D7A only) • You can also use Menu 1–5–7 (TH-D7A) or Menu 1–5–9 (TH-D7E). 440. 88.5 kHz Tone Freq. 12 VHF Band Defaults 13 14 15 16 17 18 UHF Band Defaults 19 20 21 22 23 Note: While using the Transceiver Lock function. Step Size 5 kHz 12.000 MHz 144.5 Hz 4 Press [UP]/ [DWN] to select Yes (or No). 32 . initializing the transceiver may resolve the problem. If your transceiver seems to be malfunctioning. 88. • A confirmation message appears.5 Hz 88. 2 Press [UP]/ [DWN] to select Partial (VFO) Reset or Full Reset. 5 Press [OK]. • “RESET?” appears. Step Size 25 kHz 25 kHz Tone Freq.5 Hz 88.000 MHz Freq.5 Hz 3 Press [OK].000 MHz 430.000 MHz Version TH-D7A TH-D7E VFO Freq. you cannot perform 1 Press [F]+ POWER ON. Version VFO Freq. Becoming comfortable with all types of Scan will increase your operating efficiency. x You cannot start Scan while Tone Alert is ON. 33 . 0 TH-D7A only Stop Note: x Adjust the squelch level before using Scan.SCAN Scan is a useful feature for hands-off monitoring of your favorite frequencies. z MH This transceiver provides the following types of scans: Scan Type VFO Scan Memory Scan MHz Scan Program Scan Call/VFO Scan 1 Call/Memory Scan 1 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Scan Range All frequencies tunable on the band Frequencies stored in the memory channels All frequencies within a 1 MHz range All frequencies in the range selected on the band Call channel plus the current VFO frequency Call channel plus the selected memory channel 1 43 45. Scan stops for any signal received. x While using CTCSS. Selecting a squelch level too low could cause Scan to stop immediately. x Starting Scan switches OFF the Automatic Simplex Check. you will hear audio only when the signal contains the same CTCSS tone that you selected. however. 5 Press [MENU] to exit Menu mode. Seek mode The transceiver remains on a busy frequency (or memory channel) even after the signal drops out and does not automatically resume scanning. and then continues to scan even if the signal is still present. Note: To temporarily stop scanning and monitor weak signals. It then continues scanning according to which resume mode you select.SELECTING SCAN RESUME METHOD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 • 15 16 17 19 20 21 22 23 1 Press [MENU] to enter Menu mode. • Time-Operated mode The transceiver remains on a busy frequency (or memory channel) for approximately 5 seconds. 18 hold [MONI]. • Carrier-Operated mode The transceiver remains on a busy frequency (or memory channel) until the signal drops out. You can choose one of the following modes. press and 3 Press [UP]/ [DWN] to select Time-Operated (default). 4 Press [OK] to complete the setting. There is a 2 second delay between signal drop-out and scan resumption. or Seek. 2 Press [1]. Release the key to resume scanning. [5]. Carrier-Operated. 34 . The transceiver stops scanning at a frequency (or memory channel) on which a signal is detected. The default is Time-operated mode. [2] to select “1–5–2 (SCAN RESUME)”. While Scan is being interrupted.VFO SCAN VFO Scan monitors all frequencies tunable on the band. 2 Press [VFO] (1 s). 2 Press [MR] (1 s). • To reverse scan direction. 11 12 13 14 15 16 17 18 19 20 21 22 23 3 To quit VFO Scan. 35 . • Scan starts at the frequency currently displayed. press [UP] (upward scan) or [DWN] (downward scan). x The L0 to L9 and U0 to U9 memory channels are not scanned. the channel number blinks. x You can also start Memory Scan when in Channel Display mode. press [ESC]. 1 2 3 4 5 6 7 8 9 10 1 Select the desired band. using the current frequency step size. press [ESC]. Note: x On the current band at least 2 or more memory channels must contain data and must not be locked out. • The 1 MHz decimal blinks while scanning is in progress. 3 To quit Memory Scan. 1 Select the desired band. • Scan starts with the channel last recalled. • To reverse scan direction. • The 1 MHz decimal blinks while scanning is in progress. press [UP] (upward scan) or [DWN] (downward scan). MEMORY SCAN Use Memory Scan to monitor all memory channels programmed with frequency data. 5 To quit MHz Scan. STA CON 5 MHz SCAN MHz Scan monitors a 1 MHz segment of the band. x If you have recalled a memory channel on the non-current band (A or B). 1 Recall the desired memory channel.s Locking Out a Memory Channel 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Note: x The L0 to L9 and U0 to U9 memory channels cannot be locked out. 2 Press [VFO] to select VFO mode. press [UP] (upward scan) or [DWN] (downward scan). if the current frequency is 145. press [ESC]. • Scan starts at the frequency currently displayed.995 MHz. Select memory channels that you prefer not to monitor while scanning. 4 Press [MHz] (1 s) to start MHz Scan. • To reverse scan direction. you cannot select the same channel on the current band to lock out. PACKET96BCONDUP 9 7 1 Select the desired band. then the scan range would be from 145.400 MHz. 3 Select a frequency within the desired 1 MHz segment. using the current frequency step size.000 MHz to 145. 36 . • The 1 MHz decimal blinks while scanning is in progress. • A star appears above the channel number when the channel is locked out. The current 1 MHz digit determines the limits of the scan. 2 Press [F]. [0] to switch Lockout ON (or OFF). The exact upper limit depends on the current frequency step size. For example. • If you have selected for example L3 in step 5. 10 Press [OK]. x The lower and upper frequency step sizes must be equal. 2 Press [VFO]. x The lower and upper limits must be selected on the same band. Note: x The lower limit must be lower in frequency than the upper limit. 6 Press [OK]. then select the L and U channels. 8 Press [F]. 1 2 3 4 5 6 7 8 9 10 s Setting Scan Limits You can store up to 10 scan ranges in memory channels L0/U0 to L9/U9. [MR]. 37 . 1 Select the desired band. press [MR]. select U3. 9 Press [UP]/ [DWN] to select a matching channel in the range U0 to U9. 4 Press [F]. [MR]. • The lower limit is stored in the channel. 3 Select the desired frequency as the lower limit.PROGRAM SCAN Program Scan is identical with VFO Scan except that you select the frequency range of the scan. • The upper limit is stored in the channel. 7 Select the desired frequency as the upper limit. 5 Press [UP]/ [DWN] to select a channel in the range L0 to L9. 11 12 13 14 15 16 17 18 19 20 21 22 23 To confirm the stored scan limits. 5 To quit Program Scan. • The Call channel on the same band as of the selected memory channel is used for Scan. press [ESC]. • The 1 MHz decimal blinks while scanning is in progress. 2 Press [CALL] (1 s) to start Call/Memory Scan. • Scan starts at the frequency currently displayed. 5 To quit Call/VFO Scan. 4 Press [CALL] (1 s) to start Call/VFO Scan. 2 Press [VFO] . you cannot use Program Scan. Note: The memory channel last used is scanned even if it has been locked out. 4 Press [VFO] (1 s). • The 1 MHz decimal blinks while scanning is in progress. 1 Select the appropriate band. Note: x If the step size of the current VFO frequency differs from that of the programmed frequencies.s Using Program Scan 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 CALL/VFO SCAN (TH-D7A ONLY) Use Call/VFO Scan to monitor both the Call channel and the current VFO frequency on the selected band. CALL/MEMORY SCAN (TH-D7A ONLY) Use Call/Memory Scan to monitor both the Call channel and the desired memory channel. 3 To quit Call/Memory Scan. 2 Press [VFO]. the range stored in the smallest channel number is used. 3 Select the desired frequency. press [UP] (upward scan) or [DWN] (downward scan). press [ESC]. • To reverse scan direction. 38 . 1 Select the desired band. x If the current VFO frequency is within more than one programmed scan range. 3 Select a frequency equal to or between the programmed scan limits. you cannot use Program Scan. 1 Recall the desired memory channel. • The 1 MHz decimal blinks while scanning is in progress. press [ESC]. x If the step size differs between the lower limit and the upper limit. 5 Hz • The selectable frequencies are the same as for the tone frequency.0 Hz d 4 Press [OK] to complete the setting. press [F]. [4] to select “F–4 (CTCSS FREQ)”. [A/B] to recall the sub-band. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 2 Press [F]. Received 3 Press [UP]/ [DWN] to select the appropriate CTCSS frequency. SELECTING A CTCSS FREQUENCY 1 Press [A/B] to select band A or B.5 Hz CTCSS: OFF 23 39 . A CTCSS tone is subaudible and is selectable from among the 38 standard tone frequencies. The Continuous Tone Coded Squelch System (CTCSS) allows you to ignore (not hear) unwanted calls from other persons who are using the same frequency. First select the same CTCSS tone as selected by the other persons in your group. See the table given in “Selecting a Tone Frequency” {page 22}. 19 20 21 22 CTCSS frequency: 82. Note: CTCSS does not cause your conversation to be private.CONTINUOUS TONE CODED SQUELCH SYSTEM (CTCSS) You may sometimes want to hear calls from only specific persons. • If necessary. N re ot ce ive d N re ot ce ive CTCSS frequency: 100. It only relieves you from listening to unwanted conversations. CTCSS frequency: 82. • When the CTCSS frequency is identified. press [OK] (1 s) to activate the function. then speak into the microphone. [4] (1 s) to activate the function. x If you select a high CTCSS frequency. [A/B] to recall the sub-band. • If necessary. • To quit the function. receiving audio or noise that contains the same frequency portions may cause CTCSS to function incorrectly. STA CON 5 1 Press [A/B] to select band A or B. • If you access “F–4 (CTCSS FREQ)” using [UP]/ [DWN] in Function Select mode. press and hold the PTT 12 switch. 1 Press [F].USING CTCSS 1 2 3 4 5 6 5 CTCSS FREQ. • Press [UP]/ [DWN] while the identified frequency is blinking. To prevent noise from causing this problem. select an appropriate squelch level {page 8}. 40 . To answer the call. • To reverse scan direction. 2 Press [OK] to program the identified frequency in place of the currently set CTCSS frequency. • The CTCSS function is switched ON. • Press [ESC] if you do not want to program the identified frequency. the identified frequency appears and blinks. press [ESC]. Switching the CTCSS function ON after activating the Tone function deactivates the Tone function. to resume scanning. ID This function scans through all CTCSS frequencies to identify the incoming CTCSS frequency on a received signal. STA CON 7 PACKET96BCONDUP 9 7 8 9 10 7 PACKET96BCONDUP 9 You will hear calls only when the selected tone is 11 received. • “CT” appears when CTCSS is ON. • The previous frequency display is restored with the CTCSS function remained ON. You may find it useful when you cannot recall the CTCSS frequency that the other persons in your group are using. press [F]. 2 Press [F]. [3] to switch the CTCSS function ON (or OFF). press [UP] (upward scan) or [DWN] (downward scan). Note: Received signals are audible while scanning is in progress. 13 14 15 16 17 18 19 20 21 22 23 Note: x You cannot use the CTCSS and Tone functions simultaneously. DUAL TONE MULTI-FREQUENCY (DTMF) FUNCTIONS The keys on the keypad also function as DTMF keys; the 12 keys found on a push-button telephone plus 4 additional keys (A, B, C, D). This transceiver provides 10 dedicated memory channels. You can store a DTMF number (16 digits max.) with a memory name (8 digits max.) in each of the channels to recall later for a quick call. Some repeaters in the U.S.A. and Canada offer a service called Autopatch. You can access the public telephone network via such a repeater by sending DTMF tones. For further information, consult your local repeater reference. s TX Hold This function makes the transceiver remain in transmit mode for 2 seconds after you release each key. So you can release the PTT switch after beginning to press keys. 1 Press [MENU] to enter Menu mode. 2 Press [1], [3], [3] to select “1–3–3 (TX HOLD)”. 1 2 3 4 5 6 7 8 9 10 11 12 MANUAL DIALING Manual Dialing requires only two steps to send DTMF tones. 1 Press and hold the PTT switch. 2 Press the keys in sequence on the keypad to send DTMF tones. • The corresponding DTMF tones are transmitted. 3 Press [UP]/ [DWN] to switch the function ON (or OFF). 13 14 15 16 17 18 19 20 21 22 23 Freq. (Hz) 697 770 852 941 1209 1 4 7 1336 2 5 8 0 1477 3 6 9 1633 A B C D 4 Press [OK] to complete the setting. 5 Press [MENU] to exit Menu mode. 41 AUTOMATIC DIALER 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 7 Repeat steps 5 and 6 to enter up to 8 digits. • Pressing [OK] after selecting the 8th digit causes the cursor to move to the start of the next field. If you use the 10 dedicated memory channels to store DTMF numbers, you need not remember a long string of digits. s Storing a DTMF Number in Memory Note: Audible DTMF tones from other transceivers near you (or from your own speaker) may be picked up by your microphone. If so, you may fail to correctly program a DTMF number. 1 Press [MENU] to enter Menu mode. 2 Press [1], [3], [1] to select “1–3–1 (STORE)”. 3 Press [UP]/ [DWN] to select from channel 0 to 9. 4 Press [OK]. • The display for entering a memory name appears; the first digit blinks. • To skip naming the channel, press [OK] again. You can jump to step 8. • To complete programming the name after entering less than 8 digits, press [OK] twice. • Each press of [ESC] causes the cursor to move backward. • Pressing [A/B] deletes the digit at which the cursor is blinking. 8 Press the keys in sequence on the keypad to enter a DTMF number with up to 16 digits. • You may press [UP]/ [DWN] then [OK] to select each digit. Select a space if you want to put a pause. 9 Press [OK] to complete the programming. 10 Press [MENU] to exit Menu mode. You can confirm the stored DTMF number by using steps 1 to 3. 5 Press [UP]/ [DWN] to select a character. • You can enter alphanumeric characters plus special ASCII characters. 6 Press [OK]. • The cursor moves to the next digit. You can also use the keypad to enter alphanumeric characters in step 5. For example, each press of [TNC] switches entry as A, B, C, a, b, c, then 2. Press [ENT] to switch among the special ASCII characters. 42 s Transmitting a Stored DTMF Number 1 Press [PTT]+[MENU]. STA CON 5 7 PACKET96BCONDUP 9 This transceiver allows you to switch the DTMF number transmission speed between Fast (default) and Slow. If a repeater cannot respond to the fast speed, access Menu 1–3–2 (TX SPEED) and select “Slow”. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 2 Release only [MENU], then press [UP]/ [DWN] to select the desired DTMF memory channel. 3 While still holding [PTT], press [MENU] again. • The number stored in the channel scrolls across the display accompanied by DTMF tones from the speaker. • After transmission, the frequency display is restored. You can also change pause duration stored in memory channels; the default is 500 msec. Access Menu 1–3–4 (PAUSE). The selectable pauses are 100, 250, 500, 750, 1000, 1500, and 2000 msec. If you need not confirm the memory channel contents, press [0] to [9] instead of [UP]/ [DWN] in step 2 to select a channel number. The stored DTMF number will be immediately transmitted. You need not press [MENU] in step 3. 43 Memory Channel [0] Lockout ON/ OFF [5] [6] [7] [8] [9] Offset freq. select AM/ FM switch 1 Programmable VFO range select Freq. • “PF 1”. • Pressing [ENT]. Press [ENT] first. • Pressing the PTT switch assigns the function that switches between VFO and Memory Recall mode. 1 Press Mic [1]. [0] to [9] to assign the functions that are selectable in Function Select mode. step size select Memory name store [1] 2 Press a key on the transceiver depending on the function you want to assign. press [F] first (ex. [F]. • To assign the second function (printed in purple). [0] to [9] allows you to recall memory channel 0 to 9.MICROPHONE CONTROL 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 The optional SMC-33 or SMC-34 speaker microphone has 3 Programmable Function (PF) keys on its top. select CTCSS ON/ OFF CTCSS freq. you cannot reprogram the Programmable Function keys. First connect the optional speaker microphone to this transceiver. The defaults on the PF keys are as follows: Mic [1]: [A/B] Mic [2]: VFO/ Memory Recall mode switch Mic [3]: [CALL] The key functions you can assign are shown below: LA NP NI MO Press [F] first. • Press [F]. [VFO]). or “PF 3” appears. x If the LOCK on the speaker microphone is ON. You can assign these keys the transceiver key functions that you frequently use. “PF 2”. or [3]+ POWER ON depending on which key you want to reprogram. [2]. • Pressing a single key on the keypad assigns only the function printed on the top of the key. LA NP SQ L TH-D7A only Press [F] first. select [2] [3] [4] TH-D7A only Note: x Turn OFF the transceiver power before connecting the optional speaker microphone. 44 . 1 Tone ON/ OFF Tone freq. : 145. enter for the 1 MHz digit and press [MHz]. Previous freq.350 MHz 45 . Note: x The 1 kHz and subsequent digits are corrected according to which key is pressed for the 1 kHz digit. you may enter a VHF frequency on band B where a UHF band is in use.: 145. enter for the 10 MHz and 1 MHz digits and press [MHz]. Previous freq. x You cannot enter a frequency in a band which cannot be recalled on the current band. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 2 Press [VFO]. press [F]. • If necessary. Previous freq. the new data is accepted for the digits entered and 0 is programmed for the digits not yet entered. To omit entry of the 100 MHz digit. • The display for Direct Frequency Entry appears.350 MHz Note: The 1 kHz and subsequent digits may be corrected depending on combinations of the previous frequency and the current frequency step size.350 MHz To omit entry of the 100 MHz and 10 MHz digits.AUXILIARY FUNCTIONS DIRECT FREQUENCY ENTRY If the desired operating frequency is far from the current frequency. For example. 3 Press [ENT]. the new data is accepted for the digits entered and the previous data remains unchanged for the digits not yet entered.: 145.: 145. The previous data remains unchanged for the 100 MHz and 10 MHz digits. • You can also enter a different band frequency from the current band. x Entering a digit that is outside the allowable range causes the nearest digit within range to be displayed. Previous freq. The previous data remains unchanged for the 100 MHz digit. using the keypad is the quickest way to change frequency. If you press [VFO] while entering a frequency.350 MHz 7 PACKET96BCONDUP 9 4 Press the numeric keys in sequence on the keypad. 1 Press [A/B] to select band A or B. [A/B] to recall the sub-band. STA CON 5 If you press [ENT] while entering a frequency. 7 PACKET96BCONDUP 9 4 Press [UP]/ [DWN] to select the desired lower frequency limit.5. [8] to select “F–8 (STEP)”. 1 Press [A/B] to select band A or B. 50. 6 Press [UP]/ [DWN] to select the desired upper frequency limit. 22 Note: Changing between step sizes may correct the displayed 23 frequency. STA CON 3 Press [UP]/ [DWN] to select the desired step size.25. set upper and lower limits for frequencies that are selectable using the Tuning control or [UP]/ [DWN]. [A/B] to recall the sub-band. 21 4 Press [OK] to complete the setting. [A/B] to recall the sub-band. x The exact 100 kHz and subsequent digits of the upper limit depend on the frequency step size selected. For example.9875 MHz. 1 Press [A/B] to select band A or B. STA CON 2 Press [VFO]. • The selectable step sizes are 5. 6. The default step size on the VHF band is 5 kHz (TH-D7A) or 12. For example. changing to a 12. press [F]. Note: x You cannot program the 100 kHz and subsequent digits.995 MHz is displayed with a 5 kHz step size selected.000 MHz to 146. 2 Press [F]. if 144. 3 Press [F]. press [F]. • If necessary. PACKET96BCONDUP 9 5 7 PACKET96BCONDUP 9 17 18 19 20 5 7 5 Press [OK].CHANGING FREQUENCY STEP SIZE 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 STA CON 5 PROGRAMMABLE VFO If you always check frequencies within a certain range. 25. • The current upper frequency limit blinks. • The current lower frequency limit blinks. 10. 30. 12. 46 . • If necessary. and 100 kHz. the tunable range will be from 145.5 kHz (TH-D7E). The default on the UHF band is 25 kHz no matter which market version. [7] to select “F–7 (PROGRAM VFO)”. 15. if you select 145 MHz for the lower limit and 146 MHz for the upper limit. 7 Press [OK]. 20. Choosing the correct step size is essential in order to select your exact receive frequency using the Tuning control or [UP]/ [DWN].5 kHz step size corrects the displayed frequency to 144.995 MHz. APO does not turn the power OFF. In addition. Note: x While Tone Alert is ON. • A bell icon appears when Tone Alert is ON. Those settings are described in “APRS” sections {pages 63 and 77}. • Each time a new signal is received. • Pressing the PTT switch while the bell icon is blinking switches Tone Alert OFF. it shows the number of hours and minutes elapsed after signals were received. 1 Press [A/B] to select band A or B. You can also switch this function OFF.TONE ALERT Tone Alert provides an audible alarm when signals are received on the frequency you are monitoring. press and hold [MONI]. To hear receive audio. the time resets to 00. If you use Tone Alert with CTCSS. press [F]. 2 Press [F]. • If necessary. an alarm sounds and the bell icon starts blinking. there is no speaker output when a signal is received. The default is “ALL”. STA CON 5 7 PACKET96BCONDUP 9 • When a signal is received. In Menu 1–5–3 you can also select “KEY” and “KEY+NEW DATA”. it alarms only when a received CTCSS tone matches the tone you selected. [ENT] to switch Tone Alert ON (or OFF). Access Menu 1–5–3 (BEEP) and select “OFF”. counting stops. 16 17 18 19 20 21 22 23 47 . [A/B] to recall the sub-band. x When Tone Alert is ON. x When Tone Alert is ON. you can use only the following functions: • Lamp ON • Lamp Latch ON • Monitor • Band A/B Select • Squelch Level Select 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 BEEP ON/OFF The transceiver beeps each time you press a key on the keypad. • When 99 hours and 59 minutes pass after a signal is received.00. 16 17 LAMP FUNCTION 18 You can illuminate the transceiver display and keypad by 19 pressing [LAMP]. for example between daytime and nighttime. 1 Press [BAL]. Pressing any key other than [LAMP] while the 21 display is lit restarts the 5 second timer. 2 Press [DUAL] to switch the function ON (or OFF). The light . This saves power consumption and makes it simpler to read the information you need. quit frequency display on the unused band. Access Menu 1–1–2 (CONTRAST) and select the contrast from 16 levels. remains ON until you press [F]. 1 Press [A/B] to select band A or B. [LAMP]. 48 23 To latch the light ON. you may sometimes feel that audio output on either band is too noisy. pressing 22 releasing [LAMP]. While simultaneously receiving on 2 bands. BLANKING A BAND DISPLAY If you have no plans to use band A or B. press [F]. the light goes OFF if no other key is [LAMP] turns OFF the light immediately. Approximately 5 seconds after 20 pressed. The default is level 8. use this function to select the optimum display contrast.ADJUSTING VOLUME BALANCE 1 2 3 4 5 6 7 8 9 10 2 Press [UP]/ [DWN] to change the setting. When you find the display is not clear. • The balance scale appears with a blinking cursor. 15 3 Press [OK] to complete the setting. You can adjust the volume on the noisy band. 11 12 13 Band A Max 14 Band B Mute Max Att Max Max Att Max Max: Maximum Mute Mute: Muted Max Att: Attenuated ADJUSTING DISPLAY CONTRAST The display visibility changes depending on ambient conditions. • The non-current band will be blanked. [LAMP] again. selecting OFF switches the function OFF. After the predetermined time passes with no operations.0 second. 0. or whether any control has been turned.0. 1 2 3 4 5 6 7 8 9 10 11 12 Note: x If a signal is received while APO is ON. and 5. 4.0. x The APO timer does not operate while Tone Alert or any scan is being used.AUTOMATIC POWER OFF (APO) Automatic Power Off is a background function that monitors whether any keys have been pressed. The default is 1.8.2. 1 minute before the power turns OFF. the timer begins counting again from 0. 3.0. However. 0. “APO” blinks and a series of warning tones sound. BATTERY SAVER Battery Saver repeats switching the receive circuit ON and OFF at a certain interval when no signal is present and no key is pressed for approximately 10 seconds. 0. 2. This function becomes passive whenever a signal is received or any key is pressed.6.0. Access Menu 1–2–1 (BAT SAVER) to select the desired interval (power OFF duration). 1. or OFF. APO turns OFF the power.0 seconds plus OFF. • The selectable intervals are 0. 60 minutes. 13 14 15 16 17 18 19 20 21 22 23 49 .4. Access Menu 1–2–2 (APO) and select 30 minutes (default). 5 7 PACKET96BCONDUP 9 4 Press [OK]. [1]. 2 Press [1].POWER-ON MESSAGE 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 6 Press [MENU] to exit Menu mode. each press of [TNC] switches entry as A. “HELLO !!” appears and stays for approximately 1 second. c. B. • Pressing [A/B] deletes the digit at which the cursor is blinking. • A key icon appears when the function is ON. Press [ENT] to switch among the special ASCII characters. • The display for entering a message appears. Each time you switch the transceiver ON. • You can enter alphanumeric characters plus special ASCII characters. Access Menu 1–5–4 (TUNE ENABLE) and select “ON”. You may want to use the Tuning control or [UP]/ [DWN] in Transceiver Lock mode. a. 50 . STA CON 3 Press [UP]/ [DWN] to select a character. the first digit blinks. You can also use the keypad to enter alphanumeric characters in step 3. 5 Repeat steps 3 and 4 to enter up to 8 digits. • To complete programming the message after entering less than 8 digits. For example. press [OK] twice. 1 Press [MENU] to enter Menu mode. then 2. Press [DUAL] to switch 0 and space. You can program your favorite message in place of the factory default. C. • Each press of [ESC] causes the cursor to move backward. b. Press [F] (1 s) to switch the function ON (or OFF). • The cursor moves to the next digit. • Pressing [OK] after selecting the 8th digit completes the programming. [1] to select “1–1–1 (PWR ON MSG)”. or unauthorized individuals from changing the transceiver settings. TRANSCEIVER LOCK This function prevents accidental changes. x Switching ON the AIP also affects the VHF sub-band on band B. Access Menu 1–5–6 (TH-D7A) or Menu 1–5–8 (TH-D7E) and select “ON”. 2 Press [F]. 21 22 23 51 . You may use this function when operating on the VHF band. ADVANCED INTERCEPT POINT (AIP) The VHF band is often crowded in urban areas. Access Menu 1–5–7 (144Tx NARROW) and select “ON”. SWITCHING AM/FM MODE (TH-D7A ONLY) This transceiver allows you to select AM or FM mode to receive on the 118 MHz band.TX INHIBIT You can disable the transmit function to prevent unauthorized individuals from transmitting. [6] to switch between AM and FM. The default is AM. Access Menu 1–5–5 (TX INHIBIT) and select “ON”. SWITCHING TX DEVIATION (TH-D7E ONLY) This transceiver is capable of switching the VHF band to narrow transmit deviation. • The 1 MHz decimal becomes long when AM mode is selected. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Note: When using the VHF band to transmit packets. AIP helps eliminate interference and reduce audio distortion caused by intermodulation. • Pressing the PTT switch after switching TX Inhibit ON causes the transceiver to generate an error beep and display “TX INHIBIT!”. Note: x This transceiver does not allow you to use the AIP on the UHF band. 1 Select the 118 MHz band. do not switch the function ON. or to eliminate the risk of accidentally transmitting by yourself. Packets can be transmitted on radio waves as well as on communications lines. x Packet operation. First find out the call signs and frequencies used by your local PBBSs. A variety of packet applications developed by hams include packet bulletin board systems (PBBSs). This transceiver has a built-in TNC.PACKET OPERATION 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Packet is a unit of data transmitted as a whole from one computer to another on a network. easily affected by transmit and receive conditions. A TNC converts packets to audio tones and vice versa as one of its tasks. requires a full-scale S-meter reading for reliable communication. x This transceiver is incapable of functioning as a digipeater. Thousands of PBBSs. PBBSs are created and maintained by volunteers called a System Operator (SysOp). relay e-mail to its intended destination around the world. PBBS Mail box Bulletin board Data library 23 TH-D7E Only: When using the VHF band to transmit packets. do not 52 . Note: x Not all functions available via conventional TNCs are supported by the TNC built in this transceiver. or obtain various useful information. x “ ” indicates packets to be transmitted still remain in the buffer. select the narrow transmit deviation {page 51}. which have formed a worldwide network. all you need is a terminal node controller (TNC). Besides a transceiver and a computer. communication errors are frequent. When the S-meter reads less than maximum during 9600 bps operation. Reference material for starting packet operation should be available at any store that handles Amateur Radio equipment. download a file. You may access one of your local PBBSs to send e-mail. 25 protocol. When in Converse mode. It then converts packets to audio tones which the transceiver can transmit. contact your authorized KENWOOD dealer. you can also type CONV or K instead. The TNC mainly functions in Command or Converse mode. The TNC accepts data from your personal computer and assembles it into packets. Press [OK] to complete the setting. A “cmd:” prompt appears on the computer screen. press [Ctrl]+[C] on the keyboard to restore the Command mode. Press [UP]/ [DWN] to select “UPPER”. TXD1 GND3 1 2 3 w To RXD on PC To TXD on PC To GND on PC Note: When the built-in TNC is ON. The TNC also takes audio tones from the transceiver. You can type commands from the computer keyboard to change the settings on the TNC. First learn the difference between these two modes. 2. the TNC enters this mode. 53 . type an appropriate command and if necessary a message. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 To PC jack PG-4W To COM port • Command mode When you select Packet mode. On the computer keyboard. For the commands supported by the built-in TNC. For this cable. type CONVERSE to restore the Converse mode. OPERATING TNC This transceiver has a built-in TNC which conforms to the AX. some internal frequency relationships may induce an internal heterodyne and cause the squelch to be opened unexpectedly. and checks for errors in the data. see “TNC COMMANDS LIST” on page 99. When in Command mode. then press [Enter] or [Return]. Press [TNC]+ POWER ON to access “BEAT SHIFT”. This protocol is used for communications between TNCs. The default is “NORMAL”. Note: Turn OFF the transceiver power before making the connection. converts them to data for the computer. Shifting the interference will solve this problem. t e Pin Name GND TXD RXD • Converse mode The TNC enters this mode when a linkage with the target station is established. What you type is converted into packets and transmitted over the air.5 mm (1/10") 3-conductor plug RXD2 DB-9 connector Pin No.CONNECTING WITH A PERSONAL COMPUTER You can use an optional PG-4W cable to connect the transceiver with a personal computer. y To select 9600 bps as the transfer rate from/to the target station. !0 Send appropriate commands and. 54 .PREPARATION FLOW 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 The following steps should guide you to a good start of packet operation. e Access Menu 1–4–1 to select band A or B as the data band {page 55}. • “ ” appears. messages to the target station via the TNC. type CONNECT (or C) then its call sign and press [Enter] or [Return].) and press [Enter] or [Return] to set your call sign on the TNC. The shaded steps indicate operations on your personal computer. ” appears. if necessary. q Install an appropriate communications program on the personal computer. • A variety of freeware or shareware programs can be obtained in various ways. First connect the transceiver to the personal computer {page 53}. t Press [TNC] again to enter Packet mode. The TNC cannot transmit in such a situation. a message which informs you of it appears on the computer screen. The default is 1200 bps. Note: You may switch Battery Saver OFF {page 49} to prevent the initial portion of a received packet from being missed. u Type MYCALL (or MY) then your call sign (9 digits max. i Tune to an appropriate frequency. • You must select the same transfer rate as the target station. Consult your reference material or other “packeteers”. w Initiate the communications program and set the following parameters on the personal computer: • • • • • Transfer rate (TNC <–> Computer): 9600 bps Data length: 8 bit Stop bit: 1 bit Parity: Non Flow control: Xon/Xoff o To connect with the target station. on the transceiver display. type HBAUD (or HB) 9600 and press [Enter] or [Return]. • You cannot use the default setting (NOCALL). r Press [TNC] to switch ON the TNC. adjust the squelch level in advance. • First you may want to monitor packets which are transmitted among other stations. • When a linkage is established. • “PACKET” also appears. “ • If packets from other stations keep your squelch open. When packets are received. text appears and the computer screen scrolls. Press [DUP] to enter Full Duplex mode. 11 12 13 14 15 16 17 18 D BAND ONLY: The TNC does not transmit when signals are present on the data band. Note: x You cannot use the Full Duplex function after recalling the VHF band on band B or blanking one band. Select band A or B as the data band for receiving or transmitting packets. FULL DUPLEX This transceiver is also capable of simultaneously transmitting and receiving signals. BOTH BANDS: The TNC does not transmit when signals are present on the data band or another band. x When using the Full Duplex function. “ ” indicates the current data band. it is possible to transmit audio on the current band while receiving packet data on another band (data band). • “DUP” appears. To exit Full Duplex mode. So. connect an earphone to the SP jack. Access Menu 1–4–2 (DCD SENSE) and select one of the two methods. press [DUP] again. STA CON 5 1 2 3 4 5 6 7 PACKET96BCON 9 7 8 9 10 You can also select the method for inhibiting the built-in TNC from transmitting.SELECTING DATA BAND This transceiver is capable of receiving packet data on one band (data band) while receiving audio on another band. the default is band A. Access Menu 1–4–1 (DATA BAND) and select band A or B. Using an earphone will prevent feedback that can cause the transceiver to emit a howling sound. 55 19 20 21 22 23 . ). If one station finds a DX station on the air. then press [UP]/ [DWN]. x This transceiver beeps each time it receives new or duplicate DX cluster data. You may access Menu 1–5–3 (BEEP) to change this setting. using the function. he (or she) sends a notice to his (or her) node. Node Node Node Station To scroll through up to 10 sets of DX information. “dD” and a call sign will appear at the bottom of the display. STA CON Comment • Press [LIST] to restore the frequency display. Then this node passes the information to all its local stations besides another node. Use this function to monitor the latest DX information in your local area. • When duplicate DX cluster data is received.DX PACKETCLUSTERS MONITOR 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 5 DX PacketClusters are networks which consist of nodes and stations who are interested in DXing and contesting. You cannot send DX information to a node. the frequency display is not interrupted. press [LIST] twice. the frequency display is interrupted to show information as below: STA CON 5 96BCONDUP 7 9 Frequency Time • The transceiver restores the frequency display after approximately 10 seconds pass or when you press any key. • “ ” appears. x Before tuning to a PacketCluster node. 2 Tune to the frequency of the target PacketCluster node. The default is “ALL”. 96BCONDUP 7 9 22 23 56 . This transceiver can display received DX information and hold the latest information on up to 10 DX stations. unintentional APRS packet transmission will annoy PacketCluster nodes and stations. Note: x The information is cleared when the transceiver power is turned OFF. switch the APRS Beacon function OFF {page 74}. Each time new DX cluster data is received. See the table on page 63. otherwise. 3 Press [TNC] to switch ON the TNC. • Press [OK] to access an attached comment (20 characters max. STA CON 5 96BCONDUP 7 9 1 Access Menu 1–4–1 (DATA BAND) to select band A or B. then press [OK] to change the setting on the VC-H1. you can use Menu 3–8 (TX MODE) to program a SSTV mode for the VC-H1.) Color for RSV report In addition. For this cable. see the instruction manual for the VC-H1. Note: Use an optional PG-4V cable to connect the VC-H1 to this transceiver. Press [UP]/ [DWN] to select the desired mode. transmitting at high power using the provided antenna may cause malfunction. to program information and select its color. x When the VC-H1 is too close to the transceiver. The SSTV mode currently set on the VC-H1 appears. For further information on the VC-H1. [3]. and a LCD monitor. The cable that comes with the VC-H1 allows only image transfer from/ to other stations. You can transmit or receive full-color images just by connecting the VC-H1 to this transceiver. The selectable SSTV modes are as follows: • • • • • Robot (color) 36 AVT 90 Scottie S1 Martin M1 Fast FM • • • • Robot (color) 72 AVT 94 Scottie S2 Martin M2 PG-4V Note: x Switch OFF both the transceiver and VC-H1 before making the connection. Press [MENU]. The VC-H1 is an optional portable unit which includes all requirements for SSTV. You can also select colors for those information. contact your authorized KENWOOD dealer.SLOW-SCAN TELEVISION (SSTV) WITH VC-H1 Slow-scan Television (SSTV) is a popular application for transmitting still images over the air from one station to another. 57 . From this transceiver you can enter and superimpose a message. Use the following Menu Nos. a CCD camera. a slow-scan converter.) Color for message RSV report (10 digits max. [8]. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 3–1 3–2 3–3 3–4 3–5 3–6 MY CALL MY CALL COL MESSAGE MESSAGE COL RSV RSV COLOR Call sign (8 digits max. First connect the transceiver to the VC-H1 and switch ON both the transceiver and VC-H1. and a call sign onto an image on the VC-H1 monitor. This is caused by unwanted feedback.) Color for call sign Message (9 digits max. an RSV report. Use the following procedures to enter a call sign. the RSV report should be 595. STA CON 6 Press [MENU] to exit Menu mode. You can also use the keypad to enter alphanumeric characters in step 3. 3–3. and /. • Each press of [ESC] causes the cursor to move backward. and 3–5 is the maximum number of digits that you can enter. the first digit blinks. Note: The only difference among Menus 3–1. So you may enter another message using Menu 3–5. [1] to select “3–1 (MY CALL)”. and video. or 10 digits (RSV report). • The cursor moves to the next digit.ENTERING CALL SIGN/ MESSAGE/ RSV 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 STA CON 5 5 Repeat steps 3 and 4 to enter up to 8 digits (call sign). for example. –. 1 Press [MENU] to enter Menu mode. B. 9 digits (message). 20 21 22 4 Press [OK]. • Pressing [OK] after selecting the last digit completes the programming. !. 2 Press [3]. signal strength. • To complete programming after entering less than the maximum digits. C. or [3]. a message. [3] to select “3–3 (MESSAGE)”. • The display for entering characters appears. RSV stands for readability. or an RSV report. Press [DUAL] to switch 0 and space. • Pressing [A/B] deletes the digit at which the cursor is blinking. 1 Faint signals barely perceptible 6 Good signals Moderately strong 2 Very weak signals 7 signals 3 Weak signals 8 Strong signals 4 Fair signals 5 Fairly good signals 9 Extremely strong signals 3 Press [UP]/ [DWN] to select a character. space. 23 58 . each press of [TNC] switches entry as A. then 2. Press [ENT] to switch among the special ASCII characters. For example. A to Z. If you receive a clear image free from noise. press [OK] twice. ?. or [3]. Readability 1 Unreadable 2 Barely readable Readable with considerable 3 difficulty Readable with practically no 4 difficulty 5 Perfectly readable Video 1 Unrecognizable 2 Barely recognizable Recognizable with 3 considerable difficulty Recognizable with 4 practically no difficulty 5 Perfectly recognizable 7 PACKET96BCONDUP 9 STA CON 5 7 PACKET96BCONDUP 9 16 17 18 19 5 7 PACKET96BCONDUP 9 Signal Strength • You can enter 0 to 9. [5] to select “3–5 (RSV)”. STA CON 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 7 PACKET96BCONDUP 9 7 PACKET96BCONDUP 9 STA CON 5 7 PACKET96BCONDUP 9 • “EXECUTING” appears and data transfer starts. STA CON 5 7 PACKET96BCONDUP 9 3 Press [MENU] to exit Menu mode. [7] to select “3–7 (SUPERIMPOSE)”. cyan. or RSV report. magenta. 59 . [4] to select “3–4 (MESSAGE COL)”. or [3].SELECTING COLOR FOR CALL SIGN/ MESSAGE/ RSV You can select white (default). STA CON 5 EXECUTING SUPERIMPOSITION After connecting the VC-H1 to this transceiver. message. red. blue. green. 1 Press [MENU] to enter Menu mode. First recall the desired image on the VC-H1. or yellow to color the call sign. or [3]. 2 Press [3]. 2 Press [3]. Note: Switch OFF both the transceiver and VC-H1 before making the connection. 5 Press [MENU] to exit Menu mode. 3 Press [UP]/ [DWN] to select the color. [2] to select “3–2 (MY CALL COL)”. black. 4 Press [OK] to complete the setting. 1 Press [MENU] to enter Menu mode. use the following procedure to execute superimposition. [6] to select “3–6 (RSV COLOR)”. Transmit a subaudible tone from the remote control to this transceiver connected with the VC-H1 for more than 1 second. and transmits the image to the target station. The power is ON 2. program a CTCSS frequency {page 39}. 2 Press [3]. The camera and LCD monitor must not be left ON. [9] to select “3–9 (VC SHUTTER)”. • Switching the function ON activates the CTCSS. Then this transceiver causes the VC-H1 to capture an image. The following table concludes the settings you must confirm: TH-D7 and remote control TH-D7 and remote control Remote control VC-H1 1 2 The current frequency is the same as the target station. 60 . Note: x If you have made no entry for superimposition. STA CON 5 7 PACKET96BCONDUP 9 e Ton 4 Press [OK] to complete the setting.VC-H1 CONTROL 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 1 Press [MENU] to enter Menu mode. executes the superimposition. STA CON 5 If you have another transceiver that has the Tone function. “CT” appears. The Tone function is ON. 5 Press [MENU] to exit Menu mode. The tone frequencies match 1. x “EXECUTING” appears and blinks on this transceiver while a series of operations is in progress. superimposition will not be executed. use F–4 (CTCSS FREQ) {page 39}. on this transceiver. you can use it as a remote control for the VC-H1. You must select the same tone frequency on both transceivers. 7 PACKET96BCONDUP 9 3 Press [UP]/ [DWN] to switch the function ON (or OFF). For the TH-D7. He has made packet communications much more exciting than before. Imagine seeing one mobile station moving on the map which can be scaled from . you usually need a computer running the APRS. use this function if you do not have a GPS receiver.5 to 2000 miles.AUTOMATIC PACKET/ POSITION REPORTING SYSTEM® The Automatic Packet/ Position Reporting System (APRS®) is a software program and registered trademark of Bob Bruninga. To have them track you. however. consult Internet Web pages relating to the APRS. you do not need a computer. This program allows you to track mobile stations on a map which you recall on a computer screen. Its display shows information each time correct APRS data is received. You also may be tracked on the computer screen of another station. To track other stations. WB4APR. Note: x Turn OFF the transceiver power before making the connections. It receives signals from the satellites to inform you of your current geographical position. You may use the provided cable {page 1} to modify the cable end of your GPS receiver. This transceiver has a PC jack and GPS jack to connect with a personal computer and a GPS receiver. This manual. It also allows you to manually enter position data (latitude/ longitude) to transmit. You may use one of the Internet search engines to find correct URLs. and a TNC. a transceiver. The connection of each conductor (TXD/ RXD/ GND) is the same as the plug on the PG-4W {page 53}. Besides position data this transceiver can receive or transmit the following information: Station icon Position comment Moving speed 1 2 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Weather reporting Status text Moving direction 2 1 Receive only Can be transmitted only when using a GPS receiver. For further information. PG-4W To COM port GPS receiver 61 . does not describe APRS communications which require these equipment. Stations to be tracked must transmit beacons at certain intervals. you also need a GPS receiver. GPS stands for Global Positioning System. The APRS interprets the National Marine Electronics Association (NMEA) data strings coming from the GPS receiver.5 mm (1/10") 3-conductor plug. This transceiver includes a TNC and a program for dealing with data formats supported by the APRS. x The GPS jack also accepts a 2. Note: When using your personal computer. access Menu 2–2 and select “NMEA”.OPERATION FLOW 1 2 3 4 5 6 7 8 9 10 11 12 Now you are ready to receive APRS data from other 13 stations. On the transceiver. !4 Press [BCON]. To transmit your APRS data. 15 16 17 18 19 20 21 22 23 The following steps should guide you to a good start of APRS operation. access Menu 2–6 to enter status text using up to 20 alphanumeric characters {page 70}. proceed to r Access Menu 2–1 to program your call sign (9 digits max. • “ ” appears. {page 63}. then press and release the PTT switch. u Access Menu 2–3 to enter latitude and longitude data {page 68}. access Menu 2–7 to select the interval for transmitting beacons {page 75}. o If you want. press [TNC] twice to enter Packet mode. !1 If necessary. w Access Menu 1–4–1 to select band A or B as the data band {page 55}. access Menu 2–A to program a group code {page 71}. !2 Access Menu 2–9 to select the operation method for transmitting beacons {page 74}. y Access Menu 2–5 to select your station icon {page 67}. t If you have connected a GPS receiver. set the same communication parameters as Packet Operation {page 54}. access Menu 2–8 to program a packet path {page 72}. e On the data band select the same frequency as other stations in your group. 62 . “PACKET” should appear. The default is “NOT USED”.) {page 66}. !3 If you selected “PTT” or “AUTO” in step !2. !0 If you want. q Press [TNC] to switch ON the TNC. i Access Menu 2–4 to select from 8 position comments {page 69}. See page 74. If you selected “PTT” in step !2. • You may tune to the frequency of an appropriate digipeater {page 72}. Refer to “RECEIVING APRS DATA” 14 step r. Packet that cannot be decoded The transceiver automatically transmits the appropriate information in approximately 2 minutes after receiving a request. Note: When you receive APRS data that you transmitted. See the table. This could happen when one or more digipeaters {page 72} are used. The data entered to these two fields are transmitted as separate packets. “MY PACKET” will appear at the bottom of the display. The default is “ALL”. In this case. the frequency display is interrupted to show information as below: STA CON 5 Indicator dP dS >P Q ?1 ?? 1 Meaning What is Included? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Same comment as the Duplicate position previous one from the comment same station Duplicate status text Beyond position limit Query Status text already received Data from a station outside the selected range {page 75} Request for sending information 96BCONDUP 7 9 Position comment (or status text) • The received APRS data may include information on an object such as a hurricane or tornado. You may access Menu 1–5–3 (BEEP) to change this setting. This transceiver beeps each time it receives new or duplicate APRS data.RECEIVING APRS DATA Each time new APRS data is received. If a received packet does not include new (or proper) APRS data. the name of the object appears instead of a call sign. STA CON 5 Note: The APRS programs for PCs have entry fields for a position comment and status text. the frequency display is not interrupted. • The transceiver restores the frequency display after approximately 10 seconds pass or when you press any key. the frequency display is not interrupted. 96BCONDUP 7 9 Selections OFF KEY KEY+NEW DATA ALL Key Pressed No beep Beep Beep Beep New APRS Data No beep No beep Beep Beep Duplicate APRS Data No beep No beep No beep Beep 63 . An indicator such as “dP” appears depending on the types of data. x When APRS data is received with a GPS receiver connected. by switching the display. the right 6 digits of the call sign is used as a name (ex. for KJ6HC-3. x Each time new APRS data is received from the same station. You can select the desired station and access the desired information. 96BCONDUP 5 96BCONDUP 7 9 • You may press [ESC] to restore the previous display. STA CON 5 This transceiver is capable of receiving and storing APRS data from up to 40 stations in memory. the NMEA-0183 ($GPWPL) format is used. • The numbers beside the call signs indicate the order in which data is received. The data received last is assigned 1. 5 Press [LIST] twice to restore the frequency display. see the next page. Note: x When data from the 41st station is received. J6HC-3). the old data from that station (in memory) is replaced by new data. For details. 1 Press [LIST]. Press [A/B] instead of [OK] in step 3 or 4.ACCESSING RECEIVED APRS DATA 1 2 3 4 5 6 7 8 STA CON 4 Press [OK] repeatedly until you can access the desired information. STA CON 5 96BCONDUP 7 9 64 . STA CON 5 96BCONDUP 7 9 3 Press [OK]. 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 7 9 2 Press [UP]/ [DWN] to select the desired station. To delete the information of all stations. • The display for selecting a station appears. Press [OK]. “DELETE?” appears. “DELETE ALL?” appears. the oldest data in memory is replaced by that data. press [A/B] (1 s) in step 2. You may want to delete all information of the desired station. Press [OK] to delete the information. • The display for accessing the desired information appears. Then “ARE YOU OK?” appears. This data is registered in the Waypoint List of the receiver. included position data is sent to the receiver. The types of information accessible in step 4 differ depending on the types of stations. Press [OK] again to delete the information. 0 to 9999 miles (or km) are shown for distances from other stations. the display will show an icon code such as /$ or \$. 65 . You can also change these units to kilometer and °C. When icon data other than these is received. 1 2 3 4 Some icons may appear with characters if the received icon data includes them. 10 11 12 13 14 15 Mobile station q Moving direction w Moving speed m: Mile/hour k: km/hour q Transmit power w Height of antenna (elevation) ’ : Feet M: Meter e Antenna gain r Antenna directivity omni: Omnidirectional Object {page 63} q Transmit range (mile or km) 1 0. “xxxxmi” (or “xxxxkm”) is shown for distances over 9999 miles (or km). “ ” indicates the other station is located at the northeast relative to your position. Access Menu 2–C (UNIT) and 17 select “km. For example. 18 19 STA CON 5 96BCONDUP 7 9 20 21 22 23 q Wind direction q Call sign w Wind speed m: Mile/hour k: km/hour e Temperature F: ° F c: °C r Amount of rainfall in the past hour (" or mm) Note: You cannot separately change the units of distance and temperature. Using compressed APRS data format Weather station On this transceiver the default units for distance and 16 temperature are mile and °F. The following are examples: 5 6 7 8 q Position comment (or status text) q Grid square locator w Distance from the station (mile or km) Fixed station q Latitude/ longitude data N: North S: South W: West E: East Fixed station 1 The following icons show the directions of stations relative 9 to your position.This transceiver is capable of displaying the following 18 icons as station IDs. °C”. C.PROGRAMMING A CALL SIGN 1 2 3 4 5 6 7 5 To transmit APRS data. and –. 96BCONDUP 7 9 8 9 10 11 3 Press [UP]/ [DWN] to select a character. Press [ENT] to enter –. • The display for entering characters appears. 17 • To complete programming after entering less than 9 18 digits. The default is “NOCALL”. you cannot transmit APRS data. 22 23 6 Press [MENU] to exit Menu mode. then 2. 21 • Pressing [A/B] deletes the digit at which the cursor is blinking. the first digit blinks. Note: Unless you program a call sign. 16 • Pressing [OK] after selecting the 9th digit completes the programming. press [OK] twice. each press of [TNC] switches entry as A. 12 • You can enter 0 to 9. A to Z. 14 • The cursor moves to the next digit. 2 Press [2]. For example. 66 . 19 • Each press of [ESC] causes the cursor to move 20 backward. 15 5 Repeat steps 3 and 4 to enter up to 9 digits. B. 1 Press [MENU] to enter Menu mode. 13 4 Press [OK]. [1] to select “2–1 (MY CALL)”. first program your call sign using a maximum of 9 alphanumeric characters. STA CON You can also use the keypad to enter alphanumeric characters in step 3. 5 Press [MENU] to exit Menu mode. This manual describes the APRS in further details. 4 Press [OK]. and the other is a table identification code (either / or \). [5] to select “2–5 (ICON)”. This method is described in the separate manual (document file) that comes with an optional PG-4W cable. It allows users to select each icon by specifying a combination of two ASCII codes. / and !. STA CON 5 KENWOOD Jogger Home Portable (tent) Yacht SSTV Aircraft Boat Car Motorcycle Triangle Jeep Recreation vehicle Truck Van 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 96BCONDUP 7 9 3 Press [UP]/ [DWN] to select from 15 icons plus “OTHERS”. for example. 1 Press [MENU] to enter Menu mode. You may select an icon depending on your current location. One is a symbol code. 67 . • The following 15 icons are selectable: APRS supports approximately 200 icons. If you select “OTHERS” in step 3.SELECTING YOUR STATION ICON Select an icon which will be displayed on the monitors of other stations as your ID. 2 Press [2]. you can proceed to steps for specifying combinations of two codes. Press [OK] again. Each field is then divided into 100 “squares” (00 ~ 99). • You may press [POS] instead. 96BCONDUP 21 22 23 5 7 9 68 . 12 13 4 Press [OK]. 1 Press [MENU] to enter Menu mode. 10 Press [UP]/ [DWN] to select data for degrees. • The degree digits blink. 20 STA CON 13 Press [MENU] to exit Menu mode. 2 Press [2]. • The minute digits blink. 9 Press [OK]. STA CON 96BCONDUP 7 9 12 Repeat steps 10 and 11 to select data for minutes (down to one hundredth digit). 11 Press [OK]. The world is eventually divided into 18. 14 • The degree digits blink. you can also copy the measured data to the position entry display for Menu 2–3. The position data received via the GPS receiver most lately will be displayed. 662. 15 5 Press [UP]/ [DWN] to select data for degrees. each grid is expressed with 6 digits. This transceiver allows you to manually enter latitude and longitude data to transmit to other stations. Note: x If have selected “NMEA” in Menu 2–2. Each square is further divided into 576 “sub-squares” (AA ~ XX). Then you can skip step 2. 400 grids. x Grid squares were developed to shortly identify locations anywhere on the Earth. The world is first divided into 324 areas (AA ~ RR) called “fields”.ENTERING LATITUDE/ LONGITUDE DATA 1 2 3 4 5 6 7 5 8 Press [UP]/ [DWN] to switch between west longitude (default) and east longitude. Grid square locator 5 8 9 10 STA CON 96BCONDUP 7 9 11 3 Press [UP]/ [DWN] to switch between north latitude (default) and south latitude. [3] to select “2–3 (My Pos)”. “COPY to MENU?” appears. then press [OK]. 17 • The minute digits blink. 16 6 Press [OK]. x If using a GPS receiver. 18 7 Repeat steps 5 and 6 to select data for minutes 19 (down to one hundredth digit). Press [POS] to display the measured data. pressing [POS] does not allow you to access the display for entering latitude/ longitude data. 2 Press [2]. STA CON 5 96BCONDUP 7 9 4 Press [OK] to complete the setting. The selectable comments are listed below: Off Duty (default) En Route In Service Returning 1 Committed Special Priority 1 1 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Emergency! STA CON 5 96BCONDUP 7 9 2 Selecting these comments will highlight your station on all other APRS computer displays. 5 Press [MENU] to exit Menu mode. You will activate alarms in all monitoring APRS stations. 69 . Select this comment only when absolutely necessary. [4] to select “2–4 (POS COMMENT)”.SELECTING A POSITION COMMENT The APRS data which you transmit always include one of the 8 predetermined position comments. 3 Press [UP]/ [DWN] to select the desired comment. 1 Press [MENU] to enter Menu mode. Select an appropriate comment depending on your situation. ENTERING STATUS TEXT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 Press [UP]/ [DWN] to select a character. 1 Press [MENU] to enter Menu mode. each press of [TNC] switches entry as A. You can also transmit any comment (status text) with the latitude/ longitude data. • Pressing [A/B] deletes the digit at which the cursor is blinking. a. the first digit blinks. 96BCONDUP 6 Press [MENU] to exit Menu mode. then 2. For example. • The cursor moves to the next digit. press [OK] twice. 2 Press [2]. • The display for entering a comment appears. • Pressing [OK] after selecting the 20th digit completes the programming. c. • To complete programming a comment after entering less than 20 digits. If you want. enter a desired comment using a maximum of 20 alphanumeric characters. 15 16 • You can enter alphanumeric characters plus special ASCII characters. Note: Attaching a long comment can double the size and length of the packet. • Each press of [ESC] causes the cursor to move backward. C. Enter a comment only if necessary. [6] to select “2–6 (STATUS TEXT)”. You can also use the keypad to enter alphanumeric characters in step 3. b. B. Press [DUAL] to switch 0 and space. Press [ENT] to switch among the special ASCII characters. 7 9 17 4 Press [OK]. 18 19 20 21 22 23 70 . STA CON 5 5 Repeat steps 3 and 4 to enter up to 20 digits. [A] to select “2–A (UNPROTOCOL)”. 2 Press [2]. • The cursor moves to the next digit. each press of [TNC] switches entry as A. The APRS on this transceiver supports the following three types of group codes. In order to reject other packets. 5 Repeat steps 3 and 4 to enter up to 9 digits.1. press [OK] twice. • To complete programming after entering less than 9 digits. 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 GPS ALL SYM SKYWRN QST MAIL CQ ID BEACON SPC L 4 Press [OK]. C. • Pressing [A/B] deletes the digit at which the cursor is blinking. A to Z. • You can enter 0 to 9. All calls: Program a 6-digit code that always starts with AP. This code is generally programmed by all stations at a special event. Alternate net: Program any other code with a maximum of 6 digits. 6 Press [MENU] to exit Menu mode. For example. include various codes instead of group codes. You will receive only APRS packets that include the exact same code. STA CON 5 1 2 3 4 5 6 7 8 96BCONDUP 7 9 3 Press [UP]/ [DWN] to select a character. and –. then 2. Special: Enter “SPCL”. • Each press of [ESC] causes the cursor to move backward. 71 . K001 stands for KENWOOD Ver. You will receive all APRS packets which include AP in group codes.PROGRAMMING A GROUP CODE Using a group code relieves you from receiving unwanted packets. You will receive only APRS packets that include SPCL as a group code. It does not matter whether or not the subsequent 4 digits match. Press [ENT] to enter –. Note: APRS packets. The default is APK001 (All calls). • Pressing [OK] after selecting the 9th digit completes the programming. The default on this transceiver is APK001. Note: Menu 2–A allows you to enter up to 9 digits (not 6 digits) because of possible future enhancement of the group code system. You can also use the keypad to enter alphanumeric characters in step 3. B. which are generated via various methods. Using “All calls” allows you to receive packets which include the following codes. 1 Press [MENU] to enter Menu mode. the first digit blinks. • The display for entering characters appears. this code should not include characters specified by the above two types. press [OK] twice. 4 Press [OK]. it operates on a simplex frequency.PROGRAMMING A PACKET PATH 1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 20 21 22 23 Wide-type Relay-type 1 Press [MENU] to enter Menu mode. Some of those methods are described on the next page. This came from a digital repeater. each press of [TNC] switches entry as A. This transceiver allows you to edit a path using a maximum of 32 alphanumeric characters. then 2. A comma must be put between each parameter. Each volunteer who installs a digipeater declares his (or her) digipeater to be a “wide” type or “relay” type. 5 Repeat steps 3 and 4 to enter up to 32 digits. • Pressing [A/B] deletes the digit at which the cursor is blinking. the first digit blinks. • To complete programming after entering less than 32 digits. [8] to select “2–8 (PACKET PATH)”. STA CON 5 A packet path specifies how APRS data should be transferred via one or more repeaters. B. which is used for packet transfer. is commonly called a digipeater. 96BCONDUP 7 9 3 Press [UP]/ [DWN] to select a character. Press [ENT] to switch between . 6 Press [MENU] to exit Menu mode. A to Z. • The cursor moves to the next digit. Generally a wide-type digipeater transmits packets over much greater distances than a relay-type one. • Pressing [OK] after selecting the 32nd digit completes the programming. The default is “RELAY. and –. 72 . A digipeater is usually located on a mountain top or high building. 2 Press [2]. You can also use the keypad to enter alphanumeric characters in step 3. The APRS supports various methods for specifying a packet path. (comma). For example. • You can enter 0 to 9. A repeater. and –. • The display for entering characters appears. C. . Unlike a voice repeater. 15 Note: This transceiver is incapable of functioning as a digipeater. • Each press of [ESC] causes the cursor to move backward.WIDE” that is one of the common settings. WIDE” for example. APRS data is transferred to any relay-type digipeater near your position first. APRS data will be transferred to any wide-type near your position first. The digipeater which receives your APRS data specifies the call sign of the next digipeater before forwarding. “RELAY. This is repeated until your APRS data reaches the destination. You can easily specify the number of digipeaters that will be used for relay. You can also specify which directions of digipeaters relative to your position will be used. then to another wide-type. Method 1 (Specific path): Program the call signs of one or more digipeaters in the sequence of transfer relay. In this example. “KD6ZZV. You can also program more than one “WIDE”.KF6RJZ”. APRS data will be relayed by three digipeaters in any direction. ex. Note: This method is supported only by advanced APRS networks. Note: This method is supported only by advanced APRS networks. ex. then to any wide-type digipeater. often 2 digipeaters are used in total.WIDE”. where both Ns indicate the number of wide-type digipeaters to be used for relay. See the table. Method 2 (Generic path): Program “RELAY” and/or “WIDE”. If you enter “WIDE. 73 . 2 The first digipeater which receives your APRS data specifies the entire route to the destination before forwarding.Let us describe four basic methods for editing a packet path. This method relieves you from specifying the call signs of digipeaters. Parameter 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 Number of digipeaters 1 2 3 4 5 6 7 2 (or more) 1 2 (or more) 1 2 (or more) 1 2 (or more) 1 Many 2 Direction All All All Al l All All All North South East West North South East West 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Many 2 Many 2 Many 2 Method 4 (SSID path): Program a single number 1 to 15. Method 3 (WIDEN-N path): Program “WIDEN-N”. If you enter “WIDE3-3” for example. • Switching the function ON transmits the APRS data once. 3 Release the PTT switch. • “BCON” appears.SELECTING BEACON TRANSMIT METHOD 1 2 3 4 5 6 5 MANUAL Select the operation method for transmitting APRS data. 74 . The table concludes how operations differ depending on the selection: 1 Press [MENU] to enter Menu mode. After that. • You cannot retransmit the APRS data unless the time selected in Menu 2–7 (TX INTERVAL) passes. 1 Press [BCON] to switch the function ON. STA CON Each press of [BCON] transmits the APRS data. press [BCON] again. APRS data is automatically transmitted at intervals of the period selected in Menu 2–7 (TX INTERVAL). 96BCONDUP 2 Press and hold the PTT switch. 1 Press [BCON] to switch the function ON. 2 Press [2]. 96BCONDUP 5 13 14 15 16 7 9 4 To switch the function OFF. PTT • Releasing the switch transmits the APRS data. PTT. Wait until “BCON” starts blinking to indicate transmitting is ready. 19 20 21 22 23 AUTO 2 To switch the function OFF. 17 4 Press [OK] to complete the setting. or Auto. 18 5 Press [MENU] to exit Menu mode. [9] to select “2–9 (DATA TX)”. then speak into the microphone. 7 9 7 8 9 10 11 12 STA CON 3 Press [UP]/ [DWN] to select Manual (default). • “BCON” appears and blinks. press [BCON] again. 1 Press [MENU] to enter Menu mode. The unit is mile or kilometer depending on the 14 selection in Menu 2–C (UNIT) {page 65}. 2 Press [2]. 3. 4 Press [OK] to complete the setting. 2 Press [2]. 10. 5 Press [MENU] to exit Menu mode. After that. 5. x While signals are present. 96BCONDUP 7 9 12 • The selectable range is from 10 to 2500 in steps of 10. • The selectable intervals are . you may receive too many APRS packets for a short period. [B] to select “2–B (POS LIMIT)” STA CON 5 1 2 3 4 5 6 7 8 9 10 11 96BCONDUP 7 9 96BCONDUP 7 9 3 Press [UP]/ [DWN] to select the desired interval. STA CON 5 3 Press [UP]/ [DWN] to select the desired distance. 13 plus OFF.5. The default is 5 minutes. 15 STA CON 5 96BCONDUP 7 9 16 17 18 19 4 Press [OK] to complete the setting. 1. STA CON 5 RESTRICTING RECEPTION OF APRS DATA If APRS is popular in your country. specify a distance from your location. 1 Press [MENU] to enter Menu mode. pressing [OK] in step 4 causes the APRS data to be immediately transmitted. the APRS data is transmitted at intervals of the selected period. 20 21 22 23 75 . 5 Press [MENU] to exit Menu mode. and 30 minutes. 2. [7] to select “2–7 (TX INTERVAL)”. You will not receive APRS data from stations beyond this distance. If this disturbs your APRS activities. Note: x With “AUTO” in Menu 2–9 and Beacon ON. 20. APRS data is not transmitted after the interval. transmitting is executed. Approximately 2 seconds after signals drop.SELECTING BEACON TRANSMIT INTERVAL Select an interval for automatically transmitting APRS data. r Access Menu 2–1 to program your call sign (9 digits max. Now you are ready to receive a message from other stations. 76 .APRS® MESSAGE 1 2 3 4 5 6 7 8 9 10 11 13 14 15 16 17 18 19 20 21 22 23 The APRS® supports a function for transmitting and receiving a message independent of position reports. Completing step y causes the transceiver to automatically transmit the message (or bulletin). y Enter a message (or bulletin) using up to 45 alphanumeric characters {page 79}. the entered message is transmitted up to 5 times until a reception acknowledgment is returned. access Menu 2–8 to program a packet path {page 72}. t If necessary. Refer to “RECEIVING A MESSAGE” {page 77}. • “ ” appears. e On the data band select the same frequency as other stations in your group. OPERATION FLOW APRS Message operation. If you specify a station. “ack” appears. w Access Menu 1–4–1 to select band A or B as the data band {page 55}. A maximum of 16 incoming or outgoing messages can be held in the message memory. • You may tune to the frequency of an appropriate digipeater {page 72}. 12 The following steps should guide you to a good start of q Press [TNC] to switch ON the TNC. Each message which you transmit can consist of up to 45 alphanumeric characters. To transmit a message. If you send a message (not a bulletin). You can transmit a message to a single station only or a bulletin to all other stations in your group.) {page 66}. proceed to step t. a reception acknowledgment should be returned. A~Z ! 1 A personal message to you A bulletin to all stations in your group A report by the National Weather Service Reception acknowledgment to your message Note: x This transceiver allows you to receive a message also when the SSID does not match. it will not return a reception acknowledgment. However. STA CON 5 • When a message to other stations is received. 1 Sequence of message (or bulletin) packets from the same station 77 . You may access Menu 1–5–3 (BEEP) to change this setting. “dM” and a call sign appear on the display. Selections Key Pressed No beep Beep Beep Beep New Message No beep No beep Beep Beep Duplicate Message No beep No beep No beep Beep 96BCONDUP 7 9 OFF KEY KEY+NEW DATA ALL The following indicators appear depending on types of received messages: 0 ~9 1 0~9 1. an error beep sounds. • “ ” appears and stays at the bottom left of the display until you use the List function {page 78}.RECEIVING A MESSAGE Each time a proper message is received. x When a message addressed to you is received. If you do not press any key in approximately 5 seconds. STA CON 1 2 3 4 5 6 96BCONDUP 96BCONDUP 5 7 9 7 9 Indicator • The display shows only the first 24 characters of the message. the frequency display is interrupted to show information as below: STA CON 5 When a duplicate message from the same station is received. the light goes off. The default is “ALL”. • The transceiver restores the frequency display after approximately 10 seconds pass or when you press any key. “oM” appears at the bottom left of the display. In addition. 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 This transceiver beeps each time it receives a new or duplicate message. the transceiver display and keypad are illuminated. 2 Press [UP]/ [DWN] to select “LIST”. 11 • Press [OK] to see the 25th and subsequent digits of the message. 0~9 . 15 Pressing [MSG] in step 4 allows you to enter a message to be returned to the station. You can access the desired massage by switching the display. A message not yet transmitted 5 times may be unexpectedly deleted. If “ ” stays at the bottom left of the display when memory is full. the display will show the following types of information: STA CON 5 This transceiver is capable of storing a maximum of 16 messages in memory. You can skip steps 1 to 6 in 16 “ENTERING A MESSAGE” {page 79}. Select the message in step 4 and press [MSG]. STA CON 96BCONDUP 7 9 Message qw e 96BCONDUP 7 9 q Message Type 0~9 1 1 A personal message to you A bulletin to all stations in your group A report by the National Weather Service w RX or TX? 3 Press [OK]. The call sign and message are copied to the recalled entry display {page 79}.) and messages for transmitting. 78 . a new message does not replace the oldest message. Receiving a new message when the memory is full causes the oldest message to be deleted. a reception acknowledgment was not returned. 12 13 • “ ” indicates the end of the message. This transceiver returns a reject command and shows “rM” and a call sign at the bottom of the display. 1 Press [MSG]. 14 5 Press [ESC] twice to restore the frequency display. A~Z ! 1 10 4 Press [UP]/ [DWN] to select the desired station. 17 Note: 18 x The dedicated memory is used for storing both received messages 19 20 21 22 23 x <– –> 2 A received message A message for transmitting e Status 2 A message (or bulletin) not yet transmitted 5 times A message for which a reception acknowledgment was returned A message (or bulletin) transmitted 5 times (For a message. 2 . 1 2 2 Sequence of message (or bulletin) packets from the same station These indicators appear for outgoing messages {page 80}. A message already transmitted can be easily sent to the same station.ACCESSING RECEIVED APRS MESSAGES 1 2 3 4 5 6 7 8 9 5 Besides the call sign and message. 1 Press [MSG]. Press [ENT] to enter –. then [OK] to select the first digit of a message (or bulletin). For example. • You may use the keypad. then 2. where must be any single alphanumeric character. c. • Completing step 8 causes the transceiver to automatically transmit the message (or bulletin). • The cursor moves to the next digit. enter “BLN ” as the call sign. 20 • To complete programming after entering less than 45 digits. For example. press [OK] twice. a reception acknowledgment should be returned. the first digit blinks. STA CON 5 7 Press [UP]/ [DWN]. first enter the call sign of the target station. To transmit a message. For example. Press [ENT] to switch among the special ASCII characters. • You can enter alphanumeric characters plus special ASCII characters. You can use to indicate the sequence of the bulletin portions. 2 Press [UP]/ [DWN] to select “INPUT”. then 2.ENTERING A MESSAGE You can enter a message or bulletin using up to 45 alphanumeric characters. When the length of your bulletin exceeds 45 digits. B. 3 Press [OK]. C. “ack” appears. If you send a message (not a bulletin). • The display for entering a call sign appears. C. • Pressing [A/B] deletes the digit at which the cursor is blinking. each press of [TNC] switches entry as A. 6 Repeat steps 4 and 5 to enter up to 9 digits. a. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 5 Press [OK]. b. To transmit a bulletin to all other stations in your group. you may program “BLN0” (or “BLNA”) to send the first packet. you may transmit more than one packet to send the entire bulletin. STA CON 5 • You may use the keypad. 79 . 21 22 23 4 Press [UP]/ [DWN] to select a character. each press of [TNC] switches entry as A. press [OK] twice. B. STA CON 5 96BCONDUP 7 9 96BCONDUP 7 9 • To complete programming the call sign after entering less than 9 digits. then “BLN1” (or “BLNB”) to send the second packet. • Each press of [ESC] causes the cursor to move backward. 96BCONDUP 7 9 8 Repeat step 7 to enter a message (or bulletin) with up 19 to 45 digits. • Pressing [OK] after selecting the 9th digit causes the cursor to move to the start of the next field. A 13 reception acknowledgment is not returned. 80 . STA CON 96BCONDUP 96BCONDUP 5 7 9 7 9 8 9 10 11 For a bulletin: 12 The transceiver always repeat transmitting 5 times. You can also manually transmit all of those regardless of the 5-minute timer. 1 Press [MSG]. For a message: The transceiver repeats transmitting up to 5 times until a reception acknowledgment is returned. “+” is assigned to messages (or bulletins) that have not yet been transmitted 5 times. • After transmission.TRANSMITTING A MESSAGE 1 2 3 4 5 6 7 5 When entry of a message (or bulletin) is completed. this transceiver automatically transmits it 5 times (max. 14 15 16 17 18 19 20 21 22 23 3 Press [OK] to start transmitting.) at intervals of 1 minute. 2 Press [UP]/ [DWN] to select “TRANSMIT”. the frequency display is restored. STA CON The table given on page 78 also shows indicators that appear for outgoing messages (or bulletins). x The FCC rules permit you to send control codes only on the 440 MHz band. you can control one of its bands by sending DTMF tones from this handy transceiver. Press [OK] (or [ESC]) to move the cursor to the next (or previous) digit. Note: x You can remotely control only the mobile transceivers that have both the DTSS and Remote Control functions. PREPARATION Let us assume the VHF band of the mobile transceiver will be controlled. • You can also press [UP]/ [DWN] to select each digit. You will find this function useful when you want to control your mobile transceiver from a location outside your vehicle. 4 Select the UHF band. The default is 000. 3 Press [OK] to complete the setting. • The current secret access code number appears. 81 . 5 Select the transmit frequency. On the handy transceiver: 1 Press [PTT]+[VFO]+ POWER ON. STA CON 1 2 3 4 5 6 7 8 96BCONDUP 5 DT MF 7 9 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ton es 2 Press a numeric key 0 to 9 to enter a 3-digit secret number.WIRELESS REMOTE CONTROL (TH-D7A ONLY) If you also have a KENWOOD multi-band mobile transceiver. 17 10 Make the transceiver enter Remote Control mode. • Mate this frequency with the transmit frequency on the handy transceiver. or 20 service center. 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 • To exit Remote control mode. [5]) ¬ [TONE SEL]) • Use Nos. the handy transceiver will automatically enter transmit mode and send the corresponding command to the mobile transceiver. Check the instruction manual for the mobile transceiver. the keys of the handy transceiver will function as below. 96BCONDUP 7 9 On the mobile transceiver: secret number. It may also allow you to program a separate tone and CTCSS frequency. 01 to 38 shown in the table in page 22. [0]. refer to the instruction manual for the mobile transceiver. repeat steps 6 and 7. To change the transmit/ receive frequency: ([VFO] ¬ [ENT] ¬ [0] ~ [9] (enter the necessary digits) ¬ [ENT]) or ([VFO] ¬ [UP]/ [DWN]) To recall a memory channel: ([MR] ¬ [ENT] ¬ [0] ~ [9] (enter the necessary digits) ¬ [ENT]) or ([MR] ¬ [UP]/ [DWN]) To change the tone (or CTCSS) frequency: ([TONE SEL] ¬ [0] ~ [9] (enter 2 digits. • The transceiver enters Remote Control mode. 18 • For the method. 21 22 23 82 . “MOBILE CTRL” appears. • Select the same number as you selected in step 2. • Your mobile transceiver may require you to first activate the Tone or CTCSS function.6 Turn the transceiver power OFF. customer service. consult your 19 authorized KENWOOD dealer. 1 2 10 8 Program the DTSS code on the UHF band as the TM-V7A: REV ON/ OFF Switches Cross-band Repeater ON/ OFF if the mobile transceiver has the function. refer to the instruction manual for the mobile transceiver. ex. 9 Select the receive frequency on the UHF band. • For the programming method. Each time you press the desired key. 7 Press [PTT]+[MR]+ POWER ON. STA CON 5 CONTROL OPERATION When in Remote Control mode. If not described. for example. or to operate the HF transceiver while relaxing in the living room or patio. Audio UHF freq. The Sky Command System allows you. TS-570S. instead of in the shack. Audios Control commands tResponse Commander Audio Control commands tResponse Transporter 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 VHF freq. 16 17 18 19 20 21 22 23 Your shack 83 . You will use one TH-D7A as both a remote control and speaker microphone. Both the Commander and Transporter use Full Duplex function to transfer audio and commands as below: VHF freq. to watch for and hunt DX while working around the house. or TS-870S HF transceiver. It will function as an interface between the Commander and the HF transceiver. This TH-D7A is called “Commander”. This system requires two TH-D7As and the optional cables which connect one TH-D7A to the HF transceiver. The TH-D7 connected with the HF transceiver is called “Transporter”. UHF freq.SKY COMMAND 2 (TH-D7A ONLY) The Sky Command 2 allows remote control of a TS-570D. HF freq. unwanted feedback may cause malfunction. x The Transporter automatically transmits its call sign in Morse at regular intervals because of the legal requirement.5 mm (1/8") 2-conductor plug You may install appropriate noise filters at the shown positions to prevent unwanted feedback from causing malfunction. use the MONI control to adjust the volume of sidetone. On TS-570D or TS-570S. On TS-870S. For these cables.5 mm (1/8") I/O unit GPS You need not worry about which end goes to which side HF transceiver COM connector EXT SP jack MIC connector 3.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 CONNECTING THE TRANSPORTER WITH THE HF TRANSCEIVER You can use the optional cables (PG-4R) to connect the Transporter with the HF transceiver. transmit sidetone must be output from the HF transceiver. 84 . I/O unit 2. therefore. Unwanted feedback may cause malfunction. Note: x Switch OFF both the Transporter and HF transceiver before making the connection. x When the Transporter is too close to the HF transceiver. x Do not share a regulated power supply between the Transporter and the HF transceiver. do not select “OFF” in Menu 21. contact your authorized KENWOOD dealer.5 mm (1/10") 3. ex. First switch ON the HF transceiver and press [SYNC] on the Commander. x Adjust the audio level on both the Transporter and HF transceiver. select 9600 bps and 1 stop bit (default) using the Menu Setup function. r On the Transporter Access Menu 4–1 to program the same call sign as you entered in step w {page 86}. • For the selectable frequencies. For operations in this mode. • Select the same tone frequency on both transceivers.) for the Transporter {page 86}. access Menu 4–4 and select “OFF”. • “PUSH [ 0 ] KEY TO START COMMANDER!!” appears. w On the Commander Access Menu 4–1 to program a call sign (9 digits max. WD6BQD. x On the HF transceiver. [1] to switch the Tone function OFF. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 u On the Commander Access Menu 4–4 and select “COMMANDER”. So you may add SSID characters. see “CONTROL OPERATION” on page 87. you cannot select “COMMANDER” or “TRANSPORTER” using Menu 4–4 . First connect the Transporter to the HF transceiver {page 84}. • You may enter your exact call sign. WD6BQD-1. • This call sign must be different from the one for the Commander.) for the Commander {page 86}. To exit the Sky Command mode. ex. Note: x Unless you program call signs. i On the Transporter Access Menu 4–4 and select “TRANSPORTER”. press [F]. y On the Commander Access Menu 4–3 and select and Transporter the tone frequency {page 86}. q On the Commander Select the same VHF and UHF and Transporter frequencies. e On the Commander Access Menu 4–2 to program a call sign (9 digits max. Now the Commander and Transporter are in Sky Command mode. Access Menu 4–2 to program the same call sign as you entered in step e {page 86}.PREPARATION FLOW The following steps should guide you to a good start of Sky Command operation. see the table given on page 22. t On the Transporter 85 . • “TRANSPORTER” appears. and press [DUP] to exit Full Duplex mode. [2] to select “4–2 (TRP CALL)”.PROGRAMMING CALL SIGNS 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 Press [MENU] to enter Menu mode. press [OK] twice. The built-in TNCs of the Commander and Transporter communicate each other when you send a control command from the Commander. the first 17 digit blinks. • You can enter 0 to 9. [1] to select “4–1 (CMD CALL)”. • Pressing [OK] after selecting the 9th digit completes the programming. PROGRAMMING A TONE FREQUENCY On receiving a tone from the Commander. On Commander 4–1 4–2 CMD CALL TRP CALL Call sign for Commander Call sign for Transporter On Transporter 4–1 4–2 CMD CALL TRP CALL Call sign for Commander Call sign for Transporter 6 Press [MENU] to exit Menu mode. same tone frequency. 18 19 5 4 Press [OK]. • The cursor moves to the next digit. or [4]. 15 2 Press [4]. each press of [TNC] switches entry as A. Press [ENT] to enter –. 16 • The display for entering characters appears. the Transporter causes the HF transceiver to enter Transmit mode. then 2. and –. B. C. • Each press of [ESC] causes the cursor to move backward. For example. • To complete programming after entering less than 9 digits. You can also use the keypad to enter alphanumeric characters in step 3. • Pressing [A/B] deletes the digit at which the cursor is blinking. On both the Commander and Transporter. Use the following Menu Nos. STA CON 5 STA CON 96BCONDUP 5 STA CON 96BCONDUP 7 9 7 9 20 21 22 23 3 Press [UP]/ [DWN] to select a character. The default is “NOCALL”. 96BCONDUP 7 9 86 . So you must program different call signs (9 digits max.) on these transceivers as the IDs of the TNCs. access Menu 4–3 (TONE FREQ) and select the desired. to program call signs: 5 Repeat steps 3 and 4 to enter up to 9 digits. A to Z. Tuning control Key Tuning control Function Frequency or memory channel number change In VFO mode: VFO A/ VFO B switch In Memory Recall mode: no change 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 UP/ DWN RIT offset or XIT offset change A/B POWER RX RIT 1 1 Power ON/ OFF HF frequency receive ON/ OFF Modulation mode switch RIT ON/ OFF XIT ON/ OFF RIT offset or XIT offset clear Split-frequency ON/ OFF Transfer from Memory to VFO In LSB.CONTROL OPERATION When in the Sky Command mode. and the VOL control will not change. then speak into the microphone. transceiver To transmit audio on a HF frequency To receive audio on a HF frequency To monitor the UHF band on the Commander Press and hold the PTT switch. the Commander will automatically enter transmit mode and send the corresponding control command to the Transporter. you can use these keys as numeric keys to enter a frequency or memory channel number. Press [RX]. [MONI]. Press and hold [MONI]. 87 . the keys of the Commander will function as below. To switch ON/ OFF the HF Press [POWER]. 1 M ± V1 FAST SYNC 1 ENT M/V After pressing [ENT]. or CW mode: 10 Hz/ 1 kHz switch In FM or AM mode: 1 kHz/ 10 kHz switch Current settings retrieve (from HF transceiver) In VFO mode: frequency entry ON In Memory Recall mode: channel number entry ON VFO/ Memory Recall mode switch MODE 1 XIT 1 CLR 1 SPLIT 1 Each time you press the desired key. First switch ON the HF transceiver and press [SYNC] on the Commander. Only the functions of [LAMP]. USB. x After pressing [MENU]. the Commander shows the current settings of the HF transceiver as below: 1 2 3 4 5 6 q e w t y r u q HF frequency w A (VFO A). and [MENU] will function. B (VFO B).99 9 t “FS” appears when [FAST] is ON. you can access only Menu 4–4. 12 13 14 15 16 17 18 19 20 21 22 23 Note: x On the Transporter. Pressing any other key will simply cause the Transporter to generate an error beep. USB. XIT 8 r OFF. CW. 00 ~ 99 (memory channel number) 7 e RIT. [MONI].99 ~ +9. only [LAMP]. y LSB. 11 SPLIT–M: A memory channel is used for transmitting. or AM 10 u SPLIT–A: VFO A is used for transmitting. SPLIT–B: VFO B is used for transmitting. using the 144 MHz band. x The Transporter will transmit its call sign in Morse every 10 minutes. –9.When [SYNC] is pressed. FM. x The APO timer does not operate on the transceiver with Transporter ON. 88 . Include your telephone number along with your name and address in case the service technician needs to call you. please include a photocopy of the bill of sale. Include a full description of the problem(s) experienced.MAINTENANCE GENERAL INFORMATION This product has been factory aligned and tested to specification before shipment. You may return this product for service to the authorized KENWOOD dealer from whom you purchased it. Please do not send subassemblies or printed circuit boards. please make your note legible. x When claiming warranty service. A copy of the service report will be returned with the product. or other proof-of-purchase showing the date of sale. and to the point. pack it in its original box and packing material. Send the complete product. include also your fax number and e-mail address. Don’t return accessory items unless you feel they are directly related to the service problem. serial number and dealer from whom this product was purchased. short. Attempting service or alignment without factory authorization can void the product warranty. or any authorized KENWOOD service center. SERVICE NOTE If you desire to correspond on a technical or operational problem. retain a written record of any maintenance performed on this product. Help us help you by providing the following: • Model and serial number of equipment • Question or problem you are having • Other equipment in your station pertaining to the problem 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 SERVICE When returning this product to your dealer or service center for repair. x For your own information. Note: Record the date of purchase. x CLEANING To clean the case of this product. Do not pack the equipment in crushed newspapers for shipment! Extensive damage may result during rough handling or shipping. 21 22 23 89 . complete. if available. use a neutral detergent 19 20 (no strong chemicals) and a damp cloth. 2 The transceiver is in Channel 2 Press [A/B]+ POWER ON to exit Display mode. Channel Display mode.TROUBLESHOOTING 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 The problems described in this table are commonly encountered operational malfunctions and are usually not caused by circuit failure. size. control after transmitting of packet data is completed. using the [UP]/ [DWN] or Tuning control. 3 Tone Alert is ON (Bell icon is 3 Press [F]. The current frequency step size does Select the appropriate frequency step You cannot select the exact desired frequency not allow the frequency to be selected. Page 2. function. Problem Nothing appears on the display when the transceiver is switched ON. Probable Cause 1 Low supply voltage 2 If using the optional DC cable: a) Bad power cable or connections Corrective Action 1 Recharge the battery pack or replace the batteries. 2 Ref. b) Open (blown) power supply fuse b) Investigate the cause for the open fuse. You cannot recall any You have stored no data in any of the Store the desired frequencies in memory channels using the current memory channels. memory channels using the current band. Transceiver Lock. 4 a) Check the power cable and connections. [ENT] to switch OFF Tone visible). 5 — 50 31 47 — 46 27 90 . Most keys and the 1 Transceiver Lock is ON (Key icon is 1 Press [F] (1 s) to switch OFF Tuning control do not visible). or the display is blinking ON and OFF. then correct/replace as necessary. 4 Packet data was being transmitted 4 Operate the keys or the Tuning using the data band. Alert. Replace the fuse. band. 1 Select the correct squelch level so that the squelch is opened only when signals are present. 2 You did not select the same transfer rate as the target station. Packet operation results 1 The squelch is open. 3 Access Menu 1–5–5 and select “OFF”. then [UP]/ [DWN] to correctly adjust the volume balance between the two bands. 3 TX Inhibit is ON. The Automatic Power Off (APO) Switch OFF the APO function. in no connects with other stations. hear audio. Corrective Action 1 Select a frequency within the allowable transmit frequency range. Ref. 5 Packet data was being transmitted 5 Press the PTT switch after transmitting using the data band. of packet data is completed. 48 8 54 91 . Turning the VOL control The speaker for the band you wanted does not allow you to to monitor was muted. [ENT] to switch OFF Tone Alert. 2 Use HBAUD command to select the appropriate transfer rate. [MHz] repeatedly so neither “+” nor “–” is visible. function is ON. Press [BAL]. 4 Press [F]. Page 7 1 2 3 4 5 6 21 51 47 — 49 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 The transceiver switches OFF for no apparent reason. 2 Press [F]. 2 You selected a transmit offset that places the transmit frequency outside the allowable range. 4 Tone Alert is ON. Probable Cause 1 You selected a frequency outside the allowable transmit frequency range.Problem You cannot transmit by pressing the PTT switch. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 92 . 85 or 45.85 n (fSV – 45. the VC-H1 with a SSTV mode. an internal heterodyne may be heard. 2 Press [SYNC] occasionally to read the status of the HF transceiver. control commands from being correctly transmitted.05) – 4 (fV + 38. [3] to switch OFF the CTCSS. You cannot You failed to correctly enter superimpose information to be superimposed.05) – n (fV + 38.85) = 38.85) = 38.05) – 2 (fV + 38. 2 (fU – 45. You cannot program Bad cable connections.85) = 38. Page — 1 2 3 4 5 6 7 8 9 10 11 12 Operating the 1 Too large distance between the Commander simply Commander and Transporter causes it to output an prevents correct data error beep and does not communications. 59 Refer to the instruction manual for the VC-H1 and correctly connect the VC-H1 to the transceiver.05 (fU – 45. Ref. 58. or 5. 4. Press [F].85 or 45. fV = VHF frequency (band A) fU = UHF frequency (band B) fSV = VHF frequency (band B) 93 . 87 40 Use Menu 3–1 to 3–6 to correctly enter the desired information. transceiver. You cannot hear audio You switched ON the CTCSS on the received by the HF 144 MHz band of the Commander. This is not a defect.Problem Probable Cause Corrective Action 1 Operate the Commander within a distance that allows the two transceivers to show a full-scale S-meter reading. allow you to control the 2 Bad radio wave conditions prevent HF transceiver.05 where n = 3. 57 13 14 15 16 17 18 19 20 21 22 23 Note: When two received frequencies have relationships per the equation below or other similar relationships. information onto the VC-H1 monitor. OPTIONAL ACCESSORIES 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 SMC-32 Speaker Microphone SMC-33 Remote Control Speaker Microphone SMC-34 Remote Control Speaker Microphone (with Volume Control) HMC-3 Head Set with VOX/PTT EMC-3 Clip Microphone with Earphone PB-38 Standard Battery Pack (6 V/ 650 mAh) PB-39 High-power Battery Pack (9.6 V/ 600 mAh) BT-11 Battery Case BC-17 Wall Charger BC-19 Rapid Charger SC-40 Soft Case PG-2W DC Cable 94 . 95 .A. This manual gives further detailed information on specialized communications including Packet and APRS.S.1 PG-3J Filtered Cigarette Lighter Cable VC-H1 Interactive Visual Communicator PG-4V Connection Cable to VC-H1 PG-4R Sky Command Cable Kit (U./ Canada only) 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 PG-4W Connection Cable to Computer (With a memory store program 1 and a separate manual (document file) 2) 1 2 This software is mainly used to program memory channels via a personal computer. 5 V line in the transceiver.5 plug 3. Ø3.5 plug SP jack Ø2.5 V MIC PTT Note 1 PTT switch PTT switch Note 2 10µF External microphone. TNC TX.3 V is developed. approximately 3.5 plug CONNECTING EQUIPMENT FOR REMOTE CONTROL Make connections as shown when remotely controlling equipment. Note 2: A 10 µF capacitor is not required in the following cases: • When the other equipment has DC blocking capacitors. • When a 2-terminal electret condenser microphone is used. External microphone Note 2 10 µF Note 1: Voltage is developed across the 100 Ω resistor in the 3. 17 Note 2: A 10 µF capacitor is not required in the following cases: • When the other equipment has DC blocking capacitors.5 V line in the transceiver. TNC RX. refer to the diagram below. Lock SW SW-1 3. approximately 3. 18 19 20 21 22 23 • When a 2-terminal electret condenser microphone is used. 15 Note 1: Voltage is developed across the 100 Ω resistor in the 3. etc. When 2 mA flows. 96 .9K SW-2 10K SW-3 27K CONNECTING OTHER EXTERNAL EQUIPMENT When connecting an external speaker.3 V is 16 developed. Speaker Ground 100 Ω SP External speaker Ø2. an external microphone. or other equipment such as a TNC for packet radio to the SP jack or MIC jack. etc.EQUIPMENT CONNECTIONS 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Note 1 MIC jack Ø3.5 plug External speaker. When 2 mA flows.5 V MIC PTT 3. 1. 90 mA Average 25 mA Approx.5 ~ 15.5 mm Approx.6 V (battery terminals) Transmit with H.SPECIFICATIONS Frequency range Mode Usable temperature range Rated voltage External power supply (DC IN) Battery terminals Receive with no signals 1 Battery Saver ON 2 TNC ON Transmit with H. 9.3 A Approx.5 ~ 16.6 A Approx. 1.8 V) 4. 1. 115 mA Approx.0 V (6. 340 g/ 12.5 mm/ 2.6 A Approx. and hand strap included 97 .8 V (DC IN) Transmit with H. 6.70" x 1. 6.4 oz Approx. 45 mA 2 With one band blanked (TNC OFF): Approx.7 A Approx.4 A Approx.0 x 119.5 x 35. 300 mA Negative 54. 1. 1.0 V) Approx.7 A Approx.0 V (13. 25 mA 3 Projections not included 4 Antenna. F2D (FSK) –20°C ~ +60°C (–4°F ~ +140°F) 5.0 V (battery terminals) Transmit with L.0 oz Within ±10 ppm Within ±15 ppm 2 kΩ 50 Ω 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Current Ground method Dimensions (W x H x D) 3 Weight 4 Frequency stability Microphone impedance Antenna impedance 1 With one band blanked (TNC OFF): Approx. 380 g/ 13.5 x 43.0 V (battery terminals) TH-D7A (with a PB-39 installed) TH-D7E (with a PB-38 installed) TH-D7A (with a PB-39 installed) TH-D7E (with a PB-38 installed) –10 ~ +50 °C –20 ~ +60 °C General TH-D7A TH-D7E VHF Band UHF Band 144 ~ 148 MHz 438 ~ 450 MHz 144 ~ 146 MHz 430 ~ 440 MHz F3E (FM).71" 54.0 x 119. 500 mA Approx. 1. belt hook.0 V (battery terminals) Transmit with EL. 13.13" x 4. 6. F1D (GMSK). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Power output Transmitter H, 13.8 V H, 9.6 V H, 6.0 V L, 6.0 V EL, 6.0 V VHF Band 6W UHF Band 5.5 W Modulation Maximum frequency deviation Spurious emissions (at high transmit power) Approx. 5 W Approx. 2.5 W Approx. 2.2 W Approx. 0.5 W Approx. 50 mW Reactance Within ±5 kHz –60 dB or less Receiver Circuitry 1st intermediate frequency 2nd intermediate frequency Sensitivity (12 dB SINAD) 1 Squelch sensitivity Selectivity (–6 dB) Selectivity (–40 dB) 9.6 V (battery terminals) Audio output (10% distortion) 6.0 V (battery terminals) 1 VHF sub-band: 0.28 µV or less VHF Band UHF Band Double conversion superheterodyne 38.85 MHz 45.05 MHz 450 kHz 455 kHz 0.18 µV or less 0.1 µV or less 12 kHz or more 28 kHz or less 450 mW or higher (8 Ω load) 300 mW or higher (8 Ω load) 17 Specifications are subject to change without notice due to advancements in technology. 18 19 20 21 22 23 98 APPENDIX TNC COMMANDS LIST The commands supported by the built-in TNC are listed below. You must enter a space between a command name (or short-form) and a parameter, or between two parameters; ex. AU OFF, BEACON EVERY 18. Command Name AUTOLF Short AU Default ON Parameter ON/ OFF Description BEACON B EVERY 0 BTEXT CALIBRAT CHECK CONNECT CONVERSE CPACTIME CR DISCONNE BT CAL CH C CONV or K CP CR D — — 30 — — OF F ON — When ON, sends a line feed (LF) to the computer after each carriage return (CR). If set to EVERY, sends a beacon packet at intervals of the EVERY/ specified period (n). If set to AFTER, sends a beacon packet AFTER n only once after the specified period (n). The unit of n is (n = 0 ~ 250) 10 seconds. 0 ~ 159 Specifies the content of the data portion of a beacon packet. characters Sends a space/mark square wave (50/50 ratio). Enter Q to — exit Calibrate mode and restore the Command mode. Specifies the interval from signal drop-out until execution of 0 ~ 250 disconnection. The unit of the parameter is 10 seconds. Call1 (VIA Sends a connect request. Call1 is the call sign of the station call2, call3, ... to be connected to. Call2 to call9 are call signs of stations to call9) be digipeated through. Causes the TNC to enter Converse mode. Press [Ctrl]+[C] to — restore the Command mode. When ON and in Converse mode, sends a packet at intervals ON/ OFF of the period determined by PACTIME. When ON, appends a carriage return (CR) to all packets to be ON/ OFF sent. — Sends a disconnect request. 99 Command Name Short Default Parameter Description Causes the TNC to display the current status of all the commands. You can also specify a class identifier A, C, H, I, L, M, or T to display the status of only the desired command class. Enter a space between the command name and a class identifier; ex. DISPLAY H. DISPLAY DISP — — A (ASYNC): RS-232C port parameters C (CHAR): Special TNC characters H (HEALTH): Counter parameters I (ID): ID parameters L (LINK): TNC-to-TNC link status M (MONITOR): Monitor parameters T (TIMING): Timing parameters DWAIT ECHO DW E 30 ON 0 ~ 25 0 ON/ OFF FIRMRNR FIR OF F ON/ OFF FLOW FRACK GBAUD GPSSEND GPSTEXT F FR GB GPSS GPST ON 3 4800 — $PNTS ON/ OFF 0 ~ 250 4800/ 9600 0 ~ 159 characters 0~6 characters Specifies the interval from no carrier detection until execution of transmission. The unit of the parameter is 10 milliseconds. When ON, causes the TNC to echo received characters to the computer. The other station sends a notice (packet) to you if it is not ready to receive data. When ON, receiving such a notice causes the TNC to suspend transmission until it receives a “ready” notice. When ON, starting key entry causes the computer to stop displaying received packets. Specifies the interval from one transmission until retry of transmission. The unit of the parameter is 1 second. Selects 4800 or 9600 bps as the transfer rate between the TNC and the GPS receiver. Specifies the content of data to be output to the GPS receiver; this data is used to program the default settings on the receiver. The output data is not stored in memory. Specifies the type of a message to be determined by LTEXT. 100 0 ~ 159 characters 0 ~ 250 ON/ OFF ON/ OFF ON/ OFF ON/ OFF Specifies the content of a message to be included in GPS data. When ON. a message appears like a received beacon packet. causes the TNC to display the entire digipeat list for monitored packets. Specifies the interval for displaying a message determined by LTEXT on the screen. causes the TNC to monitor packets. sends a packet only once after (n = 0 ~ 250) the specified period (n). If set to AFTER. sends a packet at intervals of the specified AFTER n period (n). The unit of n is 10 seconds. EVERY/ If set to EVERY. . Call2 to call9 are call signs of stations to be call9) digipeated through. the destination. call3.Command Name HBAUD LOCATION Short HB LOC Default 1200 EVERY 0 Parameter 1200/ 9600 Description Selects 1200 or 9600 bps as the transfer rate between packet stations. When ON.. Call1 (VIA Specifies call signs to send GPS data. 101 . sends GPS data at intervals of the specified AFTER n period (n). EVERY/ If set to EVERY. sends GPS data only once after (n = 0 ~ 250) the specified period (n). When ON. SSID 0 ~ 255 Specifies the maximum length of the data portion of a packet. If set to AFTER. causes the TNC to also monitor control packets. The unit of the parameter is 1 second. causes the TNC to monitor other stations while in connection with the target station. When ON. When OFF. LPATH LTEXT LTMON MCOM MCON MONITOR MRPT MYCALL PACLEN PACTIME LPA LT LTM MCOM MC M MR MY P PACT GPS — 0 OFF OFF ON ON NOCALL 12 8 AFTER 10 6 characters + Specifies your call sign. The unit of n is 100 milliseconds.. causes it to monitor only information packets. Call1 is the call sign of call2. Command Name PERSIST PPERSIST RESET RESPTIME RESTART RETRY SENDPAC SLOTTIME TRACE TRIES TXDELAY UNPROTO XFLOW 102 Short PE PP RESET RES RESTART Default 128 ON — 5 — 10 $0D 3 OFF 0 50 CQ ON Parameter 0 ~ 255 ON/ OFF — 0 ~ 250 — 0 ~ 15 0 ~ $7F 0 ~ 250 ON/ OFF 0 ~ 15 0 ~ 12 0 Description Specifies a parameter to calculate probability for the PERSIST/SLOTTIME method. Specifies the number of transmission retries. The unit of the parameter is 10 milliseconds. a connect request is sent again after the specified number of retries. call2. Specifies the time delay between PTT ON and start of transmission. Restores the default status for all the commands. causes the TNC to display all received packets in their entirety. Call1 is the call sign of the destination. Call2 to call9 are call call9) signs of stations to be digipeated through. X . When ON. The unit of the parameter is 100 milliseconds.. or hardware flow control when OFF. Specifies the acknowledgment packet transmission delay. Causes the TNC to use the PERSIST/SLOTTIME method when ON. Specifies a character which forces a packet to be sent. or the DWAIT method when OFF.. The unit of the parameter is 10 milliseconds. Causes the TNC to function as if it is switched OFF then ON. RE SE SL TRAC TRI TX U Call1 (VIA Specifies call signs to send a packet in Unprotocol mode. . Specifies the period of random number generation intervals for the PERSIST/SLOTTIME method. ON/ OFF Causes the TNC to perform software flow control when ON. Specifies the number of transmission retries programmed in the retry counter. call3. If packets are not correctly accepted while in connection. [5]. [MONI] ¬ [UP]/ [DWN] ¬ [OK] F (1 s) [MENU]. [5]. [1] ¬ [UP]/ [DWN] ¬ [OK] ¬ Enter up to 8 digits Ref. [1] ¬ [UP]/ [DWN] ¬ [OK] [MENU]. [LAMP] [MENU]. [4]. Function Key Operation POWER OFF ¬ [F]+ POWER ON ¬ [UP]/ [DWN] ¬ [OK] ¬ [UP]/ [DWN] ¬ [OK] Recall a memory channel ¬ [CALL] (1 s) Select band ¬ [VFO] ¬ [CALL] (1 s) Select band ¬ [MR] (1 s) Select band ¬ [VFO] ¬ [MHz] (1 s) Select band ¬ [VFO] (1 s) [MENU]. [4] ¬ [UP]/ [DWN] ¬ [OK] [MENU]. [1] ¬ [UP]/ [DWN] ¬ [OK] [MENU]. [1]. [1]. [5] ¬ [UP]/ [DWN] ¬ [OK] Function AIP ON/ OFF (TH-D7A) AIP ON/ OFF (TH-D7E) APO ON/ OFF Automatic Repeater Offset ON/ OFF ASC ON Battery Saver Interval Select Beep ON/ OFF Channel Display ON / OFF Data Band Select Display Contrast Adjust Lamp Latch ON / OFF Power-ON Message Enter Key Operation [MENU]. [2]. [5]. [1]. [1]. [5]. [1]. [6] ¬ [UP]/ [DWN] ¬ [OK] [MENU]. [5]. [2] ¬ [UP]/ [DWN] ¬ [OK] [F]. [5]. [1].QUICK REFERENCE GUIDE Note: Not all functions are covered by this guide. [8] ¬ [UP]/ [DWN] ¬ [OK] [MENU]. [1]. [1]. [2] ¬ [UP]/ [DWN] ¬ [OK] [F]. [1] ¬ [UP]/ [DWN] ¬ [OK] [REV] (1 s) [MENU]. [1]. [5]. [3] ¬ [UP]/ [DWN] ¬ [OK] POWER OFF ¬ [A/B]+ POWER ON [MENU]. [1]. [1]. [1]. Page 32 Reset (Partial/ Full) Scan Start Call/Memory (TH-D7A only) Call/VFO (TH-D7A only) Memory MHz VFO Scan Resume Method Select Squelch Level Adjust Transceiver Lock ON/ OFF Tuning Control Enable TX Deviation Switch (TH-D7E only) TX Inhibit ON/ OFF 38 38 35 36 35 34 8 50 50 51 51 103 . [5]. [7] ¬ [UP]/ [DWN] ¬ [OK] [MENU]. Page 51 51 49 23 24 49 47 31 55 48 48 50 Ref. [2]. [2] ¬ [UP]/ [DWN] ¬ [OK] [MENU]. [1]. [1]. [1]. [2] (1 s) [F]. [6] ¬ [UP]/ [DWN] ¬ [OK] ¬ Enter up to 20 digits [2]. [2] ¬ [UP]/ [DWN] ¬ [OK] [F]. [5] ¬ [UP]/ [DWN] ¬ [OK] Select 118 MHz band ¬ [F]. [7] ¬ [UP]/ [DWN] ¬ [OK] [2]. [7] ¬ [UP]/ [DWN] ¬ [OK] ¬ [UP]/ [DWN] ¬ [OK] [F]. ID Start CTCSS ON/ OFF CTCSS Frequency Select CTCSS Freq. [C] ¬ [UP]/ [DWN] ¬ [OK] Selection My Call Sign GPS Receiver Latitude/ Longitude Data Position Comment Station Icon Status Text Beacon Transmit Interval Packet Path Beacon Transmit Method Group Code Reception Restriction Distance Unit Ref. [3] ¬ See reference page [2]. Page 66 62 68 69 67 70 75 72 74 71 75 65 Memory Channel Lockout ON/ OFF Tone ON/ OFF Tone Frequency Select Tone Freq. [5] ¬ [UP]/ [DWN] ¬ [OK] [2]. [4] ¬ [UP]/ [DWN] ¬ [OK] [F]. [8] ¬ [UP]/ [DWN] ¬ [OK] ¬ Enter up to 32 digits [2]. Page 36 22 22 25 40 39 40 21 51 46 46 Key Operation [2]. Function Ref. ID Start Offset Frequency Select AM/FM Mode Switch 1 Lower/ Upper Freq. [2] ¬ [UP]/ [DWN] ¬ [OK] [2]. [0] [F]. [A] ¬ [UP]/ [DWN] ¬ [OK] ¬ Enter up to 9 digits [2]. [1] [F]. [1] ¬ [UP]/ [DWN] ¬ [OK] ¬ Enter up to 9 digits [2]. [8] ¬ [UP]/ [DWN] ¬ [OK] Recall a memory channel ¬ [F]. [9] ¬ [UP]/ [DWN] ¬ [OK] ¬ Enter up to 8 digits 1 Press [MENU] first to access the APRS Menu Nos.First select the desired band. [4] (1 s) [F]. [B] ¬ [UP]/ [DWN] ¬ [OK] [2]. Limit Select Frequency Step Size Select Naming a Memory Channel 29 TH-D7A only 104 . [9] ¬ [UP]/ [DWN] ¬ [OK] [2]. Key Operation Recall a memory channel ¬ [F]. [4] ¬ [UP]/ [DWN] ¬ [OK] [2]. [3] [F]. [6] [VFO] ¬ [F]. ................. 77 Transmitting ... 28 Storing........... 50 Programmable VFO ...................................... 25 Frequency.......................................... 30 Recalling ....... 32 Reverse Function . 29 Recalling .................................... Selecting .. 7........... 35 Sky Command 2 (TH-D7A only) ................... Simplex .......................................................... 50 Memory Channels Clearing ...................................... 9 Troubleshooting .......................... 55 Display Contrast.......... Selecting .. Odd-split ................................................................. 24 Scan Call/Memory . 45 Frequency Step Size .... 51 TX Inhibit ................................ 66~75 Receiving ............. 16 Microphone Control ......... 43 TX Hold ......... ID .......................INDEX Accessories Optional ............................................................................................ ID ....................... 46 Full Duplex ... 90 TX Deviation (TH-D7E only) .................................. 8 TNC .............. 31 CTCSS Freq.................... 32 Partial (VFO) ...................................... 79 Receiving ................................. 55 Lamp Function ...................................... 38 Memory ...... 51 Volume Balance................................................................................................................... 97 Squelch.............................. 41 Frequency.. Selecting ......... 40 Frequency................................. 31 Menu . 46 Repeater Access ......... 35 MHz ...................................... 1 Advanced Intercept Point (AIP) .. 36 Naming ......... 39 Using ...................... 80 Automatic Power Off (APO) ............................................................................................... 47 Transmit Power....................................................................... Selecting ................................ 74 APRS Message Entering ..................... 24 Band....................................................... 94 Supplied ........... 47 Call Channel Contents..... Adjusting ........................................... 27 Storing.................. 48 Lock.............. 38 Call/VFO ..... 48 Wireless Remote Control (TH-D7A only) .................................................................................. 34 VFO ................... 41 Storing Numbers .......................... 22 Tone Alert ............. 48 DTMF Making Calls . 23 Offset Direction .. 7........................................ 28 Initializing ..................... 27 Transfer to VFO .............................. 22 Freq. 83 Slow-Scan Television (SSTV) ... 40 Data Band ......................... Selecting ........ 49 Automatic Simplex Check (ASC) ...... 51 APRS Programming ..................... 20 Reset Full .................... 21 Packet Operation ... Adjusting ....................................................... 44 Offset Automatic Repeater ............... Transceiver ...................................................................................................................... 42 Transmitting Stored Numbers ... 49 Beep ON/OFF ........................... 12 Battery Saver . 63 Transmitting ........................................................................................................... 81 53 ........................................ 52 Power-ON Message ................... Changing . 21 Offset Frequency .... 37 Resume Method . 32 Locking Out ........... 57 Specifications .......................................................................................... Adjusting ....................... 30 Channel Display ... 53 Tone Activating ................ 36 Program ......................................................... This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/46224836/THD7A
CC-MAIN-2016-44
refinedweb
29,203
77.13
Serverless is a powerful and popular paradigm where you don’t have to worry about managing and maintaining your application infrastructure. In the serverless context, a function is a single-purpose piece of code created by the developer but run and monitored by the managed infrastructure. A serverless function’s value is its simplicity and swiftness, which can entice even those who don’t consider themselves developers. This article introduces you to Red Hat OpenShift Serverless Functions, a new developer preview feature in Red Hat OpenShift Serverless 1.11. I will provide an overview, then present two example applications demonstrating Serverless Functions with Node.js. Please check the OpenShift Serverless Functions Quick Start document for the example prerequisites. OpenShift Serverless Functions Red Hat OpenShift Serverless leverages the power of Knative to deliver serverless, event-driven applications that scale on demand. With the OpenShift Serverless 1.11 release, we have added the new Serverless Functions feature, currently available as a developer preview. Serverless Functions comes with pre-defined templates and runtimes and provides a local developer experience. Together, these features make it very easy to create serverless applications. How to get Serverless Functions Serverless Functions is bundled with the OpenShift Serverless command-line interface (CLI), kn. When you use an OpenShift Serverless Operator for installation, OpenShift Serverless is automatically deployed, and managed on OpenShift. You can access Serverless Functions with the following command: $ kn func Note: See the OpenShift Serverless documentation for installation instructions. What's included? Serverless Functions comes with predefined runtimes for popular languages such as Quarkus, Node.js, and Go. These runtimes are based on Cloud Native Buildpacks. After you choose a runtime, Serverless Functions creates the appropriate project scaffolding so that you can focus on writing business logic. Serverless Functions also includes a local developer experience to support a quick inner loop of iterative development and testing. Invoking Serverless Functions You can invoke Serverless Functions using plain HTTP requests or CloudEvents with OpenShift Serverless eventing components. OpenShift Serverless Functions comes with out-of-the-box project templates to jumpstart your code for both the HTTP and CloudEvents trigger types. Next, we'll explore two examples. For the first example, we'll configure Serverless Functions for HTTP requests. For the second example, we'll use CloudEvents. Please use the Serverless Functions quick start document to ensure that you have the example prerequisites installed. Example 1: Create a serverless function for HTTP requests Once you have the prerequisites installed, create a new directory for your serverless function. Once you are in the directory, execute the following command to create and deploy a new serverless function: $ kn func create By default, the function is initialized with a project template for plain HTTP requests. You can choose your programming language by entering Node.js, Quarkus, or Go as the value for the -l flag. If you do not provide a runtime with the -l flag, the default runtime is Node.js. We'll use Node.js for both of our examples. Note: You can use the -c flag to prompt the CLI to guide you in creating your first function through the interactive developer experience, which prompts you to add the language and event values. Type -help anytime for assistance. The Node.js runtime By default, entering the command $ kn func create creates the scaffolding for a function that is triggered by a plain HTTP request. The scaffolding for our default Node.js runtime includes index.js, package.json, and func.yaml files. We can extend the index.js base code to develop our serverless function. As a start, let's add a return message of Greeting <username> in the provided handleGet(context) method. Figure 1 shows the handleGet function in index.js. Deploy the function Next, we'll deploy this function to our OpenShift cluster. Be sure that you are logged into an OpenShift cluster from your local environment, then type the following command with the project name or cluster namespace: $ kn func deploy -n <namespace> Remember that you can use the -c flag for an interactive experience. Serverless Functions will prompt you to provide a container registry where the resulting image is uploaded. DockerHub is the default registry, but you can use any public image registry. Now, go to the Topology view in the OpenShift developer console. You will see your function deployed as a Knative service, as shown in Figure 2. Test the function We can use the routes URL shown in Figure 2 to test our deployed serverless function. Enter the following command to delete the function from your cluster: $ kn func delete For a local developer experience, we can test serverless functions using standard language tooling or in a container running locally. Use the following command on the kn command-line to build the container image: $ kn func build To test the built image container in a local environment, enter: $ kn func run Use the curl command to test your deployed image: $ curl ‘’ You may also use the browser to see the results, as shown in Figure 3. Example 2: Create a serverless function for CloudEvents For our second example, we'll create a serverless function that responds to CloudEvents rather than HTTP requests. Before you start, please check the quick start document to ensure that you have the prerequisites installed for this example. Create a new serverless function project We'll use the same command that we used previously to create a new project. This time, however, we will provide an events value for the -t flag. Alternatively, we could use the -c flag for interactive prompts. $ kn func create -l <node|quarkus> -t events To receive CloudEvents, we will need Knative eventing components, so we'll set that up next. Log in to the OpenShift developer console and navigate to the Developer perspective. Click the Add section to see the Channel tile highlighted in Figure 4. This tile creates a default channel. Now, we need an event source. For that, we will go back to the Add section and click on the Event Source tile shown in Figure 5. Next, as shown in Figure 6, we will select and configure a ping source as the event source for our deployed function. Note that the Sink section displays the deployed function and the channel we've just created. For this example, we will choose the channel as the sink for our event source. After creating the event source, we can view all the components in the Topology view, as shown in Figure 7. To add a trigger to the deployed function, hover over the channel, then click and drag the blue line to connect the channel to the function. Figure 8 shows the full deployment details in the Topology view. When the function starts receiving events, Knative spins up the function pod, and the logs show the call to the function. We have just created and deployed an OpenShift serverless function. Looking forward OpenShift Serverless Functions is available as a developer preview in OpenShift Serverless 1.11. It is available to all OpenShift users. We will release new features in the coming months, and your feedback is greatly appreciated. This article is the first in a series introducing Serverless Functions. My next article will introduce you to creating serverless functions with Quarkus, the supersonic, subatomic Java runtime. In the meantime, you can learn more about OpenShift Serverless Functions by reading the OpenShift Serverless 1.11 release announcement, the OpenShift Serverless documentation, and the OpenShift Serverless Functions documentation.Last updated: October 19, 2021
https://developers.redhat.com/blog/2021/01/04/create-your-first-serverless-function-with-red-hat-openshift-serverless-functions
CC-MAIN-2022-05
refinedweb
1,257
55.64
Update note: Lea Marolt Sonnenschein updated this tutorial for iOS 12, Xcode 10 and Swift 4.2. Ray Wenderlich wrote the original. Core Graphics is one of those frameworks that’s easy to avoid as an iOS developer. It’s a little obscure, the syntax is not super modern and Apple doesn’t give it as much love at WWDC as they should! Plus, you can avoid it very easily by just using images instead. However, Core Graphics is an insanely powerful tool to master! You can free yourself from the shackles of graphic designers and wield the mighty CG sword to create amazing UI beauty on your own. In this tutorial, you’ll learn how to create a customizable, reusable glossy button using only Core Graphics. Haven’t you heard skeuomorphism is back in style? ;] In the process, you’ll learn how to draw rounded rectangles, how to easily tint your Core Graphics drawings and how to create gradient and gloss effects. There are many options for customizing UIButtons already, from full-fledged custom UIButton classes to smaller extensions. But what’s been missing in this discussion is a detailed Core Graphics tutorial for how to customize the buttons yourself, from start to finish. It’s pretty simple; you can wield it to get the exact look you want in your app. It’s time to get started! Getting Started Use the Download Materials button at the top or bottom of this tutorial to download the starter project. Open the starter project: CoolButton Starter. The project structure is very simple, consisting of only the files created when choosing the Single View App Xcode template. The only two major exceptions are: - A couple of images in the Assets.xcassets catalog. - You can find a pre-designed UI for ViewControllerin Main.storyboard. Now go to File ▸ New ▸ File…, choose the iOS ▸ Cocoa Touch Class and click Next. In the next menu, enter CoolButton as the class name. In the subclass field, type UIButton. For language, choose Swift. Now click Next and then Create. Open CoolButton.swift and replace the class definition with the following: class CoolButton: UIButton { var hue: CGFloat { didSet { setNeedsDisplay() } } var saturation: CGFloat { didSet { setNeedsDisplay() } } var brightness: CGFloat { didSet { setNeedsDisplay() } } } Here, you create three properties that you’ll use to customize the color’s hue, saturation and brightness. When the properties are set, you trigger a call to setNeedsDisplay to force your UIButton to redraw the button when the user changes its color. Now, paste the following code at the bottom of CoolButton, right before the last curly bracket: required init?(coder aDecoder: NSCoder) { self.hue = 0.5 self.saturation = 0.5 self.brightness = 0.5 super.init(coder: aDecoder) self.isOpaque = false self.backgroundColor = .clear } override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0) context.setFillColor(color.cgColor) context.fill(bounds) } Here, you initialize the variables and fill the button with a pre-configured color to make sure everything’s working from the start. Configuring the Button’s UI Open Main.storyboard to configure the UI. There’s one view controller containing three sliders — one for hue, one for saturation and one for brightness. You’re missing the UIButton, so add that to the top of the screen. Go to Object Library, type in UIButton, and drag it into the screen. Time for some auto-layout! Control-drag from the button to the view and choose Center Horizontally in Safe Area. Control-drag from the button to the hue label and choose Vertical Spacing. Now, resize the button to a size that you like. Control-drag left or right from the button and choose Width. Control-drag up or down from the button and choose Height. Note: If you have difficulty setting Width and Height constraints by dragging, select the button and click the Add New Contraints button in the lower right of the canvas. It looks a bit like a Tie fighter from Star Wars. Next, delete the text that says “Button” by double clicking it and pressing the Delete key. With the button still selected, go to the Inspectors sidebar on the right-hand side of the screen and click on the Identity inspector. In Custom Class ▸ Class, enter CoolButton to make your button an instance of the CoolButton class. With the button in place, you’re ready to start hooking the UI up to the code! Making Your Button Functional Open ViewController.swift and replace the class definition with the following: class ViewController: UIViewController { @IBOutlet weak var coolButton: CoolButton! @IBAction func hueValueChanged(_ sender: Any) { } @IBAction func saturationValueChanged(_ sender: Any) { } @IBAction func brightnessValueChanged(_ sender: Any) { } } Here, you’re declaring a reference to the button that you just created in your storyboard. You’re also declaring the callbacks that occur when the values of the configuration sliders change. Now, open Main.storyboard again and choose Assistant Editor in the top bar to show ViewController.swift and Main.storyboard side by side. Control-drag from the button in View Controller Scene ▸ ViewController on the left and connect it to the coolButton outlet. Similarly, control-drag from the sliders in View Controller Scene ▸ ViewController on the left and connect each one to the appropriate value-changed callback on the right. Next, switch to ViewController.swift and implement the value-changed callbacks of the sliders: @IBAction func hueValueChanged(_ sender: Any) { guard let slider = sender as? UISlider else { return } coolButton.hue = CGFloat(slider.value) } @IBAction func saturationValueChanged(_ sender: Any) { guard let slider = sender as? UISlider else { return } coolButton.saturation = CGFloat(slider.value) } @IBAction func brightnessValueChanged(_ sender: Any) { guard let slider = sender as? UISlider else { return } coolButton.brightness = CGFloat(slider.value) } By default, UISliders have a range of 0.0 to 1.0. This is perfect for your hue, saturation and brightness values, which also range from 0.0 to 1.0, so you can just set them directly. Phew, after all this work, it’s finally time to build and run! If all works well, you can play around with the sliders to fill the button with various colors: Drawing Rounded Rectangles It’s true that you can easily create square buttons, but button styles come and go faster than the weather changes in Chicago! In fact, since we originally released this tutorial, square buttons and rounded rectangle buttons have flip-flopped back and forth for the number-one spot in the button pageant, so it’s a good idea to know how to make both versions. You can also argue that it’s quite easy to create rounded rectangles by simply changing the corner radius of a UIView, but where’s the fun in that? There’s so much more gratification, or maybe madness, in doing it the hard way. :] One way to make rounded rectangles is to draw arcs using the CGContextAddArc API. Using that API, you can draw an arc at each corner and draw lines to connect them. But that’s cumbersome and requires a lot of geometry. Fortunately, there’s an easier way! You don’t have to do as much math and it works well with drawing rounded rectangles. It’s the CGContextAddArcToPoint API. Using the CGContextAddArcToPoint API The CGContextAddArcToPoint API lets you describe the arc to draw by specifying two tangent lines and a radius. The following diagram from the Quartz2D Programming Guide shows how it works: When you’re working with a rectangle, you know the tangent lines for each arc you want to draw — they are simply the edges of the rectangle! And you can specify the radius based on how rounded you want the rectangle to be — the larger the arc, the more rounded the corners will be. The other neat thing about this function is that, if the current point in the path isn’t set to where you tell the arc to begin drawing, it will draw a line from the current point to the beginning of the path. So you can use this as a shortcut to draw a rounded rectangle in just a few calls. Drawing Your Arcs Since you’re going to create a bunch of rounded rectangles in this Core Graphics tutorial, and you want your code to be as reusable as possible, create a separate file for all of your drawing methods. Go to File ▸ New ▸ File…, and choose iOS ▸ Swift File. Press Next, call it Drawing and click Create. Now, replace import Foundation with the following: import UIKit import CoreGraphics extension UIView { func createRoundedRectPath(for rect: CGRect, radius: CGFloat) -> CGMutablePath { let path = CGMutablePath() // 1 let midTopPoint = CGPoint(x: rect.midX, y: rect.minY) path.move(to: midTopPoint) // 2 let topRightPoint = CGPoint(x: rect.maxX, y: rect.minY) let bottomRightPoint = CGPoint(x: rect.maxX, y: rect.maxY) let bottomLeftPoint = CGPoint(x: rect.minX, y: rect.maxY) let topLeftPoint = CGPoint(x: rect.minX, y: rect.minY) // 3 path.addArc(tangent1End: topRightPoint, tangent2End: bottomRightPoint, radius: radius) path.addArc(tangent1End: bottomRightPoint, tangent2End: bottomLeftPoint, radius: radius) path.addArc(tangent1End: bottomLeftPoint, tangent2End: topLeftPoint, radius: radius) path.addArc(tangent1End: topLeftPoint, tangent2End: topRightPoint, radius: radius) // 4 path.closeSubpath() return path } } The code above creates a global extension for everything of type UIView, so you can use it for more than just UIButtons. The code also instructs createRoundedRectPath(for:radius:) to draw the rounded rect in the following order: Here’s the breakdown of what’s going on in the code: - You move to the center of the top line segment. - You declare each corner as a local constant. - You add each arc to the path: - First, you add an arc for the upper right corner. Before drawing an arc, CGPathAddArcToPointwill draw a line from the current position in the middle of the rect to the beginning of the arc for you. - Similarly, you add an arc for the lower right corner and the connecting line. - Then you add an arc for the lower left corner and the connecting line. - Last, you add an arc for the upper left corner and the connecting line. - Finally, you connect the ending point of the arc with the starting point with closeSubpath(). Making Your Button Rounded OK, now it’s time to put this method to work! Open CoolButton.swift and replace draw(_:) with the following: override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } // 1 let outerColor = UIColor( hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0) let shadowColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5) // 2 let outerMargin: CGFloat = 5.0 let outerRect = rect.insetBy(dx: outerMargin, dy: outerMargin) // 3 let outerPath = createRoundedRectPath(for: outerRect, radius: 6.0) // 4 if state != .highlighted { context.saveGState() context.setFillColor(outerColor.cgColor) context.setShadow(offset: CGSize(width: 0, height: 2), blur: 3.0, color: shadowColor.cgColor) context.addPath(outerPath) context.fillPath() context.restoreGState() } } To break this down: - You define your two colors. - Then you use insetBy(dx:dy:)to get a slightly smaller rectangle (5 pixels on each side) where you’ll draw the rounded rect. You’ve made it smaller so that you’ll have space to draw a shadow on the outside. - Next, you call the function you just wrote, createRoundedRectPath(for:radius:), to create a path for your rounded rect. - Finally, you set the fill color and shadow, add the path to your context and call fillPath()to fill it with your current color. Note: You only want to run the code if your button isn’t currently highlighted; for example, it isn’t being tapped. Build and run the app; if all works well, you should see the following: Adding a Gradient All right, the button’s starting to look pretty good, but you can do even better! How about adding a gradient? Add the following function to Drawing.swift, to make it universally available for any UIView: func drawLinearGradient( context: CGContext, rect: CGRect, startColor: CGColor, endColor: CGColor) { // 1 let colorSpace = CGColorSpaceCreateDeviceRGB() // 2 let colorLocations: [CGFloat] = [0.0, 1.0] // 3 let colors: CFArray = [startColor, endColor] as CFArray // 4 let gradient = CGGradient( colorsSpace: colorSpace, colors: colors, locations: colorLocations)! // More to come... } It doesn’t look like much, but there’s a lot going on in this function! - The first thing you need is to get a color space that you’ll use to draw the gradient. - Next, you set up an array that tracks the location of each color within the range of the gradient. A value of 0 means the start of the gradient, 1 means the end of the gradient. You only have two colors, and you want the first to be at the start and the second to be at the end, so you pass in 0 and 1. - After that, you create an array with the colors that you passed into your function. You use a plain old array here for convenience, but you need to cast it as a CFArray, since that’s what the API requires. - Then you create your gradient with CGGradient(colorsSpace:colors:locations:), passing in the color space, color array and locations you previously made. Note: There’s a lot you can do with color spaces, but 99% of the time you just want a standard device-dependent RGB color space. So simply use the function CGColorSpaceCreateDeviceRGB() to get the reference that you need. Note: You can have three or more colors in a gradient if you want, and you can set where each color begins in the gradient. This can be useful for certain effects. You now have a gradient reference, but it hasn’t actually drawn anything yet. It’s just a pointer to the information you will use when actually drawing it later. Complete the function by adding the following at the end of drawLinearGradient(context:rect:startColor:endColor:): // 5 let startPoint = CGPoint(x: rect.midX, y: rect.minY) let endPoint = CGPoint(x: rect.midX, y: rect.maxY) context.saveGState() // 6 context.addRect(rect) // 7 context.clip() // 8 context.drawLinearGradient( gradient, start: startPoint, end: endPoint, options: []) context.restoreGState() - The first thing you do is calculate the start and end point where you want to draw the gradient. You just set this as a line from the “top middle” to the “bottom middle” of the rectangle. The rest of the code helps you draw a gradient into the provided rectangle, the key function being drawLinearGradient(_:start:end:options:). Constraining a Gradient to a Sub-area The weird thing about that function, though, is that it fills up the entire drawing region with the gradient — there’s no way to set it to only fill a sub-area with the gradient! Well, without clipping, that is! Clipping is an awesome feature of Core Graphics that lets you restrict drawing to an arbitrary shape. All you have to do is add the shape to the context, but then instead of filling it like you usually would, you call clip(). Now, you’ve restricted all future drawing to that region! So that’s what you do here: - You add your rectangle to the context. - Clip to that region. - Then call drawLinearGradient(_:start:end:options:), passing in all the variables that you set up before. So what’s this stuff about saveGState()/ restoreGState() all about? Well, Core Graphics is a state machine. You configure a set of states you want, such as colors and line thickness, and then perform actions to actually draw them. That means that once you’ve set something, it stays that way until you change it back. Well, you’ve just clipped to a region, so unless you do something about it, you’ll never be able to draw outside of that region again! That’s where saveGState()/ restoreGState() come to the rescue. With these, you can save the current setup of your context to a stack and then pop it back later when you’re done to get back to where you were. That’s it, now try it out! Open CoolButton.swift and add this to the bottom of draw(_:) : // Outer Path Gradient: // 1 let outerTop = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0) let outerBottom = UIColor(hue: hue, saturation: saturation, brightness: brightness * 0.8, alpha: 1.0) // 2 context.saveGState() context.addPath(outerPath) context.clip() drawLinearGradient(context: context, rect: outerRect, startColor: outerTop.cgColor, endColor: outerBottom.cgColor) context.restoreGState() Build and run; you should see something like this: - First, you define the top and bottom colors. - Then, you draw the gradient by saving the current graphics state on the stack, adding your path, clipping it, drawing the gradient and restoring the state again. Hooray, your button is looking pretty snazzy! How about some extra pizazz?! Adding a Gloss Effect Now it’s time to make this button shiny, because skeuomorphism should never have gone out of style! When that you can apply to UIViews across the board, so add the following function to the UIView extension in Drawing.swift: func drawGlossAndGradient( context: CGContext, rect: CGRect, startColor: CGColor, endColor: CGColor) { // 1 drawLinearGradient( context: context, rect: rect, startColor: startColor, endColor: endColor) let glossColor1 = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.35) let glossColor2 = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.1) let topHalf = CGRect(origin: rect.origin, size: CGSize(width: rect.width, height: rect.height/2)) drawLinearGradient(context: context, rect: topHalf, startColor: glossColor1.cgColor, endColor: glossColor2.cgColor) } This function is basically drawing a gradient over a rectangle from a start to end color, and then adding a gloss to the top half. Here’s a breakdown of what’s happening: - To draw the gradient, you call the function you wrote earlier. - To draw the gloss, you then draw another gradient on top of that, from pretty transparent (white with 0.35 alpha) to very transparent (white with 0.1 alpha). Simple, eh? Plug it in and see how it looks. Go back to CoolButton.swift and make a small change in draw(_:). Replace this line, which is the second to last in draw(_:): drawLinearGradient(context: context, rect: outerRect, startColor: outerTop.cgColor, endColor: outerBottom.cgColor) with: drawGlossAndGradient(context: context, rect: outerRect, startColor: outerTop.cgColor, endColor: outerBottom.cgColor) In case you can’t spot the difference, you just changed drawLinearGradient(context:rect:startColor:endColor:) into drawGlossAndGradient(context:rect:startColor:endColor:), the newly added method in Drawing.swift. Build and run, and your button should now look like this: Oooh, shiny! Styling the Button Now for the super-fine, nit-picky details. If you’re making a 3D button, you might as well go all out. To do that, you need a bevel. To create a bevel-type effect, add an inner path that has a slightly different gradient than the outer path. Add this to the bottom of draw(_:) in CoolButton.swift: // 1: Inner Colors let innerTop = UIColor( hue: hue, saturation: saturation, brightness: brightness * 0.9, alpha: 1.0) let innerBottom = UIColor( hue: hue, saturation: saturation, brightness: brightness * 0.7, alpha: 1.0) // 2: Inner Path let innerMargin: CGFloat = 3.0 let innerRect = outerRect.insetBy(dx: innerMargin, dy: innerMargin) let innerPath = createRoundedRectPath(for: innerRect, radius: 6.0) // 3: Draw Inner Path Gloss and Gradient context.saveGState() context.addPath(innerPath) context.clip() drawGlossAndGradient(context: context, rect: innerRect, startColor: innerTop.cgColor, endColor: innerBottom.cgColor) context.restoreGState() Here, you shrink the rectangle again with insetBy(dx:dy:), then get a rounded rectangle and run a gradient over it. Build and run and you’ll see a subtle improvement: Highlighting the Button Your button looks pretty cool, but it doesn’t act like a button. There’s no indication of whether the user has pressed the button or not. To handle this, you need to override the touch events to tell your button to redisplay itself, since it might need an update after a user selects it. Add the following to CoolButton.swift: @objc func hesitateUpdate() { setNeedsDisplay() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) setNeedsDisplay() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) setNeedsDisplay() } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) setNeedsDisplay() perform(#selector(hesitateUpdate), with: nil, afterDelay: 0.1) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) setNeedsDisplay() perform(#selector(hesitateUpdate), with: nil, afterDelay: 0.1) } Build and run the project, and you’ll see that there’s a difference when you tap the button now — the highlight and bevel disappear. But you can make the effect a bit better with one more change to draw(_:): When a user presses the button, the overall button should become darker. You can achieve this by creating a temporary variable for the brightness called actualBrightness, and then adjusting it appropriately based on the button’s state: var actualBrightness = brightness if state == .highlighted { actualBrightness -= 0.1 } Then, inside draw(_:), replace all the instances of brightness with actualBrightness. Altogether, the draw(_:) function now looks like this. It’s a little long, but the repetition is worth it: override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } var actualBrightness = brightness if state == .highlighted { actualBrightness -= 0.1 } let outerColor = UIColor( hue: hue, saturation: saturation, brightness: actualBrightness, alpha: 1.0) let shadowColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5) let outerMargin: CGFloat = 5.0 let outerRect = rect.insetBy(dx: outerMargin, dy: outerMargin) let outerPath = createRoundedRectPath(for: outerRect, radius: 6.0) if state != .highlighted { context.saveGState() context.setFillColor(outerColor.cgColor) context.setShadow( offset: CGSize(width: 0, height: 2), blur: 3.0, color: shadowColor.cgColor) context.addPath(outerPath) context.fillPath() context.restoreGState() } // Outer Path Gloss & Gradient let outerTop = UIColor(hue: hue, saturation: saturation, brightness: actualBrightness, alpha: 1.0) let outerBottom = UIColor(hue: hue, saturation: saturation, brightness: actualBrightness * 0.8, alpha: 1.0) context.saveGState() context.addPath(outerPath) context.clip() drawGlossAndGradient(context: context, rect: outerRect, startColor: outerTop.cgColor, endColor: outerBottom.cgColor) context.restoreGState() // Inner Path Gloss & Gradient let innerTop = UIColor(hue: hue, saturation: saturation, brightness: actualBrightness * 0.9, alpha: 1.0) let innerBottom = UIColor(hue: hue, saturation: saturation, brightness: actualBrightness * 0.7, alpha: 1.0) let innerMargin: CGFloat = 3.0 let innerRect = outerRect.insetBy(dx: innerMargin, dy: innerMargin) let innerPath = createRoundedRectPath(for: innerRect, radius: 6.0) context.saveGState() context.addPath(innerPath) context.clip() drawGlossAndGradient(context: context, rect: innerRect, startColor: innerTop.cgColor, endColor: innerBottom.cgColor) context.restoreGState() } Build and run; now the button should look pretty good when you tap it! Where to Go From Here? Now that you’ve gone through all of the steps to create custom buttons from scratch, you should be intimately familiar with how to customize every aspect of the button to your liking for your project’s style! Hopefully, this tutorial helped you become more comfortable with Core Graphics and sparked an interest in exploring the API further. :] If this tutorial was a little hard to follow, or you want to make sure to cover your basics, check out our Beginning Core Graphics video series. If you’re looking for something more advanced, take a look at the Intermediate Core Graphics course. And if you don’t feel like you can commit to a full course yet, try the Core Graphics Article Series where you’ll learn how to draw an entire app, including graphs, from scratch with Core Graphics! Plus there are many more Core Graphics tutorials, all recently updated for Xcode 10, on the site. If you have any questions or comments, please join the forum discussion below. Source link
http://smartsoftware247.com/core-graphics-how-to-make-a-glossy-button/
CC-MAIN-2019-22
refinedweb
3,940
58.89
Details - Type: Bug - Status: Resolved - Priority: Major - Resolution: Fixed - Affects Version/s: 2.0.0Release - Fix Version/s: 2.5.2.Release - Component/s: Refactoring - Labels:None - Number of attachments : Description The last remaining problem (that I know of) with moving and copying of groovy compilation units are that import statements are not properly updated. For Java files, an import rewriter is used, but this does not work for groovy files. Perhaps, we can make a change in the import rewriter to delegate to a groovy version when required. We already have a "groovy organize imports" action. This can be refactored a bit and moved from UI to core and then this can be used to rewrite import statements. Activity As I say above, we really should get this working for 2.1.2. Thanks a lot. This really saves time for refactorings. It's shocking that we haven't gotten this to work yet. We really should. I just had a look at what we need to do and it is much simpler than I had originally thought. We do not need to do the import updating ourselves, that can all be delegated to existing JDT code. All we need to do is re-implement the TypeReferenceSearchRequestor so that it can handle wildcard types. I have a prototype implementation working locally, but I uncovered a fairly serious JDT bug. I raised an issue here: Still need to write some tests. Also, this will not be released until after the 2.5.1 release. What's missing in the current implementation? I just tested a Groovy class that holds an instance of a Java and one of a Groovy class. Moving these two classes to another package updates the imports correctly. Interesting...there are a number of cases that do seem to be working without any fix (something I wasn't aware of), but I am focussing on this situation: In src/first/ToMove.groovy: package first; public class ToMove { public Foo x; } In src/first/Foo.groovy: package first; public class Foo { } Now, ToMove.groovy move to a new package and no import statement is added. It looks like if Foo.groovy is moved, then an import statement is correctly added to ToMove.groovy. But, this all needs some tests to make sure that it is not accidentally broken in the future. Fixed. Will go into 2.5.2 release. We should really get this working for 2.1.0.
http://jira.codehaus.org/browse/GRECLIPSE-682?focusedCommentId=271222&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-22
refinedweb
411
67.15
System.Metrics Contents Description A module for defining metrics that can be monitored. Metrics are used to monitor program behavior and performance. All metrics have - a name, and - a way to get the metric's current value. This module provides a way to register metrics in a global "metric store". The store can then be used to get a snapshot of all metrics. The store also serves as a central place to keep track of all the program's metrics, both user and library defined. Here's an example of creating a single counter, used to count the number of request served by a web server: import System.Metrics import qualified System.Metrics.Counter as Counter main = do store <- newStore requests <- createCounter "myapp.request_count" store -- Every time we receive a request: Counter.inc requests This module also provides a way to register a number of predefined metrics that are useful in most applications. See e.g. registerGcMetrics. Synopsis - data Store - newStore :: IO Store - registerCounter :: Text -> IO Int64 -> Store -> IO () - registerGauge :: Text -> IO Int64 -> Store -> IO () - registerLabel :: Text -> IO Text -> Store -> IO () - registerDistribution :: Text -> IO Stats -> Store -> IO () - registerGroup :: HashMap Text (a -> Value) -> IO a -> Store -> IO () - createCounter :: Text -> Store -> IO Counter - createGauge :: Text -> Store -> IO Gauge - createLabel :: Text -> Store -> IO Label - createDistribution :: Text -> Store -> IO Distribution - registerGcMetrics :: Store -> IO () - type Sample = HashMap Text Value - sampleAll :: Store -> IO Sample - data Value Naming metrics Compound metric names should be separated using underscores. Example: request_count. Periods in the name imply namespacing. Example: "myapp.users". Some consumers of metrics will use these namespaces to group metrics in e.g. UIs. Libraries and frameworks that want to register their own metrics should prefix them with a namespace, to avoid collision with user-defined metrics and metrics defined by other libraries. For example, the Snap web framework could prefix all its metrics with "snap.". It's customary to suffix the metric name with a short string explaining the metric's type e.g. using "_ms" to denote milliseconds. The metric store The metric store is a shared store of metrics. It allows several disjoint components (e.g. libraries) to contribute to the set of metrics exposed by an application. Libraries that want to provide a set of metrics should defined a register method, in the style of registerGcMetrics, that registers the metrics in the Store. The register function should document which metrics are registered and their types (i.e. counter, gauge, label, or distribution). Registering metrics Before metrics can be sampled they need to be registered with the metric store. The same metric name can only be used once. Passing a metric name that has already been used to one of the register function is an error. Arguments Register a non-negative, monotonically increasing, integer-valued metric. The provided action to read the value must be thread-safe. Also see createCounter. Arguments Register an integer-valued metric. The provided action to read the value must be thread-safe. Also see createGauge. Arguments Register a text metric. The provided action to read the value must be thread-safe. Also see createLabel. registerDistribution Source # Arguments Register a distribution metric. The provided action to read the value must be thread-safe. Also see createDistribution. Arguments Register an action that will be executed any time one of the metrics computed from the value it returns needs to be sampled. When one or more of the metrics listed in the first argument needs to be sampled, the action is executed and the provided getter functions will be used to extract the metric(s) from the action's return value. The registered action might be called from a different thread and therefore needs to be thread-safe. This function allows you to sample groups of metrics together. This is useful if - you need a consistent view of several metric or - sampling the metrics together is more efficient. For example, sampling GC statistics needs to be done atomically or a GC might strike in the middle of sampling, rendering the values incoherent. Sampling GC statistics is also more efficient if done in "bulk", as the run-time system provides a function to sample all GC statistics at once. Note that sampling of the metrics is only atomic if the provided action computes a atomically (e.g. if a is a record, the action needs to compute its fields atomically if the sampling is to be atomic.) Example usage: {-# LANGUAGE OverloadedStrings #-} import qualified Data.HashMap.Strict as M import GHC.Stats import System.Metrics main = do store <- newStore let metrics = [ ("num_gcs", Counter . numGcs) , ("max_bytes_used", Gauge . maxBytesUsed) ] registerGroup (M.fromList metrics) getGCStats store Convenience functions These functions combined the creation of a mutable reference (e.g. a Counter) with registering that reference in the store in one convenient function. Arguments Create and register a zero-initialized counter. Arguments Create and register a zero-initialized gauge. Arguments Create and register an empty label. createDistribution Source # Arguments Create and register an event tracker. Predefined metrics This library provides a number of pre-defined metrics that can easily be added to a metrics store by calling their register function. registerGcMetrics :: Store -> IO () Source # Register a number of metrics related to garbage collector behavior. To enable GC statistics collection, either run your program with +RTS -T or compile it with -with-rtsopts=-T The runtime overhead of -T is very small so it's safe to always leave it enabled. Registered counters: rts.gc.bytes_allocated - Total number of bytes allocated rts.gc.num_gcs - Number of garbage collections performed rts.gc.num_bytes_usage_samples - Number of byte usage samples taken rts.gc.cumulative_bytes_used - Sum of all byte usage samples, can be used with numByteUsageSamplesto calculate averages with arbitrary weighting (if you are sampling this record multiple times). rts.gc.bytes_copied - Number of bytes copied during GC rts.gc.mutator_cpu_ms - CPU time spent running mutator threads, in milliseconds. This does not include any profiling overhead or initialization. rts.gc.mutator_wall_ms - Wall clock time spent running mutator threads, in milliseconds. This does not include initialization. rts.gc.gc_cpu_ms - CPU time spent running GC, in milliseconds. rts.gc.gc_wall_ms - Wall clock time spent running GC, in milliseconds. rts.gc.cpu_ms - Total CPU time elapsed since program start, in milliseconds. rts.gc.wall_ms - Total wall clock time elapsed since start, in milliseconds. Registered gauges: rts.gc.max_bytes_used - Maximum number of live bytes seen so far rts.gc.current_bytes_used - Current number of live bytes rts.gc.current_bytes_slop - Current number of bytes lost to slop rts.gc.max_bytes_slop - Maximum number of bytes lost to slop at any one time so far rts.gc.peak_megabytes_allocated - Maximum number of megabytes allocated rts.gc.par_tot_bytes_copied - Number of bytes copied during GC, minus space held by mutable lists held by the capabilities. Can be used with parMaxBytesCopiedto determine how well parallel GC utilized all cores. rts.gc.par_avg_bytes_copied - Deprecated alias for par_tot_bytes_copied. rts.gc.par_max_bytes_copied - Sum of number of bytes copied each GC by the most active GC thread each GC. The ratio of par_tot_bytes_copieddivided by par_max_bytes_copiedapproaches 1 for a maximally sequential run and approaches the number of threads (set by the RTS flag -N) for a maximally parallel run. Sampling metrics The metrics register in the store can be sampled together. Sampling is not atomic. While each metric will be retrieved atomically, the sample is not an atomic snapshot of the system as a whole. See registerGroup for an explanation of how to sample a subset of all metrics atomically. sampleAll :: Store -> IO Sample Source # Sample all metrics. Sampling is not atomic in the sense that some metrics might have been mutated before they're sampled but after some other metrics have already been sampled.
https://hackage.haskell.org/package/ekg-core-0.1.1.1/docs/System-Metrics.html
CC-MAIN-2021-43
refinedweb
1,274
50.12
Opened 6 years ago Last modified 4 months ago #20147 assigned New feature Provide an alternative to request.META for accessing HTTP headers Description From the docs: HttpRequest.META A standard Python dictionary containing all available HTTP headers.... The question is, why? Why do we have this ridiculous transform? It is pure silliness, whose only explanation is a quirk of CGI, which is now totally irrelevant. You should be able to look up a header in the HTTP spec and do something very simple to get it from the HTTP request. How about this API: request.HEADERS['Host'] (for consistency with GET/POST/FILES etc.), or even request['Host'] Dictionary access should obey HTTP rules about case-sensitivity of the header names. This also would has the advantage that repr(request) wouldn't have lots of junk you don't need i.e. the entire content of os.environ, which, on a developer machine especially, can have a lot of noise (mine does). It also future-proofs us for when WSGI is replaced with something more sensible, and the whole silly round trip to os.environ can be removed completely, or if we want to support something else parallel to WSGI and client code wants to access HTTP headers in the same way for both. This leaves a few things in META that are not derived from an HTTP header, and do not have a way of accessing them from the request object. I think these are just: - SCRIPT_NAME - this is a CGI leftover, that is only useful in constructing other things, AFAICS - QUERY_STRING - this can be easily constructed from request.get_full_path()for the rare times that you need the raw query string rather than request.GET - SERVER_NAME - should use get_host() instead - SERVER_PORT - use get_host() - SERVER_PROTOCOL - could use is_secure(), but perhaps it would be nice to have a convenience get_protocol()method. (see) Change History (21) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by HTTP headers are case insensitive. You want to get rid of the transform, but what happens when someone sends "accept: " and you check for HEADERS["Accept"]? comment:3 Changed 6 years ago by As stated above, "Dictionary access should obey HTTP rules about case-sensitivity of the header names." I didn't say get rid of the transform - it should be done within the API, not by the user of the API. In terms of implementation, request.HEADERS['Accept'] will map straight to request._META['HTTP_ACCEPT'], at least for wsgi, or do something equivalent that will ensure case-insensitivity. comment:4 Changed 6 years ago by There are a few more things that need considering if this is to be done: RequestFactoryand the test Client, and their APIs which pass directly to request.META. REMOTE_ADDRESS, REMOTE_USER SECURE_PROXY_SSL_HEADER comment:5 Changed 6 years ago by Minor bikeshed-type question: is there really value in making request.HEADERS all-caps? I realize the parallel to request.POST, request.GET, and request.META, but the former two are all-caps simply because HTTP methods are usually written that way. I guess I'd just like to see a bit of rationale spelled out for how we decide whether a given request attribute ought to be all-caps; I'd probably lean towards just request.headers for the new API. More discussion of this proposal (in particular, whether to deprecate/change request.META) is here: comment:6 Changed 6 years ago by It would be consistent for request.headers to be lowercase to match up with request.body for example. comment:7 Changed 6 years ago by Should we consider having request.headers return unicode values rather than byte values? Correctly decoding HTTP headers is slightly fiddly - the default supported encoding is iso-8859-1, but utf-8 can also be supported as per RFC 2231, RFC 5987. Getting the decoding right probably isn't something we want developers to have to think about. Note: For real-world usage see this example of browser support for utf-8 in uploaded filenames: comment:8 Changed 6 years ago by (Ooops, that anonymous comment is mine.) comment:9 Changed 6 years ago by Okay, noticed that the link to chrome's use of iso-8859-1 is actually for response headers, so disregard that. The question regarding unicode vs byte values still stands, though. comment:10 Changed 6 years ago by I'm happy with request.headers instead of request.HEADERS - the parallel to request.body does make more sense that request.GET. Regarding unicode/bytes, it's a very thorny issue, and the more I look into it the worse it gets. PEP 3333 might apply, if we are assuming a simple mapping to request.META, but that essentially leaves decoding issues to the user if I'm reading it correctly. comment:11 Changed 6 years ago by Okay, maybe it's not obvious if unicode values would be preferable or not. I thought I'd take a look at what the requests library does, and found this similar ticket: If it is something that we decide to do, then the following looks like it ought to do the trick: from email.header import decode_header u''.join(header_bytes.decode(enc or 'iso-8859-1') for header_bytes, enc in decode_header(h)) For further reference note that the httpbis spec is proposed to obsolete RFC2616, cleaning up & clarifying underspecified bits of the spec. The relevant section on header value encoding is here: comment:12 Changed 6 years ago by The mailing list discussion converged towards keeping META, but recommending a dict-like request.headers. I'm updating the summary to reflect this. comment:13 Changed 5 years ago by Regarding the transformation of request headers, for example from X-Bender to the META key HTTP_X_BENDER - From what I see this transformation is not done in django but in the wsgi implementation. I tested with apache mod_wsgi and with python's wsgiref and seems that they are doing this transformation not django. I couldn't find it documented anywhere but see this from python's Lib/wsgiref/simple_server.py 99 for h in self.headers.headers: 100 k,v = h.split(':',1) 101 k=k.replace('-','_').upper(); v=v.strip() 102 if k in env: 103 continue # skip content length, type,etc. 104 if 'HTTP_'+k in env: 105 env['HTTP_'+k] += ','+v # comma-separate multiple headers 106 else: 107 env['HTTP_'+k] = v comment:14 Changed 3 years ago by comment:15 Changed 3 years ago by comment:16 Changed 2 years ago by Proof of concept: This makes request.headers have lowercase header names, and replaces underscores with hyphens. (header names are lowercase in http2) Also, on python3 we already get unicode headers from WSGI, and we're dropping py2 in January, so I don't think it's worth making the values unicode on python2. The header names are already unicode on python2. { 'accept-language': 'en-US,en;q=0.8', 'accept-encoding': 'gzip, deflate, sdch', 'host': 'localhost:8000', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'upgrade-insecure-requests': '1', 'connection': 'keep-alive', 'cache-control': 'max-age=0', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36', } comment:17 Changed 23 months ago by comment:18 Changed 6 months ago by I will give it a try and submit a PR. A strong argument against the request['Referer']API is the use of request in templates (e.g. if request.GET.some_flag), which conflates dictionary access and attribute access, probably making request.HEADERS['Referer']a much safer API.
https://code.djangoproject.com/ticket/20147
CC-MAIN-2018-47
refinedweb
1,288
56.55
On Wed, 2008-06-11 at 14:42 +0000, Kevin Kofler wrote: > Nic. They also do not appear in the default search index. That is a main reason to be careful what we put there. I doubt we want to hide any of the content you are talking about. I'm not personally against the nested directory-like structure; it is similar to how my brain stores information, so I can recall wiki URLs and such fairly well. However, we used that structure in Moin for pragmatic reasons that should be reviewed in light of how MediaWiki works. We should review if that scheme is still as useful as before, and if it can be replaced with a better scheme. For example, if you put every KDE SIG page in the [[Category:KDE SIG]], you may have gained the exact same value as nesting page names (making it easy to find and maintain an area of the wiki). Plus you may have a new set of cool things you can do because of the categorization. There are other ways to designate that a group is sponsoring a certain page. One we discussed is a "badge" that says, "You are encouraged to edit this page to make it better; if you have any questions, please contact the page sponsors, the Fonts SIG." We want to encourage people to edit pages. Does having pages in nested namespace make people feel as if, "Packaging/Foo must be owned by Packaging, I better not touch this page"? Finally, there is the situation with the search index. One of the PITAs of Moin Moin search is that a keyword for the title is always expanded as if from a wildcard search. You get back a ton of pages, with the relevant one buried in the middle. If you guessed the wrong word, good luck in the page turning up. By having spaces in names, MediaWiki allows *us*, the thinking humans, the chunk the longstringofwords into something sensible. Maybe we're lucky and MediaWiki considers a '/' to be a chunk separator. But in my usage, I've found the MediaWiki search to be better, especially where it can find the actual word amongst the 13,000+ titles in the index. - Karsten -- Karsten Wade, Sr. Developer Community Mgr. Dev Fu : Fedora : gpg key : AD0E0C41 Attachment: signature.asc Description: This is a digitally signed message part
https://www.redhat.com/archives/fedora-devel-list/2008-June/msg00680.html
CC-MAIN-2015-11
refinedweb
398
72.05
The QStyleSheet class is a collection of styles for rich text rendering and a generator of tags. More... #include <qstylesheet.h> Inherits QObject. List of all member functions. By creating QStyleSheetItem objects for a style sheet you build a definition of a set of tags. This definition will be used by the internal rich text rendering system to parse and display text documents to which the style sheet applies. Rich text is normally visualized in a QTextEdit or a QTextBrowser. However, QLabel, QWhatsThis and QMessageBox also support it, and other classes are likely to follow. With QSimpleRichText it is possible to use the rich text renderer for custom widgets as well. The default QStyleSheet object has the following style bindings, sorted by structuring bindings, anchors, character style bindings (i.e. inline styles), special elements.
http://vision.lbl.gov/People/qyang/qt_doc/qstylesheet.html
CC-MAIN-2015-35
refinedweb
134
58.08
On 12/19/00 5:39 A > I am not sure I lik M, "Peter Donald" <donaldp@apache.org> wrote: e the handling of differences between workspace/module. > In many ways I think the difference is rather .. nebulous so not sure what > to make of it. I am also strongly in favour of no intrinsic behaviour > (including searching for workspace from module file). As currently set the primary difference between workspace & module is a matter of degree... And an explicitness of which is the root. I think that things like listeners and such could also happen at the workspace level and not be a module level item. But it's just the start of a thought. Also, another difference between workspace and module is that modules don't really need names -- they are part of the name of the workspace. This is targeted at Diane's 64 subproject files. More places for differentiating themselves may present themselves. > We had a few complaints when we implemented this for ant build files. The > two prominent ones were security - mistyping ant in wrong directory could > send you into a long search that could find something in a very far away > place (way up directory tree) and some installations would not instal ant > with this feature enabled. Fair enough. I can see that... The linkage between workspace and module is explicit, but yes, the linkage between module and workspace is implicit. I don't have a problem going explicit with this link either... <module workspace="../../Workspace"> ... </module> Or some such. And, if the distinction between Workspace/Module is too overdone, then obviously this is simple to express in Project terms... [$DIR/project] <project name="Whatever"> <target name="foo"> <exec-child </target> </project> [$DIR/childdir/subproject] <project name="WhateverChild" parent="../project"> ... </project> > I much prefer explictness if at all possible. If you have a look at the > So I am not sure if seperating module/workspace out is ideal solution. I > was of the understanding that workspace was more a conceptual idea. A > "workspace" of foo was essentially the DAG of project files imported > directly or indirectly from foo. Not sure I guess it needs to be looked at > a bit more. Right. The aim of Workspace/Module explicitness is to clarify that there is a root to the system -- the root of course being special because it doesn't have a parent. > I think this may be too complex for users - not sure. While it would be > ideal if we just wanted simple data types and sets of simple data types I > think this approach would fall down in complex case. For example how would > you represent > > <property name="foo"> > <fileset dir="bob"> > <fileset ref="bar" /> > <patternset ref="blee" /> > <patternset> > <include name="grrr.java" /> > </patternset> > </fileset> > </property> Depends on what is in the ref of "blee" since the proposal to abstract this doesn't take into account definable patterns.. But besides that it's <set name="fileset1" type="java.io.File"> <builder type="filebuilder" recurse="yes"> <item>grrr.java</item> </set> Or, if particular builders were registered internally (or by explicity external builders specified in the Workspace) (and it seems that "file" would be a natural default): <set name="fileset1" type="file"> <item>grr.java</item> </set> So, if there were seperable patterns, which there very well might need to be for reuse: <pattern name="javafiles"> <item>*.java</item> </pattern> <set name="fileset1" type="file"> <usepattern name="javafiles"/> </set> Not top complex -- seems pretty straightforward to me for a worst case scenario -- and now any type of object could be put into a set. The only caveat is a task that grabed onto a property or a property set would have to know of course what types of objects went in. > However the worst thing about it is that it uses java types - yuck !!! > Remember that many of the target audience doesn't know what java is > (besides being that ugly thing thats is sometimes placed on web-pages). It > seems unreasonable to expect any knowledge of java - especially if ant was > to move towards a c/c++ build system. Java types were used as a definitive fallback to allow any kind of types in properties or property sets to be used. And ant was designed for primary use on Java projects. If it's useful in C++, fine -- of course the C++ answer (or at least MSFT answer) to simple type names of java.io.File are class ids with big long strings. If people can grok that, they can grok java.io.File. :) It is obvious that some types will want to be promoted into a simplier namespace, such as file=java.io.File in a type case and file=org.apache.ant.FileBuilder in a set builder case. > Also I don't think I like the restriction that properties could not be > defined in targets. Currently a lot of my build files use something like > > <target name="debug-mode" if="debug-mode"> > <property name="output.dir" value="../build/debug"/> > </target> > > <target name="release-mode" depends="debug-mode" unless="debug-mode" > > <property name="output.dir" value="../build/release"/> > </target> > > and I have recomended a lot of other people use that pattern. (Either that > or the mutual-exclusion of multiple targets version of above) . Like I've said from the beginning and every time I've popped up -- properties follow the same sort of model as System properties -- they are a global namespace to store things. What you are using them as there is as local variables with scoping. And I don't understand unless="targetname" like you've got -- how can a target resolve to true or false? Either you execute the target and it succeeds or fails, or don¹t. > Right - a while ago I was advocating attributes such as > > ant: ant: ant: ant:.... > > All these things are independent of the actual task and could be > implemented as part of any task. This would stop a lot of special case code > - for example a lot of my tasks used to run in default classpath but I > later needed to specify the classpath. This of course meant a complete and > utter rewrite of everything which I don't think was desirable - and I think > it must be common situation. Using namespacing for this sort of thing is interesting to consider. One thing that I don't like about it is that it would force people to declare the ant: namespace in their XML files. Being able to set the classpath for tasks is an interesting idea however it means 1) each task execution gets its own classloader that has to divorce itself from the system class loader, and yet manage to pick up system classes (ie, everything that's not on a defined classpath) and 2) it makes people have to deal with the fact that it's Java. Since you state that "java.io.File" is icky for that reason, then I have to point this out. New VM -- I'd really like to defer out of that to explicit task executions for launching new processes. One thing that wasn't in the proposal, but which I've been tinkering with in code is the concept of default threading.. IE, a attribute which is valid for all tasks is "fork|spawn|thread="yes"" (name tbd!). This would automatically in the Task execution logic spawn a thread that would execute the task and control would return to the main thread and next task. Then a <join|sync> task could wait until everything caught up. This is a little different than earlier proposals to this effect because it drive MT down into the core execution of Ant. I think this is necessary to take advantage of 4x, 8x, and *x machines to parallelize builds. > ant-call was also used for templating. So instead of writing 10 targets > that do a javac, jar, sign, you can write one target that gets properties > past in via ant-call. It was primitive but a lot of people use it this way > (which is surprising because it is slooooooow in current ant. Which is a hack in essence. Targets are supposed to be descriptors of tasks to be executed, not method definitions. This is one of the cases where people using this way doesn't make it right. >> Installer. I'd like to see more along these lines. In fact, given that >> Ant is pretty small (the biggest chunk is the durn XML parser), there's >> no real reason it can't be used as a task engine to be used by an >> installer. Probably something where a Module tree would be built >> at runtime so that things like install dir can be queried instead of >> being something that is driving off an XML file. I'm not sure that I'd >> write an installer that drove a project/workspace directly. Maybe I'd >> write it with Installets or something, but that's a whole different >> ball of wax. If this works for that purpose, more power. :) > > Right - I think it would be better to be at a lower level for installer. > Instead of reusing whole of ant it would just reuse the task execution > engine and ignore the project/module/workspace classes. Hopefully each > different concern would be localised to a different directory and such > reuse would be possible. Ok.. I do want to make it clear that if such reuse is possible, great -- but it shouldn't drive any part of the design of building stuff. >> Observations (and Questions) for Diane: >> I'd like to know more about your build-order issues. Typically divisions >> between sourcepaths and destpaths seem like they could keep things >> segregated until you copy the results together into one happy tree. >> However, the side-compile issue is the biter. I guess I'd like a bit >> more info there. > > Thats what I thought - I think her build situations is really painful. Have > to compile class 1, 2 and 3 with 1.3 JDK, then classes 4,5 6 with 1.2 JDK > and then ... ouchies ;) Yeah... Ouch. >> I agree that if/unless checks need to be for true/false/1/0 type of >> matches and not existence of property. I would like to know your >> feeling about execution order. IOW, in AntEater I checked in a >> buildtarget task that did the if/unless checking.. This is a bit >> different than doing the if checking in the target def in the fact >> that all of those items could be centralized in one target instead >> of spread out through the build files. Would this be helpful? > > I am not sure it would be useful. It is similar to the issue of CSS styling > of ant buildfiles but on a more fixed level which sounds painful ;) Huh? CSS styling? >> Logging -- it would be nice to provide a listener to simply write all >> events out to a file -- or mail the events output to somewhere at >> a particular email address... Any further comments on this? > > Theres a few issues. Sometimes you need to log to different things > depending on how build finished and how long it took and what options were > used to build etc. Similar to what you have ages ago I implemented > something like > > <project ...> > > <listener type="org.apache.ant.MailNotification"> > <param name="blah" value="blee"/> > </listener> > > </project> > > However I found it too constraining as it missed to much being instantiated > after the project was already in motion - I am not sure of a more viable > solution thou ;( I think that the definition of listeners should be that they are hooked into place *before* execution moves on. This is one of the reasons that I see properties/listeners/whatever else that isn't a target as separate from targets and something that should be in targets.. All of these things need to be made alive before execution gets started. .duncan -- James Duncan Davidson duncan@x180.net !try; do()
http://mail-archives.apache.org/mod_mbox/ant-dev/200012.mbox/%3CB664F92B.D2A1%25duncan@x180.net%3E
CC-MAIN-2017-17
refinedweb
1,994
71.65
ng_ip_input -- netgraph IP input node type #include <netgraph/ng_ip_input.h> The ip_input node type takes all received packets and queues them into the IP in input processing subsystem. An ng_ip_input node accepts any request to connect, regardless of the hook name, as long as the name is unique. This node type supports only the generic control messages. Other control messages are silently discarded. This node shuts down upon receipt of a NGM_SHUTDOWN control message, or when all hooks have been disconnected. netgraph(4), ngctl(8) The ng_ip_input node type was implemented in FreeBSD 5.0. Brooks Davis <brooks@FreeBSD.org> The ng_ip_input node type should probably keep some sort of statistics. FreeBSD 5.2.1 September 27, 2001 FreeBSD 5.2.1
http://nixdoc.net/man-pages/FreeBSD/man4/ng_ip_input.4.html
CC-MAIN-2019-43
refinedweb
122
68.67
Help with TexImage2DPosted Wednesday, 24 October, 2007 - 16:44 by nythrix in Hi, does anyone know how to actually create textures? what do i pass to GL.TexImage2D as the last parameter? i used to pass BitmapData.Scan0 like so: using System; using System.Drawing; using System.Drawing.Imaging; ... // bmp contains a valid bitmap with correct size (power of 2) glGenTextures( 1, out id ); glBindTexture( GL_TEXTURE_2D, id ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); Rectangle rect = new Rectangle( 0, 0, bmp.Width, bmp.Height ); BitmapData bmpData = bmp.LockBits( rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb ); glTexImage2D( GL_TEXTURE_2D, 0, 3, bmp.Width, bmp.Height, 0, GL_RGB, GL_UNSIGNED_BYTE, bmpData.Scan0 ); bmp.UnlockBits( bmpData ); bmp.Dispose(); ... This works on Tao. Any hints regarding OpenTK? The following code The following code works: Unsafe code is due to a bug in 0.3.12 that has been fixed in SVN. I'll add the missing formats to GL.Enums.PixelFormat to avoid the cast from GL.Enums.All, but otherwise, you can use the same code as in Tao (swapping in the correct enums of course). oh yes, i forgot to mention oh yes, i forgot to mention i'd like to avoid unsafe code :) does the bugfix mean i won't have to switch to unsafe? GL.Enums.PixelFormat.RGB is already present in 0.3.12. i couldn't find GL.Enums.TextureWrapMode.CLAMP_TO_EDGE though. thank you. edit: i see CLAMP_TO_EDGE is already reported. never mind then. edit2: you're right, BGR isn't present indeed. oh yes, i forgot to mention oh yes, i forgot to mention i'd like to avoid unsafe code :) does the bugfix mean i won't have to switch to unsafe? Yes, OpenTK tries to provide safe alternatives to all unsafe functions - the fix allows you to pass the BitmapData.Scan0 return value directly, just like in Tao.
http://www.opentk.com/node/74
CC-MAIN-2015-11
refinedweb
306
61.83
Xtreme Visual Basic Talk > Legacy Visual Basic (VB 4/5/6) > General > cant figure out Collection PDA cant figure out Collection under_seeg 07-04-2004, 08:20 AM i've been looking for a way to do this for days now, i'm not very talented myself im quite new to VB but heres my prob. i want to create a collection i think, or instances of a class or something like that, right now i have a class called 'Entity' with property 'keycomments' this is just one of the properties i have a few irrelevant ones. when i click my button i want the text entered in KeyvalID to use as the name of my new instance of Entity, shown as follows: If KeyvalID.Text = "" Then MsgBox ("You must enter an ID.") End If Dim temp temp = KeyvalID.Text Dim bla(temp) As New Entity 'in a function later on this lower section will happen 'and for now it assumes the KeyvalID.Text earlier was "npc_roll" bla(npc_roll).keycomments = "It Works!" KeyvalComments.Text = bla(npc_roll).keycomments 'this is on screen for the user to see. i know this doesnt work because i have to have a constant expression when making the bla(temp), and 'temp' is not constant, but how can i go about achieving this, all i want is the ability to type bla(npc_roll).keycomments = "It Works!" i have to be able to create an instance of the class Entity with the name of the users choice. also if i'm going to have to use a collection, can you explain very carefully because no matter how much i look at tutorials and examples on MSDN or other sites, i just cant figure them out! for a start i cant type public class bla ... end class it doesnt allow any of it. i'm just totally stumped on making collections. Read on if your willing to help find an alternative :): if theres an alternative you can think of then i'll be just as happy, i'm taking a few values that have been entered and trying to store them for saving later on. there can be any number of them and each will have a few values inside, some wont include some of the values, and in a special case, some will need to create extras (called Choice1, Choice2, Choice3... etc.) if possible i'd also like to create all these inside other classes, for example: No1.ID No1.Name No1.Keyvals.1.ID No1.Keyvals.1.Name No1.Keyvals.1.Comments No1.Keyvals.2.ID No2.ID ... this is basically the exact system i want. i just dont have the skill to do it, and i cant find out how to create something like keyvals, where it has a second or third list of properties inside it. sorry for the long post. stevo 07-04-2004, 08:42 AM how about using a Private Type. Option Explicit Private Type StringKeys Keycomments As String Irrelivantstuff As String End Type 'then you can Dim bla(5) As StringKeys 'just threw 5 in, dont know what you want here bla(0).Keycomments = "some stuff" bla(0).Irrelivantstuff = "some other stuff" Debug.Print bla(0).Keycomments & " " & bla(0).Irrelivantstuff is this what you are looking for ? under_seeg 07-04-2004, 08:47 AM almost, is there a way to make a type with more than just bla(0).comment so i could have bla(0).key1.comment? EDIT: oh yea and is it possible to just add 1 on the end of that, say it starts with 8 in and i add 1 so it becomes bla(9) or do i need to have bla(1000) at the beginning as a set limit. also using this method is it possible to start off with bla(0).ID bla(0).Keycomment and later on add bla(0).Choice1 stevo 07-04-2004, 09:00 AM try this then Option Explicit Private Type StringKeys Keycomments As String Irrelivantstuff As String End Type Private Type skeys key1 As StringKeys End Type 'then Dim bla(5) As skeys bla(0).key1.Keycomments = "blahblah" bla(0).key1.Irrelivantstuff = "blahblahblah" Debug.Print bla(0).key1.Keycomments & " " & bla(0).key1.Irrelivantstuff under_seeg 07-04-2004, 09:04 AM excellent, now all i need is a way to create key2, key3... and so on while its running, since both key's and bla's can be added and deleted, have u got any ideas on this? EDIT: wait this isnt all i need, i need a way to create these keys and bla's using 'I' in a For loop, because i'll need to see how many have already been created, if theres really no way to do this i think it'll be ok just setting limits to how many you can make, but i'd prefer a more efficient way. EZ Archive Ads Plugin for vBulletin Computer Help Forum
http://www.xtremevbtalk.com/archive/index.php/t-176260.html
CC-MAIN-2014-10
refinedweb
825
69.41
In my – admittedly limited – perception unit testing in C++ projects does not seem as widespread as in Java or the dynamic languages like Ruby or Python. Therefore I would like to show how easy it can be to integrate unit testing in a CMake-based project and a continuous integration (CI) server. I will briefly cover why we picked googletest, adding unit testing to the build process and publishing the results. Why we chose googletest There are a plethora of unit testing frameworks for C++ making it difficult to choose the right one for your needs. Here are our reasons for googletest: - Easy publishing of result because of JUnit-compatible XML output. Many other frameworks need either a Jenkins-plugin or a XSLT-script to make that work. - Moderate compiler requirements and cross-platform support. This rules out xUnit++ and to a certain degree boost.test because they need quite modern compilers. - Easy to use and integrate. Since our projects use CMake as a build system googletest really shines here. CppUnit fails because of its verbose syntax and manual test registration. - No external dependencies. It is recommended to put googletest into your source tree and build it together with your project. This kind of self-containment is really what we love. With many of the other frameworks it is not as easy, CxxTest even requiring a Perl interpreter. Integrating googletest into CMake project - Putting googletest into your source tree - Adding googletest to your toplevel CMakeLists.txtto build it as part of your project: add_subdirectory(gtest-1.7.0) - Adding the directory with your (future) tests to your toplevel CMakeLists.txt: add_subdirectory(test) - Creating a CMakeLists.txt for the test executables: include_directories(${gtest_SOURCE_DIR}/include) set(test_sources # files containing the actual tests ) add_executable(sample_tests ${test_sources}) target_link_libraries(sample_tests gtest_main) - Implementing the actual tests like so (@see examples): #include "gtest/gtest.h" TEST(SampleTest, AssertionTrue) { ASSERT_EQ(1, 1); } Integrating test execution and result publishing in Jenkins - Additional build step with shell execution containing something like: cd build_dir && test/sample_tests --gtest_output="xml:testresults.xml" - Activate “Publish JUnit test results” post-build action. Conclusion The setup of a unit testing environment for a C++ project is easier than many developers think. Using CMake, googletest and Jenkins makes it very similar to unit testing in Java projects. I have to say, thank you for this. I’ve been trying to find a way to integrate google test into our source repository, as well as been thinking about creating a build server, and you’ve answered in this one post everything I need to know! Thanks! If you prefer not to add gtest’s source code to your own project, you can get CMake to download it at configure time and still build gtest as part of your own build using add_subdirectory(). I recently write an article covering this approach here: Hope you find this useful. Thanks for providing another option! I really like this tutorial. Short to the point, with usable code and options. Great write up! Thank you so much!! Best way to implement google test. Pingback: 4 Tips for better CMake | Schneide Blog Pingback: Integrating conan, CMake and Jenkins | Schneide Blog
https://schneide.blog/2014/01/27/integrating-googletest-in-cmake-projects-and-jenkins/
CC-MAIN-2021-04
refinedweb
526
57.57
On Tue, 22 Jun 1999, Bill Huey wrote:> Are you telling me that you, being a Unix/Linux, person can't handle> FTPing a multistream file with all those user-unfriendly tar options ?yes. Linux doesnt _want_ to deal with restrictive, application-specificcomplexity like 'resource forks'.> Watch how "find" chokes on Linux/Unix/Win32 systems and then do the> same search on crappy MacOS machine that's got a 32 bit DOS extender for> a VM subsystem and blow the all the Linux/Unix/Win32 away from having all> those dorky "dot" ("." <---) pathetically slow down the search.you havent tried this, have you? The new 2.2 kernel includes a rather fastfile namespace cache implementation, it takes ~5 microseconds to look up afile. Too slow?> You can just search the data fork for content.why should we add such a restrictive construct to the kerenel, if wealready have a mechanism that does this and more. > File suffix MIME determination is just about the most brain-dead/annoying> thing. Replace them with per file attributes for MIME determination, etc...no. resource forks are only useful in a very limited sense. We dont wantresource forks for the same reason we do not want to put SQL parsers andCobol compilers into the kernel. It's up to the application how it usesthe file namespace - directories are a perfect (and more generic becauserecursive) construct to store multiple attributes.Are MacOS resource forks recursive? No. Can MacOS resource forks be files? No. Can MacOS resource fork attributes have different permissions as thebase file? No. Can MacOS attributes be symbolic linked across files tosave space and be more generic? No. Can MacOS resource fork attributes bedifferent things to different users in a multiuser environment? No.Directories are all 'Yes' to those questions, and they are extremely fastwith 2.2. Whats your problem with directories?-- mingo-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.rutgers.eduPlease read the FAQ at
http://lkml.org/lkml/1999/6/23/15
CC-MAIN-2015-11
refinedweb
334
66.23
lp:~mturquette/duplicity/duplicity - Get this branch: - bzr branch lp:~mturquette/duplicity/duplicity Branch merges - Kenneth Loafman: Disapprove on 2016-09-06 - edso: Needs Fixing on 2014-08-26 - Diff: 38 lines (+14/-12)1 file modifiedbin/duplicity (+14/-12) Related bugs Related blueprints Branch information - Owner: - Michael Turquette - Status: - Development Recent revisions - 990. By Michael Turquette on 2014-05-21: http:// article. gmane.org/ gmane.comp. sysutils. backup. duplicity. general/ 4299 Signed-off-by: Mike Turquette <email address hidden> - - 981. By Kenneth Loafman on 2014-04-29 * Merged in lp:~mterry/duplicity/backend-unification - Reorganize and simplify backend code. Specifically: - Formalize the expected API between backends and duplicity. See the new file duplicity/ backends/ README for the instructions I've given authors. - Add some tests for our backend wrapper class as well as some tests for individual backends. For several backends that have some commands do all the heavy lifting (hsi, tahoe, ftp), I've added fake little mock commands so that we can test them locally. This doesn't truly test our integration with those commands, but at least lets us test the backend glue code. - Removed a lot of duplicate and unused code which backends were using (or not using). This branch drops 700 lines of code (~20%) in duplicity/backends! - Simplified expectations of backends. Our wrapper code now does all the retrying, and all the exception handling. Backends can 'fire and forget' trusting our wrappers to give the user a reasonable error message. Obviously, backends can also add more details and make nicer error messages. But they don't *have* to. - Separate out the backend classes from our wrapper class. Now there is no possibility of namespace collision. All our API methods use one underscore. Anything else (zero or two underscores) are for the backend class's use. - Added the concept of a 'backend prefix' which is used by par2 and gio backends to provide generic support for "schema+" in urls -- like par2+ or gio+. I've since marked the '--gio' flag as deprecated, in favor of 'gio+'. Now you can even nest such backends like par2+ gio+file: //blah/ blah. - The switch to control which cloudfiles backend had a typo. I fixed this, but I'm not sure I should have? If we haven't had complaints, maybe we can just drop the old backend. - I manually tested all the backends we have (except hsi and tahoe -- but those are simple wrappers around commands and I did test those via mocks per above). I also added a bunch more manual backend tests to . /testing/ manual/ backendtest. py, which can now be run like the above to test all the files you have configured in config.py or you can pass it a URL which it will use for testing (useful for backend authors). Branch metadata - Branch format: - Branch format 7 - Repository format: - Bazaar repository format 2a (needs bzr 1.16 or later) - Stacked on: - lp:duplicity/0.7-series
https://code.launchpad.net/~mturquette/duplicity/duplicity
CC-MAIN-2018-26
refinedweb
494
66.03
Contents Macros function called macro_MacroName(macro, arg1, arg2, ...), which is the entry-point. the first argument macro is an instance of class Macro, and also evaluates to a string of the macroname, - arguments arg1, arg2, ... are the arguments given by the user, but special rules apply, see below. You can access the request object by using macro.request - e.g. to access form parameters and other information related to user interaction. Your function should use the formatter to construct valid markup for the current target format. In most cases this is HTML, so writing a macro which returns HTML will work in most cases but fail when formats like XML or text/plain are requested - you can use macro.formatter to access the current formatter. For example, your wiki page has the following line on it: <<MacroName(True, 1.7772, 17)>> You could write a MacroName.py file like this: 1 from MoinMoin.wikiutil import get_unicode, get_bool, get_int, get_float 2 3 Dependencies = [] 4 generates_headings = False 5 6 def macro_MacroName(macro, arg1, arg2, arg3=7): 7 # arguments passed in can be None or a unicode object 8 9 arg1 = get_bool(macro.request, arg1) 10 arg2 = get_float(macro.request, arg2) 11 # because arg3 has a default of 7, it is always of type int or long 12 13 return macro.formatter.text("arguments are: %s %2.3f %d" % (arg1, arg2, arg3)). If your macro can generate headings (by calling macro.formatter.heading()) then set generates_headings to True to allow the TableOfContents macro to evaluate your macro for headings to take into the table of contents. Macro arguments The arguments given to your macro are normally passed as unicode instances or None if the user gave no argument. Consider this example macro: and the wiki code (together with the result) 1. <<Example()>> - passes None, None 2. <<Example(a,b)>> - passes u'a', u'b' 3. <<Example(,)>> - passes None, None 4. <<Example("",)>> - passes u'', None default values If your macro declares default values as in this example: Then the arguments can be skipped or left out and are automatically converted to the type of the default value: 1. <<Example()>> - passes 7, 2.1 2. <<Example(,3)>> - passes 7, 3.0 3. <<Example(2)>> - passes 2, 2.1 4. <<Example(a,7.54)>> - error, "a" not an integer Additionally, it is possible to declare the type you would like to get: def macro_Example(macro, arg1=int, arg2=float): ... This requires that the user enters the correct parameter types, but it is possible to skip over them by giving an empty argument in which case it'll be passed into the macro code as None: 1. <<Example()>> - passes None, None 2. <<Example(a, 2.2)>> - error, "a" not an integer 3. <<Example(7, 2.2)>> - passes 7, 2.2 4. <<Example(, 3.14)>> - passes None, 3.14 unit arguments If your macro declares unitsarguments then units are required as in this example: The defaultunit of px is used if the user does not enter a unit. He has to enter valid units of px or %. 1. <<Example()>> - argument is: None 2. <<Example(100)>> - argument is: 100px 3. <<Example(100mm)>> - <<Example: Invalid unit in value 100mm (allowed units: px, %)>> 4. <<Example(100px)>> - argument is: 100px choices If your plugin takes one of several choices, you can declare it as such: This requires that the user enter any of the given choices and uses the first choice if nothing is entered: 1. <<Example(apple)>> - passes u'apple' 2. <<Example(OrAnGe)>> - error, tells user which choices are valid 3. <<Example()>> - passes u'apple' required arguments If you require some arguments, you can tell the generic code by using the required_arg class that is instantiated getting the type of the argument: from MoinMoin.wikiutil import required_arg def macro_Example(macro, arg1=required_arg(int)): ... This requires that the user enters the argument: 1. <<Example()>> - error, argument "arg1" required 2. <<Example(4.3)>> - error, "4.3" not an integer 3. <<Example(5)>> - passes 5 keyword arguments If your macro needs to accept arbitrary keyword arguments to pass to something else, it must declare a _kwargs parameter which should default to the empty dict: This makes the user able to pass in anything, even arbitrary unicode strings as key names: 1. <<Example(äöü=7)>> - passes the dict {u'äöü': u'7'} 2. <<Example(=7)>> - passes the dict {u'': u'7'} 3. <<Example(a=1,"d e"=3)>> - passes the dict {u'a': u'1', u'd e': u'3'} 4. <<Example(a)>> - error, too many (non-keyword) arguments trailing arguments Trailing arguments allow your macro to take any number of positional arguments, or to be able to handle the syntax of some existing macros that looks like [[Macro(1, 2, 3, name=value, name2=value2, someflag, anotherflag)]]. In order to handle this, declare a _trailing_args macro parameter which should have a an empty list as the default: Also, when the user gives too many arguments, these are put into _trailing_args as in the second example: 1. <<Example(1, 2, 3, name=test, name2=test2, flag1)>> - valid, passes u'flag1' in _trailing_args 2. <<Example(1, 2, 3, test, test2, flag1)>> - same It is possible to use this feature together with the arbitrary keyword arguments feature _kwargs.
http://wiki.apache.org/logging-log4cxx/HelpOnMacros?action=show&redirect=AideDesMacros
CC-MAIN-2015-22
refinedweb
871
57.16
Dear Haskellers, after the first rush of volunteers seems to have ebbed away, it is probably time for a reminder. First, the good news: We have just about enough topics covered to convince me that it makes sense to go ahead. So the Haskell Communities page has moved to a more permanent location at and any further documents will appear there as well. I even have the first reports coming in already (thanks very much!). If everyone else could please send in their reports over the next two weeks, i.e., before *** Monday, 29. October 2001 ***, then I could try to edit everything together in the following week (modulo my own deadlines..) and put out the first version of the collective Haskell Communities Status Report early in November. Simon Marlow sent a nice example of a (more frequent) report from the FreeBSD community, which might give an idea of how a collection of brief summaries can help to get and keep an overview of a field: So far, so good. The not so good news is that there are still some quite important areas uncovered, so *** we are still looking for active Haskellers *** *** to write (and send to me) brief summaries. *** Below, you'll find first a list of topics I would like to see covered, then the list of topics for which we already have volunteers. If you think you can help out with information on one or more of the outstanding topics, please let me know. If you have the information, but are unsure about what would be a useful summary for the report, get in touch with me and we'll see what we can do. Cheers, Claus ------------------------------------ contacts still needed: ------------ core * Haskell Central changes over the last year, plans for the next few months? * Hugs often feared to be dying, but kept very much alive by enthusiasts; Currently, OGI and other enthusiastic volunteers are supporting. Any ideas about the future? What about the new release (when, what)? * nhc98 lots of new work there, though much of it will probably be covered by Olaf's report on tracing and debugging? !! for all implementations, it would be nice to know the !! position and status regarding recent extensions that !! need support to be portable, such as FFI, hierarchical !! modules namespace, portable libraries, GUI API & libraries. ------------ others * non-sequential Haskell This is an important and active area, and we seem to have lots of projects there. Ideally, someone in the field could give an overview of the state-of-the-art, but I would also be happy to get summaries from individual projects (we've got Concurrent Haskell, but nothing else yet; what about GPH, port-based distributed Haskell, ..?). [and why is there no dedicated mailing-list for the collection of non-sequential Haskell projects?] * meta programming support for Haskell Tim Sheard would like to start a project on a Haskell version of Meta ML. Any progress there? Meanwhile, there are a small number of Haskell parsers and pretty-printers around. But how complete are they, are they being kept up to date, what about language extensions? What about a standard AST format? What about static analysis and type checking/inference? A standard interface to symbol table information? Partial evaluation for Haskell?-) Reification/reflection (Bernard Pope and Lee Naish have done some work here in the context of declarative debugging)? Why all the extra tools, btw? Could we not have a standard interface to the parsers, type checkers, symbol tables that exist in our Haskell implementations (as is the case for other respectable languages?-) * lightweight modules for Haskell At this year's Haskell workshop, Mark Shields asked those interested to cooperate on this topic to contact him, mentioning that he was working on the topic. It would be useful to have an idea of the plans there. Aha, I've just found a brand new paper on that, perhaps Mark could give a brief summary of that and the implementation plans?-) * Haskell libraries collection will that be covered in the report on hierarchical module namespaces or do we need a separate report? Simon? * FFI tools Manuel will cover FFI language extensions and libraries, as well as his own C->Haskell, but what about the other tools built on top of the FFI basis? What is the status of Greencard, Hdirect & co? What about all that recent talk about new Haskell to Java connections?-) If anything is still (or newly) active: summaries&pointers, please! * Documentation tools earlier this year, there was some work and discussion on this. Anyone willing to summarise the results? * Applications Perhaps someone at Galois Connections could summarise their recent successes and immediate plans (I've heard lots of good news from that direction recently)? Haskell in hardware specification and verification? ..others.. * Formal basis The effective lack of a formal semantics for Haskell has been a constant source of embarrassment (functional languages: solid theoretical basis, effective reasoning about programs, ...; Haskell: ???, ahem, oops). There seems to have been some progress recently, and it would be nice to hear more about all that. E.g., what state the work is in, what the immediate plans are, where to get the (draft) deliverables, if any: - Karl-Filip Faxen, KTH Stockholm, has been working on a formalisation of Haskell's static semantics. - the Programmatica project at OGI, Oregon, has been working on an implementation of Haskell's static semantics in Haskell; and had to ask for clarification of ambiguities in the ongoing revisions of the Haskell 98 language report. - Andrew Tolmach, OGI, has been working on a formal specification of GHC's version of core Haskell, the subset into which full Haskell is translated for definition, compilation and optimisation. - the functional programming group at York has been working on operational semantics for Haskell to support their work on profiling and tracing, to enable reasoning about time and space behaviour, and about execution traces. - .. other work in this area..? ------------------------------------ volunteers so far: GHC Simon Peyton-Jones Foreign function interface (language extensions & libraries) Manuel Chakravarty Hierarchical module namespaces Simon Marlow GUI library API new task force [summarised by Manuel's recent announcement] Concurrent Haskell Simon Marlow Generic programming Johan Jeuring [report done!] Tracing and debugging Olaf Chitil Happy Simon Marlow C->Haskell Manuel Chakravarty Functional Reactive Programming (at Yale) John Peterson
http://haskell.org/pipermail/haskell/2001-October/002025.html
crawl-002
refinedweb
1,047
61.77
#region .Net Blog using System; using System.Windows.Forms; namespace CS_Script { class CS_Script { static void Main(string[] args) { if (args.Length > 0) { } else { MessageBox.Show("You need to provide the filename as an argument!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /* Main */ } /* CS_Script */ } /* CS_Script */); ExecuteSource(textFile); MessageBox.Show("The file could not be executed:\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);course; class CScript { public void Main() { MessageBox.Show("I'm being loaded dynamicly!"); We reached our goal of running code from a text file for now. In my next article I'll talk about adding our CS-Script.exe file to the shell menu so we can use it on our files. As always, I've uploaded the sources for this project. Update: Here is the article about adding your menu to the shell: Associating your program with every file - ShellExtension Real well done :) I Like it. It has been very usefull it's very nice, this could by usefull if you want to test small files, cool :) Very nice one (y), good work David. I will test it immediately. Looks like SnippetCompiler: Thanks for the link! Going to check it out this afternoon, looks wonderfull :) good work, very nice code! I really like it
http://weblogs.asp.net/cumpsd/articles/80785.aspx
crawl-002
refinedweb
205
70.29
How can I close another running program by reference of the file (.exe) name? Printable View How can I close another running program by reference of the file (.exe) name? Use EnumProcesses() to get a list of all the running processes. Then use OpenProcess() on each of them to get handles. Once you've got the handle you can use GetModuleFileName() to see if that process matches your filename, and if it does, use something like TerminateProcess() to close it. I'll have a go at that. Thankyou very much. :) I can't do it. I don't even know the syntax of EnumProcesses(), and google didn't find me anything I could understand. If it's not to much trouble do you think you could show me how to list the current processes? MSDN Okey dokes, It's a compiler problem I have now. I'm using dev-c++ and I'm getting this error: [Linker error] undefined reference to `EnumProcesses@12' My code it this: Thanks for the help so far. :)Thanks for the help so far. :)Code: #include <iostream> #include <stdlib.h> #include <psapi.h> using namespace std; int main(int argc, char *argv[]) { DWORD aProcesses[1024],cbNeeded; EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ); system("PAUSE"); return 0; } Did you see this example ? Does it help you? Yup. I guess it's just the compiler. Looks like I'll have to strengthen the Gates Empire more by buying Visual C++, which was the last thing I wanted to do because I don't have a job and it'll take my life savings to get a copy (I'm only 16). >>> I guess it's just the compiler. From memory, those headers and libraries are not in the standard compiler stuff, they are included with the Platform SDK. Have you downloaded that? What's that and where can I get it? I've seen it metioned in many places and I guess it stands for software dev. kit and that it probably aids in developing for win32 platform but that's about all I guess.. If you could please elaborate I'd be very grateful. :) I just killed my SDK and tried to compile this... ... and got exactly the same error as you. Reinstall the SDK, (actually re-link it to VC), and the thing compiles and runs fine, so I would definitely try this first.... and got exactly the same error as you. Reinstall the SDK, (actually re-link it to VC), and the thing compiles and runs fine, so I would definitely try this first.Code: #include <windows.h> #include <psapi.h> #include <iostream> using namespace std; int main() { DWORD Pids[100]; DWORD BytesUsed; int RetVal; RetVal = EnumProcesses(Pids, sizeof(Pids), &BytesUsed); cout << "There are " << (BytesUsed/sizeof(DWORD)) << " processes." << endl; return 1; } There are a few different SDK's some are only interesting if you have other bits of software, look here. Warning! Some of these downloads are very big! *** EDIT *** Your guesses as to what it is and what the SDK stand for are correct. Okey dokey, since I'm on a 56k and I'm almost over my 500mb download limit for the month (can't get broadband where I live :() I have to wait a few days to start the download and then probably a day for it to download. I'll be back sometime in the next few days. :) Thanks for all your help so far. :D The other routines I mentioned are in the standard windows.h, so you should be able to try them out, and maybe write a program which allows you to manually enter a PID. That way, when you've got the SDK you'll only need to stick that bit on the front. The PSAPI stuff isnt accessable easilly with the standard includes and libs that comne with VC++, you need the SDK (as adrian said). I have been caught needing these funcs before on a clean install of my compiler (same problem as you - a 100MB+ download on 56K is a swine!), so if your in a tight place you can manually do the loading yourself... Here's an example I used of getting EnumProcesses without the SDK - Might give you an option for now until you have downloaded the SDK (PS....I have broadband now - definately worth the upgrade ;))
http://cboard.cprogramming.com/windows-programming/41012-closing-other-programs-cplusplus-printable-thread.html
CC-MAIN-2014-52
refinedweb
725
74.08
Being able to automate stuff and make useful bots in Facebook messenger appears to be interesting and cool, in this tutorial, we will see how we can connect in Facebook messenger in Python and do various of different cool things! We gonna be using fbchat library, it works by emulating the browser. This means doing the exact same GET/POST requests and tricking Facebook into thinking it's accessing the website normally. Therefore, this API isn't official and it doesn't require any API key, instead, it requires the credentials of your Facebook account. Related: How to Send Emails in Python using smtplib Module. First, you gonna need to install fbchat library: pip3 install fbchat Now to get started, make an empty python file or open up an interactive shell or jupyter notebook and follow along, let's import fbchat: from fbchat import Client from fbchat.models import Message Let's first login: # facebook user credentials username = "username.or.email" password = "password" # login client = Client(username, password) Note: You need to enter correct facebook credentials, otherwise it won't make any sense following with this tutorial. We have now the client object, there are a lot of useful methods in it, try to dir() it. For instance, let's get the users you most recently talked to: # get 20 users you most recently talked to users = client.fetchThreadList() print(users) This will result in a list of threads, a thread can be a user or a group. Let's search for our best friend, let's get all the information we can get about these users: # get the detailed informations about these users detailed_users = [ list(client.fetchThreadInfo(user.uid).values())[0] for user in users ] Luckily for us, a thread object have a message_count attribute that counts number of messages between you and that thread, we can sort by this attribute: # sort by number of messages sorted_detailed_users = sorted(detailed_users, key=lambda u: u.message_count, reverse=True) We have now a list of 20 users sorted by message_count, let's get the best friend easily by: # print the best friend! best_friend = sorted_detailed_users[0] print("Best friend:", best_friend.name, "with a message count of", best_friend.message_count) Let's congratulate this friend by sending a message: # message the best friend! client.send(Message(text=f"Congratulations {best_friend.name}, you are my best friend with {best_friend.message_count} messages!"), thread_id=best_friend.uid) Let me take a look at messages: Awesome, right ? If you want to get all the users you talked to in messenger, you can by: # get all users you talked to in messenger in your account all_users = client.fetchAllUsers() print("You talked with a total of", len(all_users), "users!") Finally, when you finish, make sure you logout: # let's logout client.logout() As you can see, there are endless of possibilities you can do with this library, you can make automatic reply messages, a chatbot, echobot and many more cool functionalities. Please check their official documentation. Learn Also: How to Extract All Website Links in Python. Happy Coding ♥View Full Code
https://www.thepythoncode.com/article/make-bot-fbchat-python
CC-MAIN-2020-16
refinedweb
509
61.87
I'm taking a Java class and need some help. I need to create a java class tp accepts a users houlry rate of pay and number of hours worked and will display the users groos pay, the withholding tax 15% of gorss pay and netpay (gross pay - withholding) here is what i have but can get it working. Any help ? public class Payroll { public static void main (String [] args) { String name; int hours; double rate; double fedTax; System.out.print("Enter number of hours worked in a week: "); System.out.print("Enter hourly pay rate: "); System.out.print("Enter federal tax withholding rate: "); double grossPay; grossPay = rate * hours; double fedwithHolding; fedwithHolding = fedTax * grossPay; double netPay; netPay = (grossPay) - deduction; System.out.println("The netpay is " +netPay); } }
https://www.daniweb.com/programming/software-development/threads/379496/java-class-question
CC-MAIN-2017-43
refinedweb
126
55.13
wubi-r129.exe crashes when python 2.2 is preinstalled. deleted and the process quits. Note that the wubi GUI never starts, so no wubi logs get created. I am happy to provide further information, but need pointing in the right direction :-) . Is there a way of diagnosing/logging exactly what is happening on this machine? . Are there any dependencies for unpacking wubi that may be missing from this machine? EDIT: The thinkpad has C:\IBMTOOLS\ Is this likely to affect the package? None of the other machines that it worked successfully on have any python versions. > try running without python22 I tried this, and it made no difference. > It will require a special build in order to see more messages Assuming that the "special" build will simply be a debug one, I tried wubi-r117-debug.exe as that is available from the same place. This is the error the thinkpad gets with wubi-r117-debug.exe ------- C:\u-904> C:\u-904>Traceback (most recent call last): File "Z:\home\ File "Z:\home\ line 26, in ? File "Z:\home\ line 1, in ? File "Z:\home\ line 33, in ? File "Z:\home\ line 1, in ? File "Z:\home\ line 42, in ? File "Z:\home\ line 29, in ? File "Z:\home\ line 49, in ? File "Z:\home\ line 47, in ? File "Z:\home\ line 47, in ? ImportError: No module named Util.number C:\u-904> ------- One of the other machines (that worked with r129) loads the GUI with r117-debug and asks me if I want to uninstall. I don't want to, so I stopped there, but the GUI loaded with no traceback on the console. A different machine (not previously installed with wubi) loads the r117-debug GUI fine with no traceback. As I don't want Ubuntu on that machine I stopped at that point. If I still need to try a special build, I'll do that when you let me know where to get it from. Cheers, Pete Hmm you should have a file in the temp folder called lib/Crypto/ It would be interesting to see Util.__file__ I got a similar problem and I really don't know where to look to diagnose it. On an Windows XP SP3 HP Pavilion machine with AMD Athlon CPU, the GUI seems to try hard to start, but it simply does not. I attached the log file in temp folder. By the way, one interesting line of log: 04-24 10:52 DEBUG Distro: checking Ubuntu ISO D:\kubuntu- I don't know what it means, but Wubi is started from another subdirectory (With kubuntu- 04-24 10:52 DEBUG CommonBackend: original_ I may provide additional details, if you say so. Erdogan, The content of .disk/info inside of your ISO seems incorrect, probably the ISO is corrupted or a partial download. That shouldn't be fatal though. The issue is different from parent, please open a different bug report 04-24 10:52 DEBUG WindowsBackend: extracting .disk\info from D:\kubuntu- 04-24 10:52 DEBUG Distro: info=ÖdʼPt”Gzyí¢ ¼k8 > Hmm you should have a file in the temp folder called lib/Crypto/ > It would be interesting to see Util.__file__ The temp folder gets immediately deleted before I can see the contents. To try and get the chance to see what happens, I have pulled lp:wubi and built wubizip on a separate machine. Results on the thinkpad: -------\ import Crypto.Util.number as NUM File "C:\u-904\ import Crypto.Util.number as NUM ImportError: No module named Util.number C:\u-904\ # installing zipimport hook import zipimport # builtin # installed zipimport hook 'import site' failed; traceback: ImportError: No module named site # C:\u-904\ import warnings # precompiled from C:\u-904\ # C:\u-904\ import types # precompiled from C:\u-904\ # C:\u-904\ import linecache # precompiled from C:\u-904\ # C:\u-904\ import os # precompiled from C:\u-904\ import nt # builtin # C:\u-904\ import ntpath # precompiled from C:\u-904\ # C:\u-904\ import stat # precompiled from C:\u-904\ # C:\u-904\ import UserDict # precompiled from C:\u-904\ # C:\u-904\ import copy_reg # precompiled from C:\u-904\ Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ^Z # clear __builtin__._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.exitfunc # clear sys.exc_type # clear sys.exc_value # clear sys.exc_traceback # clear sys.last_type... Please add some logging before openpgp\ log.debug(path) import Util log.debug( To disable dir deletion edit src/pylauncher/ delete_ Then rebuild it's actually import sys log.debug(sys.path) import Crypto log.debug( import Crypto.Util log.debug( -------\ log. NameError: name 'log' is not defined ---------- That didn't seem to work, so I tried manually: -------- C:\u-904\ Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import Crypto.Util import Crypto # directory C:\u-904\ import Crypto # from C:\u-904\ # wrote C:\u-904\ import Crypto.Util # directory C:\u-904\ import Crypto.Util # from C:\u-904\ # wrote C:\u-904\ >>> Crypto. 'C:\\u- >>> import Crypto >>> Crypto.__file__ 'C:\\u- >>> import Crypto.Util.number import Crypto.Util.number # from C:\u-904\ # wrote C:\u-904\ import Crypto.PublicKey # directory C:\u-904\ import Crypto.PublicKey # from C:\u-904\ # wrote C:\u-904\ import struct # builtin >>> Crypto. 'C:\\u- -------- 2009/4/24 Agostino Russo <email address hidden>: > it's actually > > import sys > log.debug(sys.path) > import Crypto > log.debug( > import Crypto.Util > log.debug( > > -- > wubi-r129.exe does nothing. > https:/ > You received this bug notification because you are a direct subscriber > of the bug. > > Status in Wubi, Windows Ubuntu Installer: Confirmed > > del... Yes, you need the logging module as well. Manual import seems fine. Any word on this? Wubi still doesn't work for me as of r134. I have a ThinkPad R50e with XP SP3, just like the OP. Originally used Wubi to install 8.10, but have had this issue with the 9.04 Wubi (when picking up the debug build I have the same Util.number import error as the OP, even after removing C:\IBMTOOLS\ I have tried to install python 2.2 but cannot replicate this. You will have to add some log.debug statements in the code and narrow it down. Any news on that? I downloaded Wubi from http:// Hi, same result. Nothing happens. Any other ideas? Fabian I have this exactly problem too. I'm sorry, my english is very bad. Please post the logs, they are in your user temp folder (%temp%) Hi Agostino, I have not been paying any attention to this recently, but it seems to be affecting a few other people too. As I raised this, I feel morally obliged to help you diagnose it :-) I *think* the problem all us thinkpad users are having is that nearly all the OEM tools installed on the thinkpad are written in python (2.2). My gut feeling is that there is a conflict somewhere between the OEM tools and the wubi installer, but I don't know how to track it down. I suspect it is in the logger itself - the OEM config on this thinkpad explicitly defines a PYTHONPATH environment variable (%SystemDrive% If you tell me what to try, I'll give it a go in the next few days. Cheers, Pete Quick update on this: I pulled and built wubizip from trunk this morning, and have played with it a bit. If I modify openpgp/ # import Crypto.Util.number as NUM Then I get the wubi frontend and a logfile (attached). Obviously wubi chokes when it tries to check the file signatures, but this is further than I have got the python wubi to run previously. Let me know what else to try, and I'll get back to you. Cheers, Pete UPDATE: Workaround available You may close this issue as I can now run wubi on the thinkpad. This is actually a system configuration problem, not a bug in wubi. The thinkpad has the environment variable PYTHONCASEOK set. It appears to be a common known issue with certain thinkpads, as a quick search for PYTHONCASEOK will confirm. There seem to be a lot of Python developers who think IBM is a four letter word :-D I have tried a few variations of this, with mixed results. Executing python.exe -E main.py - works with wubizip builds Unsetting PYTHONCASEOK at a command prompt does not allow wubi to run. Setting PYTHONCASEOK to any value other than 1 does not allow wubi to run. Cheers, Pete Feel free to add this to the FAQs if you like. ----- Thinkpad Workaround to use Wubi 9.04 1. Right click on My Computer, select Properties OR Go to Control Panel -> System 2. On the 'Advanced' tab click the 'Environment Variables' button. 3. In the bottom pane ('System Variables') scroll down the list until you find the PYTHONCASEOK variable. 4. Highlight the PYTHONCASEOK line and click the 'Delete' button. (Just changing the value will not work.) 5. Reboot your thinkpad. 6. Run wubi.exe, and enjoy :-) 7. After installing wubi, you need to re-add PYTHONCASEOK with a value of 1 or your assorted IBM tools will not work. NOTE: You will also need to repeat steps 1-5 if you want to uninstall wubi in the future, as the wubi uninstaller will have the same problem. Don't forget to do step 7 again after running the wubi uninstaller. Actually I found an easier method: INSTALL: Create a new text file containing these two lines: SET PYTHONCASEOK= wubi.exe Save the file with the name wubi-install.bat in the same folder as your downloaded wubi.exe Double click the wubi-install.bat batch file to install. UNINSTALL Create a new text file containing these two lines: SET PYTHONCASEOK= uninstall-wubi.exe Save the file with the name wubi-uninstall.bat in the same folder as your uninstaller (Default is C:\ubuntu) Double click the wubi-uninstall.bat batch file to uninstall. Both these batch files are in the attached zip file. - @Agostino : I tried adding SetEnvironmentV to pyrun.c and rebuilding, but it doesn't seem to work. Adding "-E" to argv[] wouldn't be a good idea, as that would prevent all the other PYTHON* environment variables working :-) Could you printout sys.path and os.environ within wubi? You can use log.debug within application.py Hi again Ago, With PYTHONCASEOK set, application.py fails on from wubi.backends.win32 import WindowsBackend The cause of this, as mentioned above is openpgp/ import Crypto.Util.number as NUM Because python is running case insensitive search, the first match this gets for Crypto is actually crypto in the openpgp/sap directory. This means the module is actually trying : import openpgp. with the results we have seen all along : ImportError: No module named Util.number You can investigate this further on your build machine by setting the environment variable: export PYTHONCASEOK=1 Then when you 'make runbin' you will get exactly the same behaviour in wine. Cheers, Pete ----- Extra info as requested. # log extract (reformatted for clarity) 06-02 10:56 DEBUG root: ** extra info BEGIN ** 06-02 10:56 DEBUG root: sys.path = [ 'C: 'C: 'C: 'C: 'C: 'C: 'C: 'C: 'C: ] 06-02 10:56 DEBUG root: os.environ = { 'TMP': 'C:\\DOCUME~ 'COMPUTERNAME': 'THINKPAD', 'USERDOMAIN': 'THINKPAD', 'COMMONPROG 'PROCESSOR_ 'PROGRAMFILES': 'C:\\Program Files', 'PROCESSOR_ 'SYSTEMROOT': 'C:\\WINDOWS', 'PATH': 'C:\\PROGRAM FILES\\ 'IBMSHARE': 'C:\\IBMSHARE', 'TK_LIBRARY': 'C:\\IBMTOOLS\ 'TEMP': 'C:\\DOCUME~ 'PROCESSOR_ 'ALLUSERSPR 'SESSIONNAME': 'Console', 'HOMEPATH': '\\Documents and Settings\\Stacey', 'RRU': 'C:\\Program Files\\IBM\\IBM Rapid Restore Ultra\\', 'USERNAME': 'Stacey', 'LOGONSERVER': '\\\\THINKPAD', 'PROMPT': '$P$G', 'COMSPEC': 'C:\\WINDOWS\ 'PYTHONPATH': 'C:\\IBMTOOLS\ 'TCL_LIBRARY': 'C:\\IBMTOOLS\ 'PATHEXT': '.COM;. 'CLIENTNAME': 'Console', 'FP_ 'WINDIR': 'C:\\WINDOWS', 'APPDATA': 'C:\\Documents and Settings\ 'HOMEDRIVE': 'C:', 'SYSTEMDRIVE': 'C:', 'NUMBER_ 'PROCESSOR_ 'OS': 'Windows_NT', 'USERPROFILE': 'C:\\Documents and Settings\\Stacey' } 06-02 10:56 DEBUG root: ** extra info END ** This bug has been reported on the Ubuntu ISO testing tracker. A list of all reports related to this bug can be found here: http:// It will require a special build in order to see more messages, we will provide one in the coming days. An existing python version should not change thing, but you might want to try running without python22 (it should be sufficient to remove it from PATH and PYTHONHOME env variables).
https://bugs.launchpad.net/wubi/+bug/365501
CC-MAIN-2017-09
refinedweb
2,110
67.86
David) Background Brief Outline of the Steps Step 1: Authoring the User Control Step 2: Testing Your User Control Step 3: Use the Publish Command to Precompile the Site Step 4: Finding the Resulting Custom Control Step 5: Using Your New Custom Control Conclusion About the author Since its early days, ASP.NET has always supported two different ways of authoring server controls: These two methods are very different, and each has a number of advantages and disadvantages. I won't discuss them all, but will focus on those that are relevant to this article: The goal of this article is to show how you can have the best of both worlds by turning an ascx user control into a redistributable custom control, by making use of the new ASP.NET precompilation features. The basic steps to make this happen are as follows: We will look at those steps in more detail in the rest of the article. To author the user control, it is best to start with an empty app that contains nothing other than the ascx. While the authoring of the user control uses "standard" techniques, there are some restrictions that you need to be aware of in order for it to be successfully turned into a standalone custom control. The main restriction is that the user control needs to be self-contained. That is, it cannot be dependent on app global things like App_Code or global.asax. The reason for this is that since the goal is to turn the UserControl into a standalone DLL, it would break in other apps if it relied on code that is not part of that DLL. One exception to this rule is that the UserControl can be dependent on assemblies that live in the bin directory (or in the GAC). You just have to make sure that the other assemblies are always available when you use your custom control in other apps. Another tricky thing is the use of static resources,). So let's start and actually author the user control. Visual Studio 2005 gives you the choice to place the code in a separate file, or use inline code. This is a matter of personal preference, and either one will work to create a custom control. For this article, we will use inline code. When you create the user control (say MyTestUC.ascx),. Before trying to turn the user control into a custom control, it is a good idea to test it in the source app using a simple page. To do this, simply create a new Page in Visual Studio, go to design View, and drag and drop your user control into it. The two notable pieces of your page are the Register directive: <% CTRL-F5) and make sure the user control works the way you want before moving to the next step. The next step is to use the new Publish command to precompile your site and turn your user control into a potential custom control. You'll find the command under Build / Publish Web Site. In the Publish dialog, do the following: on this in Step 5. Go ahead and complete the dialog, which will perform the precompilation. Note This same step can also be accomplished without using Visual Studio by using the new aspnet_compiler.exe command-line tool. The options it supports are basically the same as what you see in the Publish dialog. So if you are more command-line inclined, you might prefer that route. For example, you would invoke it using the command: aspnet_compiler -p c:\SourceApp -v myapp -fixednames c:\PrecompiledApp. aspnet_compiler -p c:\SourceApp -v myapp -fixednames c:\PrecompiledApp Now, using the Windows Explorer or a command-line window, let's go to the directory you specified as the target so we can see what was generated. You will see a number of files there, but let's focus on the one that is relevant to our goal of turning the user control into a custom control. In the "bin" directory, you will find a file named something like App_Web_MyTestUC.ascx.cdcab7d2.dll. You are basically done, as this file is your user control transformed into a custom control! The only thing that's left to do is to actually use it. Note In case you're curious, the hex number within the file name (here cdcab7d2) is a hash code that represents the directory that the original file was in. So all files at the root of your source app will use cdcab7d2, while files in other folders will use different numbers. This is used to avoid naming conflicts in case you have files with the same name in different directories (which is very common for default.aspx!). cdcab7d2 Now that we have created our custom control, let's go ahead and use it in an app. To do this, create a new Web application in Visual Studio. We then need to make our custom control available to this application: Note as an alternative, you can choose to place the assembly in the GAC instead of the "%> Note how we are using a different set of attributes compared to Step 2. Recall that in Step 1, we made sure that the ClassName attribute included a namespace. This is where it becomes useful, as custom control registration is namespace-based. Also, you need to specify the assembly name, which is why having a name that is easily recognizable is useful, as discussed in Step 3. Declare a tag for the custom control, for example: <Acme: That's it, you can now run your app (CTRL-F5), and you are using your new custom control! This shows how to use your custom control declaratively, but note that it can also be used dynamically, just like any other control. To do this, just create the control using "new". Here is what the previous sample would look like using dynamic instantiation: <%@PageLanguage="C#"%> <!DOCTYPE html PUBLIC "-//W3C//DTDXHTML1.0Transitional//EN" ""> <script runat="server"> protected void Page_Load(objectsender, EventArgse){ Label1.Controls.Add(newAcme.MyTestUC()); } </script> <html> <body> < <div> <asp:</asp:Label></div> </form> </body> </html> Note Instantiating your custom control dynamically as described above is basically the equivalent of instantiating your original user control using the LoadControl API. Note that you can no longer use the standard LoadControl API after converting it to a custom control, since custom controls don't have a virtual path. However, ASP.NET 2.0 has a new LoadControl override. David Ebbo is a software architect on the ASP.NET team, and has worked on the product since its pre-1.0 days. His areas of expertise include the parser, compilation system, and various parts of the control framework.
http://msdn.microsoft.com/en-us/library/aa479318.aspx
crawl-002
refinedweb
1,121
60.45
CodePlexProject Hosting for Open Source Software Hi guys! I'm using the DbTranslations module in combination with the multitenancy. Each tenant is a different language version of the site. The obstacle I just arrived at is trying to translate the hardcoded url's to pages: /searchresults in English should be /zoekresultaten in Dutch. I implemented IRouteProvider as followed: public class Routes : IRouteProvider { private Localizer T { get; set; } public Routes() { T = NullLocalizer.Instance; } } Unfortunately, the routes are added before the localizer is instantiated, resulting in the routes not being translatable. In a second attempt I tried creating an ActionFilter (or AuthenticationFilter, same result), which install the routes. Problem here is that the routes are now only added to the routetable when a visitor first hits a non-translatable page. So the question is: how do I get to the translations from the application_start? That's where I want to enable the routes. Or is there another place this can be done? Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://orchard.codeplex.com/discussions/400279
CC-MAIN-2014-42
refinedweb
196
67.04
I am working on project and getting this error ImportError: No module named plotly.plotly I tried: - pip install plotly - pip install –upgrade plotly But import plotly.plotly as py didn’t work. Not sure if pyzo and python modules are stored at different location on your computer. And how they are referred. But you can try following to give absolute path name for plotly while loading module and see if it works. import sys sys.path.insert(0, c:pyzo2015alibsite-packagesplotly') import plotly.plotly as py I had the same exact problem, but the current answer did not resolve my issues. If that’s the case, here is an alternative (IDE dependent): I was not having success with the “pip” stuff. I am using PyCharm, and the following simple steps took care of my problems in less than 30 seconds. - Settings - Click Project: “MyProjectHere” in left hand nav menu - Select Project Interpreter from the above drop down - Find the green ‘plus’ sign near the upper right edge of the window that comes up. - Type Plotly in the search bar - Click install. Maybe one day I won’t be a dumb monkey who doesn’t know how to use a command line like all the cool kids, but for now this worked for me. I had the same problem installing plotly with pip and then import not being able to find it, but it worked when I used conda, instead.
https://techstalking.com/programming/question/solved-import-error-no-module-named-plotly-plotly/
CC-MAIN-2022-40
refinedweb
240
72.97
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project. "Stephen M. Webb" <stephen@bregmasoft.com> writes: | On Tue, 16 Oct 2001, Carlo Wood wrote: | > Why not removing the '#define _Bool bool' from 3.0's stdbool.h? | > I don't think people should use _Bool in user applications when | > compiling C++ programs with 3.x? They should use 'bool' that is | > the whole point of stdbool.h, so you can use 'bool' regardless. | | The C++ standard library should not be introducing names into the global | namespace. I would consider that an implementation flaw. >From Standard C++ point of view, _Bool is in the implementation namespace. | I think moving the type_traits names, all of them, into __gcc_cxx:: is worth | doing regardless. Agreed. -- Gaby
http://gcc.gnu.org/ml/libstdc++/2001-10/msg00141.html
crawl-001
refinedweb
130
67.86
I'm a software developer, hacker, and avid reader interested in all things tech I added a lot more to my REST API than just the JSON responses. Borum Jot was the first project I tried seriously unit testing my code, encrypting the data, and documenting my back-end. In this article, I will discuss cybersecurity, software testing, and documentation of my REST API. I encrypted my data using defuse/php-encryption. This library, claiming to be secure, unlike other libraries, did the encryption and decryption for me. To encrypt and decrypt, I needed my own key, which I generated by running: $ composer require defuse/php-encryption $ vendor/bin/generate-defuse-key Composer is a package manager for PHP applications. The key is 256 bits long and can be stored either in a file (unsecured) or in the environmental variables. Vercel has a built-in way of storing environmental variables, and was the best place, without extra tools, for me to store the key. Truthfully, I stored the key in a text file in the folder in the root directory because I didn't realize I could store it in thefolder in the root directory because I didn't realize I could store it in the etc at the time. This is highly insecure, so I am going to move this into a secure environmental variable soonat the time. This is highly insecure, so I am going to move this into a secure environmental variable soon $_ENV Then, at each request that updated or created data that I wanted to encrypt - task and note details - I loaded the key and called the encryption function. Similarly, for each request that fetched data that I encrypted, I loaded the key and decrypted before sending the response. This way, the front-ends never had to worry about encryption or decryption because I wrote everything on the backend, once. To document my APIs, I got inspiration from the Stack Exchange API documentation. I used NextJS to make a static documentation site for the entire Borum ecosystem, including Borum Jot. Then, for each page, I specified the request method, request headers, query-string, request body (for POST, PUT, and DELETE requests), and response body. Here is a given page of my developer documentation website, which is live, hosted by Vercel, and open-source on GitHub: A sample Borum Jot endpoint API reference on my Borum Dev Documentation site Because I am fluent in JavaScript, I did not have any trouble setting up the documentation site. I have a JSON file with data on each endpoint that I update whenever I update the Borum Jot REST API. I suggest including the following as a bare minimum when documenting REST or other Web API's: I used PHPUnit, a PHP unit-testing framework, and GuzzleHttp, a PHP HTTP client, to unit test my application. GuzzleHttp acts as a client to the REST API server, making requests and asserting information about the responses. namespace BorumJot\Tests; use PHPUnit\Framework\TestCase; use GuzzleHttp\Client; class LoginTest extends TestCase { private $http; public function setUp() : void { $this->http = new Client(["base_uri" => ""]); } public function testPost() { $response = $this->http->post('login'); $this->assertEquals(200, $response->getStatusCode()); $contentType = $response->getHeaders()["Content-Type"][0]; $this->assertEquals("application/json; charset=UTF-8", $contentType); } } The TestCase is a superclass in PHPUnit that indicates that the class contains test cases. The method is called by PHPUnit before each test. GuzzleHttp'smethod is called by PHPUnit before each test. GuzzleHttp's setUp() class's "request-method methods" (likeclass's "request-method methods" (like Client andand .get() ) provide information on the response, such as the headers and status code as shown above.) provide information on the response, such as the headers and status code as shown above. First I had to run to install the PHPUnit and GuzzleHttp packages.to install the PHPUnit and GuzzleHttp packages. composer install phpunit/phpunit guzzlehttp/guzzle I added the following to composer.json into the top-level object. "scripts": { "test": "phpunit tests" } This will substitute phpunit tests for composer test. It is a common practice to substitute the unit testing framework command for the package manager's command to have one command prefix to rule them all. However, this is not necessary, for you could simply run phpunit tests. The last step is to configure phpunit to find the folder with all the unit tests. I put mine in the root directory and called it , but you can call it and place it anywhere you would like, except maybe in auto-generated folders., but you can call it and place it anywhere you would like, except maybe in auto-generated folders. tests <?xml version="1.0" encoding="UTF-8"?> <phpunit bootstrap="vendor/autoload.php"> <testsuites> <testsuite name="Borum Jot REST API Test Suite"> <directory suffix=".php">./tests/</directory> </testsuite> </testsuites> </phpunit> Replace with the path to the folder with the unit tests. The test suite is an arbitrary name you give to a group of tests to identify it.with the path to the folder with the unit tests. The test suite is an arbitrary name you give to a group of tests to identify it. ./tests/ And that's how I documented, tested, and encrypted the data of my first REST API. Have you ever documented your own API? What tools did you use? Share your own projects down below! Create your free account to unlock your custom reading experience.
https://hackernoon.com/documenting-encrypting-and-unit-testing-my-first-rest-api-lz3c31ro
CC-MAIN-2021-17
refinedweb
907
52.9
I have written this code: // print.h #pragma once #ifdef __cplusplus #include <string> void print(double); void print(std::string const&); extern "C" #endif void print(); And the source file: // print.cxx #include "print.h" #include <iostream> void print(double x){ std::cout << x << 'n'; } void print(std::string const& str){ std::cout << str << 'n'; } void print(){ printf("Hi there from C function!"); } And the driver program: // main.cxx #include "print.h" #include <iostream> int main(){ print(5); print("Hi there!"); print(); std::cout << 'n'; } When I compile: gcc -c print.cxx && g++ print.o main.cxx -o prog - The program works just fine but what matter me a lot is: I compiled print.cxx using gcc which doesn’t define the C++ version print(double) and print(std::string). So I get print.o that contains only the definition of the C version of print(). - When I used G++to compile and build the program I passed print.oto it along with the source file main.cxx. It produces the executable and works fine but inside main.cxxI called the C++ versions of print(double)and print(std::string)) and these ones are not defined in prnint.obecause it has been compiled using GCC and because of the macro __cplusplus(conditional compilation). So how come that the linker doesn’t complain about missing definitions of those functions?? Thank you! Answer I compiled print.cxxusing gccwhich doesn’t define the C++ version… Not quite. gcc and g++ both invoke the same compiler suite. And the suite has a set of file extensions it automatically recognizes as either C or C++. Your *.cxx files were all compiled as C++, which is the default behavior for that extension. You can use the -x option to override the default behavior.
https://www.tutorialguruji.com/cpp/why-the-c-linker-doesnt-complain-about-missing-definitions-of-theses-functions/
CC-MAIN-2021-43
refinedweb
297
77.94
Java Meets SOAP SOAP is the Simple Object Access Protocol, a new protocol for distributed applications developed by Microsoft, IBM, DevelopMentor, and UserLand. I can see some of you frowning at the first mention of "distributed applications." The expression conjures visions of CORBA, DCOM. and RMI three technologies famous for their complexity. However, as we will see, SOAP strikes an interesting balance between complexity and flexibility. SOAP PrinciplesYou can approach SOAP from different angles. The simplest one is probably to see SOAP as a variation on file transfer a popular, but not very glamorous, approach to distributed computing. Indeed, many distributed applications rely on file transfer. The client uploads a file with its request. The server decodes the file and prepares its response for the client, again as a file. Popular Internet applications, including e-mail and the Web don't work differently. It may be less glamorous than calling RPC, as advocated by CORBA, DCOM, and RMI, but it is well understood, reliable, and very flexible. SOAP Request and ResponseA SOAP request looks like Listing 1. As you can see, it's an HTTP POST request with an XML payload. SOAP adds one new parameter to the HTTP header: SOAPAction. SOAPAction is an arbitrary URI identifying the request. It need not be the URL for the Web server; in many respects it is similar to URIs in XML namespaces. According to the specification, the SOAPAction parameter exists primarily to allow firewalls to filter SOAP requests by looking at the HTTP header only. The request is encoded in an XML document. SOAP defines an envelope and body elements (as well as an optional header). It encodes the procedure call as a XML element whose name is the method name ("reverse" in Listing 1) and whose content ("st" in Listing 1) is the call parameters. Listing 1. SOAP request. The server response is in Listing 2. Again, it's an HTTP response with an XML document. The XML document includes the same envelope and body. The result is encoded in the body (as you can see, the return element contains the reversed string). Listing 2. SOAP response.Clearly SOAP is a simple solution. It relies on HTTP (and soon SMTP) for transfering XML document. Reliance on HTTP guarantees that SOAP will work across most firewalls. Furthermore, an XML document encourages a lousy coupling between the client and the server. It proves more flexible than CORBA RPCs. Finally, since a SOAP request is essentially a Web page, it is not difficult to implement SOAP in servlets, JSP, ASP, or CGI scripts. Implementing SOAP in JavaAlthough it would not be difficult, as discussed previously, to roll your own implementation of SOAP. Java programmers have a simpler solution: IBM and DevelopMentor have released Java libraries that implement the protocol. They are available from (search SOAP for Java) and, respectively. To demonstrate them, we will implement the reverse client/server application using IBM's SOAP for Java 1.1. Listing 3 is the SOAP server with the method. You might wonder what makes it a SOAP server, Listing 3 looks suspiciously like a regular Java class. That's the beauty of the IBM library, which completely hides SOAP on the server. It uses a descriptor file (in Listing 4) to interpret SOAP calls in terms of Java objects. Listing 3. Reverse server. Listing 4. Service descriptor.The SOAP client is in Listing 5. Unlike the server, it relies heavily on SOAP objects, so you cannot mistake it for a regular class! Specifically, the client uses the Call object to implement the RPC. The Call object generates the XML document, establishes the HTTP connection, exchanges files, and decodes the result. Pay particular attention to the call to since it may be confusing. The URI is not the HTTP server where Reverse resides, this URI is used for an XML namespace. The URL for the server is passed as a parameter to . Listing 5. The SOAP client. Running This ExampleWhen installing this example, remember that SOAP for Java is still alpha software (it's part of AlphaWorks). You should not try running it unless you are comfortable working with alpha software. You will need to install the following components: - Tomcat 3.1 from jakarta.apache.org; - Xerces 1.0.3 from xml.apache.org; - IBM's SOAP for Java 1.1 from. The FutureSOAP is the second generation of XML-based remote procedure call (the first generation was XML-RPC), but it is unlikely to be the last generation. Indeed, SOAP was submitted to the IETF and the W3C for further standardization. This process will ultimately deliver a new specification that, if history is any judge, might end up being incompatible with SOAP. Regardless of the evolution of SOAP, there is definitively a role for XML-based remote procedure call. About the Author Benoît Marchal is a software engineer and writer who has been working extensively in Java and XML. He is the author of the book XML by Example and has his own business, Pineapplesoft, in Namur, Belgium. He is currently working on a new book.
http://www.developer.com/net/vb/article.php/626491/Java-Meets-SOAP.htm
CC-MAIN-2016-07
refinedweb
850
57.67
<![CDATA[Tech Opener]]> 2014-02-13T18:54:37-08:00 Octopress <![CDATA[Now using Octopress]]> 2012-01-06T16:18:00-08:00 <p>Nothing like migrating to a new blogging platform to get you in the mood to write some new posts. Just switched from Wordpress to <a href="">Octopress</a>.</p> <p>You can find migration instructions a number of places, but the process was pretty straightforward for me.</p> <ul> <li>Exported published posts from Wordpress</li> <li>Updated xml export to include atom namespace that was missing</li> <li>Used <a href="">exitwp</a> to convert the export into the markdown format. I did run into a <a href="">wrapping issue</a>.</li> <li>Enabled comments on old posts with the following find and replace</li> </ul> <pre><code> perl -pi -e 's/layout: post/layout: post\ncomments: true/g' *.markdown </code></pre> <ul> <li>Saved images to source/images and updated posts with proper links</li> <li>Deploy to github!</li> <li>Update feedburner RSS feed location</li> </ul> <p>Now I just need to find a spell checker plugin!</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Using the Dwolla API with node.js]]> 2011-12-02T10:55:52-08:00 <p><a href="">Dwolla.com</a> is a new payment network. It makes it easy to transfer money without the transaction fees charged by credit cards. Each transaction over $10 is 25 cents, and those under $10 are free. I think this has a lot of potential so I have been exploring ways to utilize their API.</p> <p>To start I wrote a node.js module for their API that you can find at <a href=""></a>. In addition, I added Dwolla OAuth2 to the <a href="">everyauth</a> module to make it easy to authenticate.</p> <p>They have some interesting API methods that are not common to payment APIs. You can view a user's account transactions and balances (with permission of course). They also integrate and expose a user's contacts from various social networks, such as Facebook and Twitter, to make it easy to send/request money from friends.</p> <p>Let me know if you build something cool or if you have a great idea that could utilize their API.</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Translation API for node.js]]> 2011-11-17T14:24:20-08:00 <p>Microsoft provides a Translator API that allows you to translate text from one language into another. It provides up to 1000 transactions/month for free. Google also provides a translation API, however has recently removed their free tier. One the projects I am working on needed the ability to translate text, so I wrote a node.js module for the Microsoft Translator API, which you can find more about at <a href="">github.com/nanek/mstranslator</a>.</p> <p>The API itself provides a good set of languages to choose from and it also can provide the audio of the word being spoken.</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Credit Cards and Security]]> 2011-07-07T08:04:54-07:00 <p>I recently returned from a wonderful trip to Norway. One tech thing that stood out was that everywhere you go there they have portable card readers that read cards with a chip or magnetic stripe. Looking into it, the "chip" is <a href="">EMV</a> technology adopted in Europe in 2005 due to security concerns. Every single place I tried to use my non-chip credit or debit card came with a puzzled look and the statement, "no chip?!" Being a tech geek I definitely felt out of date. You could tell by the way they acted that they didn't swipe cards very often, as everyone only uses the chip there.</p> <p>I remember when I applied for my first credit card, the American Express Blue card, which I still have. It came with a USB card reader and a chip in the card to help secure online transactions. I never used the card reader, but it was the main reason I got the card, and that was back in 1999. Unfortunately that is not an EMV chip, so it doesn't work in Europe.</p> <p>Swipe cards, just like plain text account numbers lack any sort of security. This is widely known, however we currently have a chicken/egg problem of not many cards with chips and not many readers for these chips in the US. <a href="">Square</a> and other companies are making card readers more accessible, however is still based upon fundamentally insecure swipe card technology. Some say mobile payments, such as <a href="">NFC</a> will provide a more secure technology and are more practical to deploy in the US over EMV technology.</p> <p>Frankly, I don't care too much what technology is used, however I would prefer the option to choose a more secure credit/debit card. Seems like there shouldn't be an issue supporting both. Recently I just go a new ING Direct MasterCard, that has no embossed numbers on the card. In fact, all of the account information such as my name and account number and expiration are printed on the back. It certainly looks cool, albeit almost fake, and it won't leave my CC number imprinted in my wallet, however im not sure it makes it my account any more secure. I guess they decided that no one makes card imprints anymore.</p> <p>Im looking forward to see some innovation in banking over the next year. Seems like the market is poised for a shake-up.</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Book recommendation: Responsive Web Design]]> 2011-07-06T10:56:30-07:00 <p>I just finished <a href="">Responsive Web Design</a> by Ethan Marcotte. It is a quick and entertaining read. It brings together some CSS techniques you may already know and some you probably don't to give clear solution to an ever increasing problem of dealing with varying screen sizes. I look forward to using these strategies in my next project and I highly recommend the book. Let me know if you want to borrow it.</p> <img src="" height="1" width="1" alt=""/> <![CDATA[How to become a Sole Proprietor in Arlington County]]> 2011-07-05T12:33:36-07:00 <p>When starting out on your own, there a number of things you need to do based on where you live. Even with all of the resources on the internet, it can still be a little confusing to determine what is needed as it varies based on a number of factors. As such, if you are starting a business, then be sure to research what is required for your situation.</p> <p>Here are the basic steps for becoming a sole proprietor in Arlington County, Virginia.</p> <ol> <li> County - Business License ($30/fee, plus tax at end of year) from the Commissioner of Revenue</li> <li> County - Home occupation permit (free) from the Commissioner of Revenue</li> <li> File State Taxes at end of year</li> <li><p> File Federal Taxes at end of year and complete tax estimates quarterly Other steps, highly recommended:</p></li> <li><p>New bank account to separate business income/expenses from personal accounts</p></li> <li>Business Cards - <a href="">about.me</a> provides free <a href="">moo</a> cards</li> <li>Health Insurance - <a href="">eHealthInsurance.com</a></li> <li>Networking - <a href="">meetup.com</a> After this, you can look into creating a more complex business type, such as an LLC and/or trademarking a business name and getting an <a href="">EIN</a> if needed. However if you are just looking to get started, it could be a simple as that. Let me know if you think im missing something.</li> </ol> <img src="" height="1" width="1" alt=""/> <![CDATA[Full Text Search with Dropbox]]> 2011-04-25T18:58:20-07:00 <p><a href="">Dropbox</a> + <a href="">Solr</a> = full text indexing and search for files in your Dropbox. I wrote an app in <a href="">Sinatra</a> that authenticates to Dropbox, downloads your files, and indexes them in Solr. It also provides a simple interface for searching that includes hit highlighting and some basic facet support.</p> <p><a href="/images/searchdropbox.png"><img src="/images/searchdropbox.png" alt="Search Dropbox" /></a></p> <p>I've posted the project on <a href="">github</a>, so feel free to download and try it. For anyone interested in this as a hosted service instead of as a download and install, let me know.</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Analyzing data from DonorsChoose.org]]> 2011-04-14T12:28:38-07:00 <p>DonorsChoose.org is running a <a href="">contest</a> by opening up its data for analysis and use in innovative applications. They have provided data dumps for project, search, donation and gift card data in large csv files. There are a two free tools that I recommend to quickly review this data.</p> <p><a href="">Google Refine</a> allows you to filter the data and identify data quality issues. It also makes it very easy to manipulate and transform the data any way you like. Bulk replacements and column transforms are two of its strengths. Another cool feature is the ability to template exports into different formats such as JSON. Heres some tips I found with working with the Donors Choose data. First increase the <a href="">memory settings</a>. Second, update the <a href="">facet limit setting</a> to something higher. The <a href="">screencasts</a> for Google Refine do a great job in demonstrating its use.</p> <p><a href="">Google Fusion Tables</a> is good for visualizing data in various ways like charts, maps, or timelines. This tool works better with data sets that are already cleaned up. It takes some time to load the data and process it, so it is best served for working with just a slice of data that you would like to present for a specific purpose. It does have a 250mb limit per user and a 100mb limit per csv file.</p> <p>So go ahead and start analyzing this data. It is for a good cause and the lucky contest winner will get to meet Steven Colbert!</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Team Drive on Google App Engine]]> 2011-04-11T16:11:46-07:00 <p>Last year, I created <a href="">Team Drive</a> on <a href="">Google App Engine</a>. I wanted to learn about Google App Engine (GAE) which is a hosting platform for python/java based applications.</p> <p>Team Drive is based on a site that Fabien built years ago to record donations of items for a charity food drive. Users from an organization are split into separate teams, and then compete to see who can collect the most food items. By adding this friendly team competition to a normal food drive, you can increase the participation and results of the drive.</p> <p>Building on GAE is quite different than traditional single server application deployments. Everything in App Engine forces you to think about how to scale your application. By placing constraints, such as a thirty second processing limit per request, it forces you to think about approaching problems differently than if you were writing this to run on a single server.</p> <p>App Engine supports two types of authentication methods, Google Accounts and OpenID. If you want to leverage their session management you need to use one of these. For an site aimed at organizations, I didn't want users to have to create a google account or OpenID. To work around this I implemented an OpenID provider in the application. Administrators could upload a list of email addresses and a Team Drive OpenID would be created for each of these users. The users themselves don't need to know that they are using OpenID, as I only ask for their username and password.</p> <p>Another example is for counting the number of items contributed by a person, team, organization or type. In a relational database you might just sum these up on demand. However using the Google datastore you generally store counts on the object itself and increment this count on each update. App Engine has also provided an implementation of map/reduce that makes it easy to perform operations such as sums or counts over large collections.</p> <img src="" height="1" width="1" alt=""/> <![CDATA[No timezones / no daylight savings time]]> 2011-04-01T13:49:30-07:00 <p>Timezones and daylight savings time never really made sense to me. How could something as fundamental, precise and constant as time be dependent upon my location or a local government?</p> <p><img src='/images/SwatchBeat1.jpg' width='263px' height='300px' /></p> <p>Turns out, <a href="">Swatch</a> tried to tackle this already. <a href="">eBeats</a> is trying something similar. Until then, there is always <a href="">Every Time Zone</a>.</p> <p>&nbsp_place_holder;</p> <img src="" height="1" width="1" alt=""/> <![CDATA[A location based URL redirector]]> 2011-03-31T11:33:40-07:00 <p>I wanted to create something to enter into <a href="">Quova Dev Challenge</a>, so I created <a href="">Nearby Link</a>. Basically its a service that creates links that redirect users to different sites based on their current location.</p> <p>If that doesn't make sense, then just visit <a href=""></a> and you will be taken to the contact form for the governor of your state. If a user in another state clicked the same link, they would visit the appropriate contact form for their state. Get it? One link, yet it can redirect to different sites based on the location of the user.</p> <p>Or instead, let's say your trying to get people to eat at your restaurant by using social media like twitter or facebook, and you want them quickly find a store location in their area. Quizno's for example, could just link to to <a href=""></a> and it will automatically show locations around the user where they are at.</p> <p>Thoughts? Other uses?</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Location history reporting]]> 2011-03-07T11:20:54-08:00 <p>There are lots of mobile location sharing products and many new ones everyday. Most of them appear to be centered around location check-ins and sharing with friends. While this is neat, it seems like only a small slice of the use cases in which location data is useful.</p> <p>For example, lets say that I take I-66 W to work everyday, starting around 9am. If this pattern is established, and there is an accident on I-66 W at 8:50am, it would be great to know that before I start my commute. The location and time of this event is important in that if it was another road or at another time, then I really don't care to be informed regarding this event. Unless the event was at 9:30am and im running late. In order to provide context aware alerts, you need to have sufficient data in order to have a good level of confidence that a user is likely to take an action at a certain time and place.</p> <p>Certainly there are existing ways to be informed regarding traffic situations. However, it seems to me that we have not taken automation regarding similar use cases yet to a usable level. Smart phones that are aways on, full of sensors and generally always with us, empower us to easily track, record, analyze and alert with minimal or no input. I've started to explore how to implement this and I hope to discuss it more over the next few days.</p> <p>&nbsp_place_holder;</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Online password security]]> 2011-03-03T16:22:42-08:00 <p>I often find myself forgetting my passwords and usernames to various sites. So recently, I decided to get serious about password management. I use <a href="">KeyPassX</a> (or KeyPass if you are using windows) as a secure way to encrypt and record the urls, usernames and passwords to sites.</p> <p>I also signed up for <a href="">Google 2 step verification</a>. This is useful for many reasons, but one in particular is that your gmail account contains a lot of information that can be used to access your other accounts. Once you get past the initial setup, everything works seamlessly as it did before. Enterprises have traditionally paid big bucks to implement this type of 2 factor authentication, typically requiring issuing RSA tokens or similar to all employees. It's great to see a more integrated solution being provided directly to consumers.</p> <p><a href="">Dropbox</a> has nothing to do with your password security, however it is a great tool to sync files between your computer, web, and devices. So one way to always be sure that you don't lose your KeyPass database or your Google verification backup codes is to place them in a private dropbox folder that you can reach from everywhere.</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Smartphone with unlimited everything for $25/month]]> 2011-03-02T10:37:12-08:00 <p>Virgin Mobile offers a great $25/month plan for unlimited data, text and web with 300 talk minutes with no contract to sign. This works great for me, as I generally just have short phone conversations. However there are of course times when I might get stuck on the phone for an hour or so. Below are a few extra steps I took to help get around the 300 minute limit without spending any more.</p> <p>First, I ported my number to <a href="">Google Voice</a>(GV). GV has a lot of features, but the key feature is being able to indicate where to forward calls to when your phone number is dialed. For example, when my GV number is called, it is then forwarded to my mobile phone number.</p> <p>Secondly, I setup GV to forward to Google Talk within Gmail. Im often in front of a computer, so this way I can easily make and receive phone calls for free without using my cell minutes or using a different phone number.</p> <p>Lastly, to take it the extra mile, what about a VOIP call when you are on your cell phone in order to avoid using your minutes? Might as well use that unlimited data plan. Turns out that there are a few extra steps here, however it is relatively easy to setup. I use a <a href="">Gizmo5</a> SIP account for this and I won't go into the details here, but there are <a href="">plenty</a> of <a href="">posts</a> on the web describing how to set this up. Keep in mind though that the call quality of this often does suffer based on the quality of the data connection.</p> <p>If you sign up for a <a href="">Virgin Mobile</a> account, feel free to use the Kickback Code IYFUMN7I for an extra 60 minutes of talk time.</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Redmine plugin for windows authentication]]> 2010-05-02T19:36:16-07:00 <p>Redmine.org is an open source project management application. It is simple to setup and works great. It supports LDAP authentication out of the box. We recently setup Redmine for a project to run behind IIS using fastcgi and wanted to automatically login using windows authentication. We didn't see a option for this, so I created a simple plugin that can be used to add this functionality.</p> <p></p> <img src="" height="1" width="1" alt=""/> <![CDATA[iPad apps]]> 2010-04-02T08:35:36-07:00 <p>Prepared for tomorrow by downloading some iPad applications before the device has even been released. Apple = Hype machine. iPad will win for the same reasons the iPhone did. For anyone not paying attention, it is the applications.</p> <p><a href="/images/iPadApps.png"><img src="/images/iPadApps.png" alt="iPad Apps" /></a></p> <img src="" height="1" width="1" alt=""/> <![CDATA[CloudCamp DC 2010]]> 2010-03-25T22:58:21-07:00 <p>Last Tuesday, I attended <a href="">CloudCamp</a> in DC. I've been meaning to go to an event like this for sometime and I was finally able to make it. In particular my main takeaway from this event was how much better an unconference format is over a traditional conference.</p> <p>This CloudCamp was ran by <a href="">Dave Nielsen</a>. There were over 200 people at my count, with standing room only at the beginning of the event. I had my concerns with how effective the event would be based on its format with such a diverse and large audience. However it was quite successful. The audience members varied widely, from cloud vendors and consultants to government employees with no knowledge of the cloud and to those with existing or future cloud projects.</p> <p>The event started with lightning talks, followed by a panel from the audience with questions from the crowd, followed by two audience lead break out sessions, ending with a wrap-up over drinks.</p> <p>The best part about the event was that it was able to live up to the definition of an unconference. Instead of going to a typical conference and hearing long presentations from just a few people, we were all able to participate, share experiences and learn from each other. I look forward to attending the next CloudCamp and other unconference events.</p> <img src="" height="1" width="1" alt=""/> <![CDATA[Foursquare on Windows Mobile]]> 2009-12-22T21:47:50-08:00 <p><a href="">Foursquare </a>does not have a windows mobile version of their application, so I thought it would be a great opportunity to try and build an app.</p> <p>Things that are working fairly well:</p> <ul> <li>Foursquare API access.</li> <li>JSON.NET is used to parse the JSON responses.</li> <li>sqlite is used for caching http responses.</li> <li>OAuth is used for authentication to foursquare.</li> <li><p>GPS lookup. Things that don't work and have proved difficult to implement:</p></li> <li><p>Responsiveness. At times the app stops responding and overall feels too slow for normal use.</p></li> <li>Cell ID lookup. This is important as GPS often does not work indoors. It appears access to this API may be protected on most phones.</li> <li><p>Good looking user interface. Plus dealing with different phone resolutions, orientations, and sizes makes it a little more complicated. Things that would be interesting to implement but require a solid base application:</p></li> <li><p>Map integration</p></li> <li>Integration with other API's such as Yelp You can find the source at <a href=""></a> along with a CAB for installation on your phone if you want to try it out. Look under the planned download section. It works ok on my HTC Touch Pro. If you are interested in contributing to this effort, let me know. I'm debating spending more time on making this work better or building a HTML5 based mobile web application.</li> </ul> <img src="" height="1" width="1" alt=""/> <![CDATA[Life Inc. call to action]]> 2009-10-20T09:07:21-07:00 <p>I recently completed the book, "<a href="">Life Inc.</a> How the world became a corporation and how to take it back," by <a href="">Douglas Rushkoff</a>.</p> <p><img alt='RUSHKOFF_LifeIncCOVER' src='/images/RUSHKOFF_LifeIncCOVER.jpg' width='197px' height='300px' /></p> <p>The book tells the compelling history of how corporations have defined and controlled the world since their inception. It might make you rethink some basic assumptions we have about how society has evolved the way that it has. One example used in the book is the concept of having a large suburban home while working in the city, being constructed by car companies to create a market and the need for cars. He ends the book with a call to action, specifically mentioning creating local currencies and using Community Supported Agriculture. I've considered trying a <a href="">CSA</a> that would deliver to Arlington, but I don't really cook that much. He also mentions <a href="">Kiva.org</a> which <a href="">I use and enjoy</a>.</p> <p>Do you use a CSA?</p> <img src="" height="1" width="1" alt=""/> <![CDATA[5 Great Microsoft .NET Developer Blogs]]> 2009-10-19T08:42:32-07:00 <p>Scott Hanselman <a href=""></a> Dan Wahlin <a href=""></a> The Morning Brew <a href=""></a> Jon Galloway <a href=""></a> Scott Gu <a href=""></a></p> <p>I'm sure I missed a bunch. What do you recommend?</p> <img src="" height="1" width="1" alt=""/>
http://feeds.feedburner.com/TechOpener
CC-MAIN-2017-43
refinedweb
4,233
64.1
Discussion in 'HTML' started by Luc, Dec 24, 2003. Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum. - Similar Threads Re: Sending mail to multiple addressesRené de Leeuw, Jul 22, 2003, in forum: ASP .Net - Replies: - 0 - Views: - 356 - René de Leeuw - Jul 22, 2003 SMTP: different mail from and from addresses?Max Metral, Oct 25, 2004, in forum: ASP .Net - Replies: - 3 - Views: - 458 - Steven Cheng[MSFT] - Oct 27, 2004 Physical Addresses VS. Logical Addressesnamespace1, Nov 29, 2006, in forum: C++ - Replies: - 3 - Views: - 875 /robots.txt at end of URL?Les Caudle, Jul 20, 2007, in forum: ASP .Net - Replies: - 4 - Views: - 418 - Walter Wang [MSFT] - Jul 22, 2007 meta robots and robots txtTim w, May 22, 2014, in forum: HTML - Replies: - 1 - Views: - 87 - se - May 22, 2014
http://www.thecodingforums.com/threads/e-mail-addresses-end-robots.156364/
CC-MAIN-2014-23
refinedweb
166
83.36
05 October 2012 17:04 [Source: ICIS news] WASHINGTON (ICIS)--The ?xml:namespace> In its monthly report on employment, the department said that the chemicals industry workforce rose to 799,600 last month from the August level of 798,000, a gain of 0.2%. The chemicals sector workforce is 0.7% larger than September last year when it measured 794,200, according to the department. While jobs in the plastics and rubber industry declined marginally in September, the sector’s workforce was essentially flat with August at 648,500. In addition, the nation’s plastics and rubber firms have seen fairly robust employment growth over the last 12 months, according to the department, with the sector’s labour force higher by 11,400 jobs compared with September 2011, a gain of 1.8%. The increase in chemical sector jobs was part of
http://www.icis.com/Articles/2012/10/05/9601619/us-chemical-sector-jobs-gain-in-sep-while-plastics-workers-decline.html
CC-MAIN-2014-42
refinedweb
143
61.26
The Attach API By John O'Conner on Aug 23, 2007 by John Zukowski When working with the Java platform, you typically program with the standard java.\* and javax.\* libraries. However, those aren't the only things that are provided for you with Sun's Java Development Kit (JDK). Several additional APIs are provided in a tools.jar file, found in the lib directory under your JDK installation directory. You'll find support for extending the javadoc tool and an API called the Attach API. As the name may imply, the Attach API allows you to attach to a target virtual machine (VM). By attaching to another VM, you can monitor what's going on and potentially detect problems before they happen. The Attach API classes are found in the com.sun.tools.attach and com.sun.tools.attach.spi packages, though you'll typically never directly use the com.sun.tools.attach.spi classes. Even including the one class in the .spi package that you won't use, the whole API includes a total of seven classes. Of that, three are exception classes and one a permission. That doesn't leave much to VirtualMachine and its associated VirtualMachineDescriptor class. The VirtualMachine class represents a specific Java virtual machine (JVM) instance. You connect to a JVM by providing the VirtualMachine class with the process id, and then you load a management agent to do your customized behavior: VirtualMachine vm = VirtualMachine.attach (processid); String agent = ... vm.loadAgent(agent); The other manner of acquiring a VirtualMachine is to ask for the list of virtual machines known to the system, and then pick the specific one you are interested in, typically by name: String name = ... List vms = VirtualMachine.list(); for (VirtualMachineDescriptor vmd: vms) { if (vmd.displayName().equals(name)) { VirtualMachine vm = VirtualMachine.attach(vmd.id()); String agent = ... vm.loadAgent(agent); // ... } } Before looking into what you can do with the agent, there are two other things you'll need to consider. First, the loadAgent method has an optional second argument to pass settings into the agent. As there is only a single argument here to potentially pass multiple options, multiple arguments get passed in as a comma-separated list: vm.loadAgent (agent, "a=1,b=2,c=3"); The agent would then split them out with code similar to the following, assuming the arguments are passed into the agent's args variable. String options[] = args.split(","); for (String option: options) System.out.println(option); } The second thing to mention is how to detach the current virtual machine from the target virtual machine. That's done via the detach method. After you load the agent with loadAgent, you should call the detach method. A JMX agent exists in the management-agent.jar file that comes with the JDK. Found in the same directory as tools.jar, the JMX management agent allows you to start the remote JMX agent's MBean Server and get an MBeanServerConnection to that server. And, with that, you can list things like threads in the remote virtual machine. The following program does just that. First, it attaches to the identified virtual machine. It then looks for a running remote JMX server and starts one if not already started. The management-agent.jar file is specified by finding the java.home of the remote virtual machine, not necessarily the local one. Once connected, the MBeanServerConnection is acquired, from which you query the ManagementFactory for things like threads or ThreadMXBean as the case may be. Lastly, a list of thread names and their states are displayed.()); } } } } To compile this program, you need to make sure you include tools.jar in your CLASSPATH. Assuming JAVA_HOME is set to the Java SE 6 installation directory, of which the Attach API is a part, the following line will compile your program: > javac -cp %JAVA_HOME%/lib/tools.jar Threads.java From here, you could run the program, but there is nothing to attach to. So, here's a simple Swing program that displays a frame. Nothing fancy, just something to list some thread names you might recognize.); } } Run the MyFrame program in one window and be prepared to run the Threads program in another. Make sure they share the same runtime location so the system can connect to the remote virtual machine. Launch MyFrame with the typical startup command: > java MyFrame Then, you need to find out the process of the running application. That's where the jps command comes in handy. It will list the process ids for all virtual machines started for the JDK installation directory you are using. Your output, specifically the process ids, will probably be different: > jps 5156 Jps 4276 MyFrame Since the jps command is itself a Java program, it shows up in the list, too. Here, 4276 is what is needed to pass into the Threads program. Your id will most likely be different. Running Threads then dumps the list of running threads: > You can use the JMX management agent to do much more than just list threads. For instance, you can call the findDeadlockedThreads method of ThreadMXBean to find deadlocked threads. Creating your own agent is actually rather simple. Similar to how applications require a main method, agents have an agentMain method. This isn't a part of any interface. The system just knows to look for one with the right argument set as parameters. import java.lang.instrument.\*; public class SecretAgent { public static void agentmain(String agentArgs, Instrumentation instrumentation) { // ... } } To use the agent, you must then package the compiled class file into a JAR file and specify the Agent-Class in the manifest: Agent-Class: SecretAgent The main method of your program then becomes a little shorter than the original Threads program since you don't have to connect to the remote JMX connector. Just be sure to change the JAR file reference there to use your newly packaged agent. Then, when you run the SecretAgent program, it will run the agentmain method right at startup, even before the application's main method is called. Like Applet, there are other magically named methods for doing things that are not part of any interface. Use the Threads program to monitor more virtual machines and try to get some threads to deadlock to show how you can still communicate with the blocked virtual machine. See the Attach API documentation for more information. Consider also reading up on the Java Virtual Machine Tool Interface (JVM TI). It requires the use of the Attach API. This comment is related to an older blog posting at You might want to check out where some "blogger" ripped off the article and posted it as his/her own. This has been reported to Google (aka blogspot.com, aka blogger.com) but they apparently don't care. Maybe a friendly reminder from a Sun corporate lawyer would gets Google's attention. Posted by Frauke Stommel on August 23, 2007 at 04:45 AM PDT # The source line Set mbeans = mbsc.queryNames(objName, null); should declare the type as Set<ObjectName> not a raw Set. This might be an html formatting issue rather than a coding issue tho'. Posted by Bruce Chapman on August 26, 2007 at 09:40 AM PDT # Bruce, good catch. You are right...it was an html formatting issue. Changing the embedded less-than and greater-than characters to character references helped. Posted by John O'Conner on August 27, 2007 at 04:21 AM PDT # This article explains how you can the Attach API in JDK6.0 Posted by Tarek Yassin on August 27, 2007 at 08:10 AM PDT # Good One Posted by J6 on August 27, 2007 at 08:17 AM PDT #
https://blogs.oracle.com/CoreJavaTechTips/entry/the_attach_api
CC-MAIN-2015-11
refinedweb
1,281
65.83
Voronoi Diagrams Back in Creating Gradients Programmatically in Python I presented some code for writing out PNGs according to some rgb-function of x and y. The relevant write_png(filename, width, height, rgb_func) is here: This enables one to quickly generate PNGs based on all sorts of functions of position. For example, here's a Voronoi diagram: Take any metric space and pick a discrete number of points in that space we'll designate "control points" (the black dots in the above example). Now colour each other point in the space based on which control point is closest. In other words, two points are the same colour if and only if they have the same "closest control point". Here's how to generate such a diagram using write_png... First of all, here's a function that given an (x, y) coordinate and a list of control points, returns a pair of: - which control point is the closest to (x, y) - what the distance was def closest(x, y, control_points): closest = None distance = None for i, pt in enumerate(control_points): px, py = pt d = ((px - x) ** 2 + (py - y) ** 2) if d == 0: return i, 0 if d < distance or not distance: closest = i distance = d return closest, distance Now we can use this and write_png to generate a PNG Voronoi diagram for a given set of control points: def voronoi(filename, size, control_points): def f(x, y): c, d = closest(x, y, control_points) # draw points in black if d < 5: return 0, 0, 0 px, py = control_points[c] # just one way to generate a colour m = px * 255 / size n = py * 255 / size return m, 255 - ((m + n) / 2), n write_png(filename, size, size, f) Of course, this is just a brute-force way of establishing the Voronoi diagram, but for just generating examples a few hundred points by a few hundred points, it's Good Enough. Note the choice of colouring, based on the coordinates of the control point is just one of many possibilities. You could also just colour based on control_point number (i.e. c) The current approach has one disadvantage that two control points very close to one another can be given almost indistinguishable colours. The example diagram was just randomly generated with the following code: import random from voronoi import voronoi space_size = 200 num_control = 8 control_points = [] for i in range(num_control): x = random.randrange(space_size) y = random.randrange(space_size) control_points.append((x, y)) voronoi("voronoi.png", space_size, control_points) You can read more about Voronoi diagrams on Wikipedia. Syndicated 2008-11-07 20:33:58 (Updated 2008-11-07 20:57:34) from James Tauber's Blog
http://www.advogato.org/person/jtauber/diary.html?start=200
CC-MAIN-2016-30
refinedweb
441
52.43
Custom action config fileblep May 27, 2008 5:20 AM Hi! I'm actually trying to make my own custom action but it needs several configuration files to startup, so consider the following esb archive file schema: / - META-INF | |______ jboss-esb.xml | |______ deployment.xml |__ mypackage/MyCustomAction |__ cfg |__ cfg1.xml |__ cfg2.xml and in the jboss-esb.xml file : [...] <action name="myAction" class="mypackage.MyCustomAction"> <property name="config1" value="/cfg/cfg1.xml" /> <property name="config2" value="/cfg/cfg2.xml" /> </action> [...] I can get the attributes from the config tree object during initialization but I'm not actually able to open these files to access content. Thanks for help! 1. Re: Custom action config fileTom Fennelly May 27, 2008 5:30 AM (in response to blep) How are you trying to open these resource? Does the actual .esb deployment contain these cfg resource in the location you identified? 2. Re: Custom action config fileblep May 27, 2008 5:44 AM (in response to blep) Yes I try : of course, if I open a stream with "/cfg/cfg1.xml" as , it attempts to open a file in c:/cfg/cfg1.xml and if I try to get it from resources loaded by the context class loader, it returns a null object. I checked with an archive manager, the directory and the files are there. 3. Re: Custom action config fileTom Fennelly May 27, 2008 6:00 AM (in response to blep) Please show us the actual code you're using to open a stream to the resource. 4. Re: Custom action config fileblep May 27, 2008 7:38 AM (in response to blep) My custom action is : public class WrapSxmlESB extends AbstractActionLifecycle{ [...] //constructor public WrapSxmlESB(ConfigTree cfg) throws Exception{ log.info("Entering WrapSxmlESB"); resourcesHref = cfg.getAttribute("resourceRef"); log.info("configHref = " + configHref); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(configHref); try{ log.info("available : " + is.available()); }catch (NullPointerException e) { log.info("Is null by context class loader!!!!!"); } try{ is = new FileInputStream(configHref); log.info("available : " + is.available()); }catch (FileNotFoundException e) { log.info("File not found by input stream!!!!!"); } log.info("Outing WrapSxmlESB"); } [...] My jboss-esb.xml contains: [...] <action name="action2" class="com.thales.poc.servingxml.WrapSxmlESB"> <property name="resourceRef" value="/cfg/fic-resource.xml"/> <property name="configRef" value="/cfg/servingxml.xml"/> </action> [...] The ESB archive : $ jar tf embed_servingxml.esb | grep cfg cfg/ cfg/FIC00002.txt cfg/fic-resource.xml cfg/out.xml cfg/servingxml.xml The JBoss logs during deployment : 13:23:44,682 INFO [JBoss4ESBDeployer] create esb service, embed_servingxml.esb 13:23:44,776 INFO [embed_servingxml] Bound to JNDI name: queue/embed_servingxml 13:23:44,823 WARN [ScheduleMapper] Attrubute 'poll-frequency-seconds' is DEPRECATED. Please change your configuration to use 'schedule-frequency'. 13:23:44,823 INFO [AbstractFileGateway] No value specified for: max-millis-for-response - This will be an 'inbound-only' gateway 13:23:44,854 INFO [WrapSxmlESB] Entering WrapSxmlESB 13:23:44,854 INFO [WrapSxmlESB] configHref = /cfg/servingxml.xml 13:23:44,854 INFO [WrapSxmlESB] Is null by context class loader!!!!! 13:23:44,854 INFO [WrapSxmlESB] File not found by input stream!!!!! 13:23:44,854 INFO [WrapSxmlESB] Outing WrapSxmlESB I'm quite sure it's a newbie issue! 5. Re: Custom action config fileTom Fennelly May 27, 2008 7:49 AM (in response to blep) Could be a scoping issue. Kev? Have you tried using the class classloader i.e. just doing 'getClass().getResourceAsStream("/cfg/servingxml.xml")'? 6. Re: Custom action config fileblep May 27, 2008 8:11 AM (in response to blep) It works!! Why did I look for a complex way instead of using a simple one?? Thank you very much for your help. 7. Re: Custom action config fileKevin Conner May 27, 2008 9:54 AM (in response to blep) It shouldn't have been a scoping issue as the context classloader would have been initialised before the lifecycle was created. Could you wrap this into a simple testcase and send it to me? I would like to understand what is going on. 8. Re: Custom action config fileKevin Conner May 29, 2008 3:29 PM (in response to blep) Sorry, should have spotted the reason for this. When asking a classloader for a resource it should not start with a leading '/'. If you change your resource from /cfg/servingxml.xml to cfg/servingxml.xml then it will work correctly with the context classloader. 9. Re: Custom action config fileblep May 30, 2008 7:29 AM (in response to blep) I just tried with the test case I sent you and it's exactly the same. FYI 10. Re: Custom action config fileKevin Conner May 30, 2008 7:45 AM (in response to blep) Your test case had a bug in it, it was using the wrong method from Classloader. You need to change the method to use getResourceAsStream instead of getSystemResourceAsStream. The code you pasted here was correct though. 11. Re: Custom action config fileblep May 30, 2008 8:18 AM (in response to blep) Right, I just checked. Sorry for that!
https://developer.jboss.org/thread/143773
CC-MAIN-2018-51
refinedweb
842
59.8
43501/how-to-use-python-scripts-in-query-editor I am trying to create Python visuals with the help of Python-Scripts. I have installed Python on my local computer and python visualization option is also available in the visualization pane in Power BI Desktop but these are the challenges I am facing: 1. I am not able to edit Queries 2. It is asking for permissions and security 3. Run Scripts option is not available How do I create Python visuals using Python Scripts? Hi, In order to use Python Visuals you need to first install Python( Anaconda or Python Version 3.5) and enable it in Power BI Desktop Follow these steps to use Python Visuals in Query Editor: Step 1: • Load your data into Power BI Desktop • Get Data > CSV from the Home ribbon in Power BI Desktop Step 2: Select the file and select Open, and the CSV is displayed in the CSV file dialog. Step 3: Once the data is loaded, you'll see it in the Fields pane in Power BI Desktop. Step 4: Open Query Editor by selecting Edit Queries from the Home tab in Power BI Desktop. Step 5: In the Transform tab, select Run Python Script and the Run Python Script editor appears Step 6: Enter your Python Script in the R Script Editor Note: You'll need to have the pandas library installed in your Python environment for the previous script code to work properly. To install pandas, run the following command in your Python installation: | > pip install pandas import pandas as pd completedData = dataset.fillna(method='backfill', inplace=False) dataset["completedValues"] = completedData["SMI missing values"] Step 7: After selecting OK, Query Editor displays a warning about data privacy. Step 8: For the Python scripts to work properly in the Power BI service, all data sources need to be set to public. Now you can finally create your own visualizations depending upon your dataset. Hope This Helps!! Hi Nithin, To fill or replace the null or ...READ MORE Hi, To create a custom column, we need to ...READ MORE Hi, There are the steps which you can ...READ MORE Can someone explain the steps how can ...READ MORE Hi, You can create interactive reports out of ...READ MORE Follow the below procedure - 1. Install ...READ MORE Hey, To create a doughnut chart in Power ...READ MORE Hi I have an existing power query created ...READ MORE Hi, There are a lot of packages available ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/43501/how-to-use-python-scripts-in-query-editor?show=43503
CC-MAIN-2020-10
refinedweb
423
63.49
XOR Operator in Java XOR is a bitwise operator and, it works by comparing individual bits of the operands. XOR stands for eXclusive OR and, it returns true if and only if the two bits being compared are not the same. The following truth table explains the output of the XOR operation. Remember that in binary 1 stands for true and 0 stands for false. XOR can also be written in terms of other basic operators like AND, OR, and NOT. A XOR B is equivalent to (A AND (NOT B)) OR (B AND (NOT A)). We can write XOR in this way because at any instant either A should be True and B should be False, or A should be False and B should be True. Example: XOR in Java In Java, the XOR operator is represented by the caret symbol(^). It can be used on any primitive data type. Let's try to verify the truth table of XOR using this operator. public static void main(String[] args) { System.out.println("0 XOR 0: " + (0 ^ 0)); System.out.println("0 XOR 1: " + (0 ^ 1)); System.out.println("1 XOR 0: " + (1 ^ 0)); System.out.print("1 XOR 1: " + (1 ^ 1)); } 0 XOR 0: 0 0 XOR 1: 1 1 XOR 0: 1 1 XOR 1: 0 Example: XOR with Boolean Values XOR can also work on boolean values. Let's try to recreate the table using boolean true and false. public static void main(String[] args) { System.out.println("False XOR False: " + (false ^ false)); System.out.println("False XOR True: " + (false ^ true)); System.out.println("True XOR False: " + (true ^ false)); System.out.print("True XOR True: " + (true ^ true)); } False XOR False: false False XOR True: true True XOR False: true True XOR True: false Example: XOR with Integer Values in Java XOR operator can be used on integers that are not 0 or 1. The XOR operator will work on the individual bits of the binary equivalent of the integer. For example, if 9 is XORed with 15, then the XOR operator will be applied on the individual bits of the two numbers(1001 for 9 and 1111 for 15). public static void main(String[] args) { System.out.println("9 XOR 15: " + (9 ^ 15));//1001 XOR 1111 = 0110 System.out.println("1 XOR 20: " + (1 ^ 20));//00001 XOR 10100 = 10101 System.out.println("7 XOR 7: " + (7 ^ 7));//0111 XOR 0111 = 0000 System.out.print("32 XOR 0: " + (32 ^ 0));//100000 XOR 000000 = 100000 } 9 XOR 15: 6 1 XOR 20: 21 7 XOR 7: 0 32 XOR 0: 32 XOR of Binary Strings XOR only works for primitive data types. However, we can write our own method that uses the XOR operator and some additional logic to find the XOR of two binary strings. We will simply loop through each character of both strings simultaneously and use the XOR operator on them. Remember that XOR can work on char data type and returns 0 if both characters are the same. public class XOR { public static String binaryStringXOR(String binStr1, String binStr2) { String xor = ""; //adding zeroes to make the two strings equal in length if(binStr1.length() > binStr2.length()) { String temp = ""; for(int i = 0; i < binStr1.length() - binStr2.length(); i++) temp += "0"; binStr2 = temp + binStr2; } else if(binStr2.length() > binStr1.length()) { String temp = ""; for(int i = 0; i < binStr2.length() - binStr1.length(); i++) temp += "0"; binStr1 = temp + binStr1; } for(int i=0; i < binStr1.length(); i++) { xor += binStr1.charAt(i) ^ binStr2.charAt(i); } return xor; } public static void main(String[] args) { System.out.println("1001 XOR 1111: " + binaryStringXOR("1001", "1111")); System.out.println("1 XOR 10100: " + binaryStringXOR("1", "10100")); System.out.println("0111 XOR 1: " + binaryStringXOR("0111", "1")); System.out.print("100000 XOR 0: " + binaryStringXOR("100000", "0")); } } 1001 XOR 1111: 0110 1 XOR 10100: 10101 0111 XOR 1: 0110 100000 XOR 0: 100000 Example: Find non repeating value using xor in Java We learned the basics of the XOR operator. Now let's use it to solve a problem. Suppose we have an array of integers and we know that each integer occurs exactly twice except one particular integer. Our task is to find this non-repeating integer. We can simply iterate over the array, and store the frequency of each integer and return the integer that occurs only once. But there is a more efficient way of doing this by using the XOR operator. Remember that XOR of a number with itself returns 0, and XOR of a number with 0 returns the number itself. For example, consider the input array [10, 12, 5, 6, 10, 6, 12]. We can see that all elements occur twice except 5. The XOR of all elements can be written as 10 ^ 12 ^ 5 ^ 6 ^ 10 ^ 6 ^ 12. This can be rearranged and written as (10 ^ 10) ^ (12 ^ 12 ) ^ (6 ^ 6) ^ 5. This is the same as writing 0 ^ 0 ^ 0 ^ 5, and this will return 5. public class XOR { public static int nonRepeatingInteger(int[] numArray) { int xor = numArray[0]; for(int i = 1; i < numArray.length; i++) xor = xor ^ numArray[i]; return xor; } public static void main(String[] args) { int[] arr = {10, 12, 5, 6, 10, 6, 12}; int nonRepeatingNum = nonRepeatingInteger(arr); System.out.print("The non-repeating integer is:" + nonRepeatingNum); } } The non-repeating integer is:5 Summary In this tutorial, we learned about the basics of the XOR operation. The caret symbol(^) is used as the XOR operator in Java and it can work on all primitive data types. We also implemented a method to find the XOR of two binary strings.
https://www.studytonight.com/java-examples/xor-operator-in-java
CC-MAIN-2022-05
refinedweb
934
65.32