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
Special price for HP laser toners Special price for HP laser toners <<Introduction>>< ?xml:namespace prefix = o Our facotry has been being the exporter and manufacturer for the compatible printer ribbon, then ink cartridge, toner cartridge, since 1996, exported to more than 30 countries; for this, we have great advantage in the price ,quality control, customer service and new items. We also supply printer parts, toner spare parts and some papers to give our customer convenience. Now we have special price for HP laser toners, Hot-selling modals, if you are interested in any modals ,welcome contact me anytime Ms.Tina MSN: xmsummit@hotmail.com Yahoo: zssummit@yahoo.com Skype: tinasummit
http://tonernews.com/forums/topic/webcontent-archived-20880/
CC-MAIN-2017-13
refinedweb
111
56.35
Haskell/Libraries/Random Random examples[edit] Random numbers have many uses. Example: Ten random integer numbers import System.Random main = do gen <- newStdGen let ns = randoms gen :: [Int] print $ take 10 ns The IO action newStdGen creates a new StdGen pseudorandom number generator state. This StdGen can be passed to functions which need to generate pseudorandom numbers. (There also exists a global random number generator which is initialized automatically in a system dependent fashion. This generator is maintained in the IO monad and can be accessed with getStdGen. This is perhaps a library wart, however, as all that you really ever need is newStdGen.) Alternatively, one can using mkStdGen: Example: Ten random floats using mkStdGen import System.Random randomList :: (Random a) => Int -> [a] randomList seed = randoms (mkStdGen seed) main :: IO () main = do print $ take 10 (randomList 42 :: [Float]) Running this script results in output like this: [0.110407025,0.8453985,0.3077821,0.78138804,0.5242582,0.5196911,0.20084688,0.4794773,0.3240164,6.1566383e-2] Example: Unsorting a list (imperfectly) import Data.List ( sortBy ) import Data.Ord ( comparing ) import System.Random ( Random, RandomGen, randoms, newStdGen ) main :: IO () main = do gen <- newStdGen interact $ unlines . unsort gen . lines unsort :: (RandomGen g) => g -> [x] -> [x] unsort g es = map snd . sortBy (comparing fst) $ zip rs es where rs = randoms g :: [Integer] There's more to random number generation than randoms. For example, you can use random (sans 's') to generate a single random number along with a new StdGen to be used for the next one. Also, randomR and randomRs take a parameter for specifying the range. See below for more ideas. The Standard Random Number Generator[edit] The Haskell standard random number functions and types are defined in the System.Random module. The definition of random is a bit tricky to follow because it uses classes to make itself more general. From the standard: ---------------- The RandomGen class ------------------------ class RandomGen g where genRange :: g -> (Int, Int) next :: g -> (Int, g) split :: g -> (g, g) ---------------- A standard instance of RandomGen ----------- data StdGen = ... -- Abstract This basically introduces StdGen, the standard random number generator "object". It's an instance of the RandomGen class which specifies the operations other pseudorandom number generator libraries need to implement to be used with the System.Random library. Given r :: StdGen, you can say: (x, r2) = next r. (The dots are not Haskell syntax; they simply say that the Standard does not define an implementation of these instances.) From the Standard: mkStdGen :: Int -> StdGen Put in a seed Int to the mkStdGen function, you'll get out a generator. As a functional language, Haskell returns a new random number generator with the next. In languages with mutable variables, the random number generator routine has the hidden side effect of updating the state of the generator ready for the next call. Haskell won't do that. If you want to generate three random numbers in Haskell, you need to say something like: let (x1, r2) = next r (x2, r3) = next r2 (x3, r4) = next r3 The random values (x1, x2, x3) are themselves random integers. To get something in the range, say, (0,999)). Therefore,". This all says: any instance of Random can use these functions. The instances of Random in the Standard are: instance Random Integer where ... instance Random Float where ... instance Random Double where ... instance Random Bool where ... instance Random Char where ... So for any of these types you can get a random range. You can get a random integer with: (x1, r2) = randomR (0,999) r And you can get a random upper case character with (c2, r3) = randomR ('A', 'Z') r2 You can even get a random bit with (b3, r4) = randomR (False, True) r3. That lets you say something like this: (r1, r2) = split r x = foo r1 In this case, we are passing r1 down into function foo, which does something random with it and returns a result "x". We can then take "r2" as the random number generator for whatever comes next. Without "split" we would have to write (x, r2) = foo r1 Yet this too is often clumsy. We can do it the quick and dirty way by putting the whole thing in the IO monad. Thus, we get a standard global random number generator just like any other language. From the Standard: ---------------- The global random generator ---------------- newStdGen :: IO StdGen setStdGen :: StdGen -> IO () getStdGen :: IO StdGen getStdRandom :: (StdGen -> (a, StdGen)) -> IO a We could write: foo :: IO Int foo = do r1 <- getStdGen let (x, r2) = randomR (0,999) r1 setStdGen r2 return x That gets the global generator, uses it, and then updates it (otherwise every random number will be the same). But having to get and update the global generator every time you use it is a pain, so its more common to use. Using QuickCheck to Generate Random Data[edit] Only being able to do random numbers via the IO monad is a bit of a pain. You find that some function deep inside your code needs a random number, and suddenly you have to rewrite half your program as IO actions instead of nice pure functions, or you need a StdGen parameter to tramp its way down there through all the higher level functions. We would prefer something a bit purer. Recall from the State monad chapter, that patterns like: let (x1, r2) = next r (x2, r3) = next r2 (x3, r4) = next r3 Can be done with "do" notation: do -- Not real Haskell x1 <- random x2 <- random x3 <- random Of course, you can do this in the IO monad, but it would be better if random numbers had their own little monad that specialized in random computations. And it just so happens that such a monad exists. It lives in the Test.QuickCheck module, and it's called Gen. The reason that Gen lives in Test.QuickCheck is historical: that is where it was invented. The purpose of QuickCheck is to generate random unit tests to verify properties of your code. (Incidentally, QuickCheck works wonderfully, and most Haskell developers use it for testing). See the Introduction to QuickCheck on the HaskellWiki for more details. This tutorial will concentrate on using the Gen monad for generating random data. To use QuickCheck modules, you will need to install the QuickCheck package. With that done, just put: randomTriple :: Gen (Integer, Integer, Integer) randomTriple = do x1 <- choose (0,999) x2 <- choose (0,999) x3 <- choose (0,999) return (x1, x2, x3) choose is one of the functions from QuickCheck. Its the equivalent to randomR. choose :: Random a => (a, a) -> Gen a In other words, for any type "a" which is an instance of "Random" (see above), choose will map a range into a generator. Once you have a Gen action you have to execute it. The unGen action executes an action and returns the random result: unGen :: Gen a -> StdGen -> Int -> a The three arguments are: - The generator action. - A random number generator. -. So for example, this generates three arbitrary numbers: let triple = unGen randomTriple (mkStdGen 1) 1 But the numbers will always be the same because the same seed value is used! If you want different numbers then you have to use a different StdGen argument. A common pattern in most programming languages involves a random number generator choosing between two courses of action: -- Not Haskell code r := random (0,1) if r == 1 then foo else bar QuickCheck provides a more declarative way of doing the same thing. If foo and bar are both generators returning the same type then we can say: oneof [foo, bar] This has an equal chance of returning either foo or " bar If you wanted different odds, then you could say something like: frequency [ (30, foo), (70, bar) ] oneof takes a simple list of Gen actions and selects one of them at random. frequency does something similar, but the probability of each item is given by the associated weighting. oneof :: [Gen a] -> Gen a frequency :: [(Int, Gen a)] -> Gen a
https://en.wikibooks.org/wiki/Haskell/Libraries/Random
CC-MAIN-2021-10
refinedweb
1,334
61.77
At this point, you should be quite the AI expert and things should be starting to gel. I've waited to talk about advanced AI scripting until now so you can see what I'm getting at with more of a foundation. You already saw that a scripted instruction language can be used for AI when you learned about using a simple [OPCODE OPERAND] language and a virtual interpreter earlier in the chapter. This is a form of scripting, of course. Then I showed you yet another way to create decision trees with a scripted language based on logical productions and a set of inputs, operators, and action functions. This technology can be taken to any limits you want. QUAKE C is a good example, as well as UNREAL Script. Both of these actually allow you to program game code with a high-level English-like language that is processed by the engine. The design of the scripting language is based on the functionality that you want to give it. Here are some questions that you might ask yourself: Will the scripting language be used for AI only, or will it be used for the entire game? Will the scripting language be compiled or interpreted? Will the scripting language be ultra-high-level, with an almost English-like syntax, or will it be a lower-level programming-like language with functions, variables, conditional logic, and so on? Will all the gameplay be designed using the scripting language? That is, will the programmers do any hard-code game design, or will the entire game run with scripts? What level of complexity and power do you want to give the scripters/game designers? Will they have access to system and engine variables? What's the level of the game designers who will use the scripting language? Are they HTML coders, entry-level programmers, or professional software engineers? These are the kinds of questions that you should think about before you start designing the language. Once you've answered these and any other questions, it's time to implement the language and really design the entire game. This is a very important phase. If your game is going to be completely controlled by a scripting language, you'd better make it really open-ended, robust, extensible, and powerful. For example, the language should be able to model an airplane that flies by every now and then, as well as a monster that attacks you! In any case, remember that the idea of a scripting language is to create a high-level interface to the engine so that low-level C/C++ code doesn't need to be programmed to control the objects in the game. Instead, an interpreted or compiled pseudo-English language can be used to describe actions in the game. This is shown in Figure 12.28. For example, here's a script for an imaginary scripting language to control a street light: OBJECT: "Street Light", SL VARIABLES: TIMER green_timer; // used to track time // called when object of this type is created ONCREATE() BEGIN // set animation to green SL.ANIM = "GREEN" END // this is the main script BEGINMAIN // is anything near the streetlight IF EVENT("near","Street Light") AND TIMER_STATE(green_timer) EQUAL OFF THEN BEGIN SL.ANIM = "RED" START_TIMER(green_timer,10) ENDIF // has the timer expired yet IF EVENT(green_timer,10) THEN BEGIN SL.ANIM = "GREEN" ENDIF ENDMAIN I just threw this together right now, so it may have some holes in it, but the point is that it's very high-level. There are a million little details about setting animations, checking proximity, and so forth, but with this language anyone can make a traffic light program. The code starts up and sets the light to green with ONCREATE(), and then it tests if anything is close by with the EVENT() test and turns the light red. After the light has been red for awhile, it turns back. The language looks a little like C, BASIC, and Pascal all mixed together—yup! This is the kind of language you need to design and implement to control a game—something that is neutral and knows how to operate on any object. For example, when you say BLOWUP("whatever"), the language processor better know how to make that work for any object in the game. Even though the call to blow up a blue monster might be TermBMs3(), and the call to blow up a wall might be PolyFractWallOneSide(), you just want to say BLOWUP("BLUE") and BLOWUP("wall"). Get the point? You're probably wondering how to implement one of these scripting languages. It's not easy. You have to decide whether you want an interpreted or compiled language—is the language going to compile into straight code, be interpreted by an interpreter in the game engine, or something in between? Then you have to write the language, a parser, a code generator, and a P-code interpreter, or make the code generator create straight PentiumX machine code or maybe translate to C/C++. These are all compiler design issues and you're on your own here, but you've already written a couple of baby interpreters. Some tools to help you are LEX and YACC, which stand for Lexical Analyzer and Yet Another Compiler Compiler. These are language parsing and definition tools to help you implement the recursive decent parser and complex state machines needed for a compiler or interpreter. I have a trick that you can use to get started without needing to write a full-blown language compiler/interpreter. Hold onto your hat! The nice thing about using an interpreted language is that the engine can read it and the game doesn't need to be recompiled. If you don't mind your game designers compiling (they should know how to anyway), you can use an old trick to make a crude game-scripting language: Use the C/C++ preprocessor to translate your scripting language for you. It takes nothing more than header files and the C/C++ source, which have nothing to do with compiler design. The C/C++ preprocessor is really an amazing tool. It enables you to perform symbolic referencing, substitutions, comparisons, math, and a lot more. If you don't mind using C/C++ as the root language and compiling your scripts, you might be able to write your scripting language by means of a clever design, a lot of text substitutions, a lot of canned functions, identifiers to refer to objects, and a good object-oriented design. Of course, under it is going to be real C/C++, but you don't have to tell your game designers that (if you have any). Or you can force them to use only the pseudo-language and not use all the real C/C++ functionality. The best way to show you this is with a very simple example (that's all I have time for). First, the scripting language will be compiled and each script will be run whenever the object it refers to is created. The script will be terminated when the object it refers to dies. The scripting language you're going to write is based on C, so I'm not going to go over everything there. But I am going to use text substitutions for a lot of new keywords and data types. A script consists of these parts: As for variable assignment and comparison, only the following operators will be valid: Comparisons—Greater than, less than, greater than or equal to, and less than or equal to all use the same C standard, which follows: (expression > expression) (expression < expression) (expression >= expression) (expression <= expression) Conditionals—The form of conditional statements is the same as C, except that the code that executes when the statement is TRUE must be contained within a BEGIN ENDIF block. Look at the following example: if (a EQUALS b) BEGIN // code ENDIF else BEGIN // code ENDELSE Similarly, the else block must be contained within a BEGIN ENDELSE block as well as the elseif. There are no switch statements in this language, and there's only one kind of loop in the language, called a WHILE loop: WHILE(condition) BEGIN // code ENDWHILE Next, there's a GOTO keyword that jumps from one point in the code to another. The jump must be labeled with a name of the form: LBL_NAME: where NAME can be any character string up to 16 characters in length. See the following example: LBL_DEAD: if (a EQUALS b) BEGIN GOTO LBL_DEAD; ENDIF You probably get the point by now. Of course, you'd want to add dozens or even hundreds of high-level helper functions that could perform tests on objects. For example, for objects that have a health or life state, you could have a function called HEALTH(): if (HEALTH("alien1") > 50) BEGIN // code ENDIF Moreover, you might create events that could be tested with a text string parameter: if (EVENT("player dead") BEGIN // code here ENDIF All this magic is accomplished by using clever global state variables and making sure to expose enough generic events to the scripts, along with system state variables (via functions) and a lot of text substitution via the preprocessor. Leaving out some of those details to keep things simple, let's take a look at what you need for text substitutions thus far. Referring to Figure 12.29, each script that is compiled will be processed first through the C/C++ preprocessor. This is where you're going to make all those text substitutions and convert your little script language back to C/C++. To make it work, you tell the scripter to save all the files with the extension script .SCR or something, and when the file is imported into your main C/C++ file for compilation, you make sure to first include the script translation header. Here's the script translator for what you've so far: SCRIPTTRANS.H // variable translations #define REAL static float #define INTEGER static int // comparisons #define EQUALS == #define NOTEQUAL != // block starts and ends #define BEGIN { #define END } #define BEGINMAIN { #define ENDIF } #define ENDWHILE } #define ENDELSE } #define ENDMAIN } // looping #define GOTO goto Then you include the following in your game code: #include "SCRIPTTRANS.H" Then you include the actual script file somewhere in your game engine at the proper moment. You can do it at the beginning, or even in a function: Main_Game_Loop() { #include "script1.scr" // more code } // end main game loop This part is up to you. The point is that the code the scripter writes must be compiled somehow, and it must be able to access the globals, see events, and make calls to the function set you expose. For example, here's a crude script that fires an event (which I didn't define at the count of 10): // the variables INTEGER index; index = 0; // the main section BEGINMAIN LBL_START: if (index EQUALS 10) BEGIN BLOWUP("self"); ENDIF if (index < 10) BEGIN index = index + 1; GOTO LBL_START; ENDIF ENDMAIN Obviously, you would have to define BLOWUP(), but you get the picture. This code would be translated by the preprocessor into the following: { static int index; index = 0; LBL_START: if (index == 10) { BLOWUP("self"); } if (index < 10) { index = index + 1; goto LBL_START; } } Cool, huh? Of course, I'm leaving out a lot of details, like problems with variable names colliding, accessing globals, debugging, making sure the script doesn't sit in an endless loop, and so forth. However, I think that you have an idea about using the compiler as a building block of a scripting language. TIP You can tell the Visual C++ compiler to output the preprocessed C/C++ file with the compiler directive /P.
http://www.yaldex.com/games-programming/0672323699_ch12lev1sec8.html
CC-MAIN-2017-04
refinedweb
1,958
66.17
Computer Science Aston University BirminghamB4 7ET Computer Graphics Lab Notes: OpenGL (in Java) Dan Cornford,Remi Barillec Module CS2150 September 29,2011 Contents Introduction 1 Lab 1:How to use OpenGL and Java;spatial awareness 2 Lab 2:Appearance in OpenGL 7 Lab 3:Construction in OpenGL 8 Lab 4:Lighting and materials in OpenGL 12 Lab 5:Quadrics and textures in OpenGL 14 Lab 6:Animation in OpenGL 16 Extra labs:useful examples in OpenGL 18 Summary 19 Introduction This series of exercises teaches you how to implement graphics using the OpenGL API,in Java.You will learn largely by following and then extending examples that we have written for you.We will be using the Eclipse IDE for Java.The great functionality offered by Eclipse can be daunting at first,but you will get familiar with it as we go along. It is highly recommended that you attempt the labs before the lab class,so that the lab time can be spent answering questions.The lab exercises build up in complexity,so you will want to attempt them in the correct order. As you will appreciate,this is not a programming module – the aim is to use OpenGL,and programming using OpenGL,to reinforce your understanding of the material covered in the course and to give you skills as graphics programmers.This will also provide you with more experience of programming in Java (which may well be of benefit when you go on placement or when you are looking for employment). OpenGL has bindings to just about every language that is used in computing.We’ll use the Java bindings provided by the Lightweight Java Game Library (LWJGL),see there are bindings to C and C++ as well as Visual Basic and many others.While you can use OpenGL with other languages I will expect coursework to be submit- ted written in Java.Installing the labs on the your computer at home is very simple;instructions can be found on the wiki (). Scene Graphs A scene graph is a hierarchical structure,commonly a tree,that represents the logical rela- tionships between objects in a given virtual world.In the labs we will make use of simplified scene graphs to describe the three dimensional virtual worlds that are rendered by the lab code examples.Later in the course you will learn how scene graphs can be used to help you write your coursework. Our simplified scene graphs will consist of two element types:nodes representing scene ob- jects,and arcs representing spatial relationships between objects.Examples of scene objects that you will encounter in the labs include three dimensional objects such as houses,planets, and the various parts of a person. In a given virtual world,spatial relationships exist between parent and child scene objects. Example spatial relationships include relative positioning (for example,a given child object is below its parent object),relative orientation (for example,a given child object is oriented 90 degrees clockwise to its parent),relative scaling (for example,a given child object is half the CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 2 size of its parent),plus combinations of these.We will use OpenGL transformation matrices to implement the spatial relationships in our scene graphs. Each node in the scene graph represents a new coordinate system relative to the centroid of the scene object at that node.Each scene graph has a scene root element,which represents the origin of the virtual world that is being described. An example scene graph,taken from Lab5,is given below. Scene origin | +-- [S(20,1,20) T(0,-1,-10)] Ground plane | +-- [S(20,1,10) Rx(90) T(0,4,-20)] Sky plane | +-- [T(4,7,-19)] Sun | +-- [Ry(35) S(2,2,2) T(-2.5,0,-10)] HouseBase | +-- [S(1,0.5,1) T(0,0.75,0)] Roof This scene graph describes the world model in Lab5;this has a ground plane and a sky plane and the sun,hanging from the scene origin.A house,rotated,scaled and translated is then drawn,and the roof of the house is scaled and translated to sit on top of the house,and moves with the house too,since this is a child element of the HouseBase (note that all transformations that are applied to the parent will also be applied to the children).Each scene object is prefixed by the spatial relationship between the scene object and its parent in square brackets,which corresponds to an OpenGL matrix (empty square brackets denote the identity matrix).Each spatial relationship is written as a series of translations (indicated by a T plus the x,y,and z units),rotations (indicated by an R plus the axis and angle of rotation) and scalings (indicated by an S plus the x,y and z units). Make sure you look at the scene graphs for each example you run;the animated person is particularly important to understand. Getting Started The code for the labs is available as a zipped workspace file that includes one project per example application.The zipped file containing all Java bits and pieces can be obtained from wiki.Note that instructions for how to use Eclipse with the code are on the wiki site too. Lab 1:How to use OpenGL and Java;spatial awareness In the labs,and in your coursework,you will use the LWJGL library,and extend an abstract base class we wrote to hide some of the implementation details and focus on what is more important. The general structure of a LWJGL based OpenGL program can be seen in the file Lab1.java.Open the Lab1.java in Eclipse and select the ‘Lab1’ project as the active project so that you can run the program. Figure 1:An overview of the Lab1 class and associated classes. The first thing to do is to look at the code (resist the temptation to run the program).The header of the files will always look something like the below: CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 3 / * Lab1.java * A simple scene consisting of three boxes * Scene Graph: ... * / package Lab1; import org.lwjgl.opengl.GL11; import org.lwjgl.util.glu.GLU; import GraphicsLab. * ; / ** * Program comment in Javadoc style * / public class Lab1 extends GraphicsLab { ... } All the labs are documented and use the Javadoc conventions;try to use this in your course- work submission too.Notice that the first thing you see in each example is the scene graph - this is very important (that’s why it comes near the top) - it provides an abstraction of the contents of the scene in a very compact form.You must produce a scene graph for your coursework submission,so it is best to get familiar with them in the labs. After the scene graph we tell the Java Virtual Machine to import the LWJGL library (at least the part of it relevant to OpenGL).This will appear in all the programs.Following this we see the main program comment.Finally we get to the class definition.In this case we define a single class (this will typically be the case) called Lab1 which extends our abstract base utility class GraphicsLab,as shown in Figure 1.Before we go any further we’ll quickly explain what is in the GraphicsLab class. The GraphicsLab abstract class is designed to provide various utility functions and encapsu- late behaviour that is needed across al the graphics labs.I do not suggest you undertake a deep analysis of it at this point,but once you are familiar with the graphics labs then you are welcome to take a look under the bonnet.For now I will describe the key methods in the class (and the associated helper classes that are also provided) shown in Figure 2. The critical method to define in terms of producing computer graphics is the renderScene method.This is where you put the code that defines what should be drawn;if we look at the Lab1.java files we can see that the protected abstract void renderScene();from the GraphicsLab abstract class is overridden with: Figure 2:An overview of the GraphicsLab and associated classes. protected void renderScene() { //position and draw the first cube GL11.glPushMatrix(); { GL11.glTranslatef(0.0f,-1.0f,-2.0f); drawUnitCube(Colour.BLUE,Colour.BLUE,Colour.RED,Colour.RED, Colour.GREEN,Colour.GREEN); } GL11.glPopMatrix(); ... } This code draws three cubes on the screen. Run the program,Lab1 to see the effect (in the Package manager,right-click on Lab1.java CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 4 and select “Run as” and “Java Application”),select.Can you understand the code in the renderScene method? The code is not too complex,but introduces a lot of features.We’ll walk through the code first.The first thing you notice is the command GL11.glPushMatrix().This command has a structure you’ll see over and over again.It starts with the GL11.- this identifies the com- mand as being related to the OpenGL v1.1 API.All OpenGL commands you will see and use start with GL11.and then are followed by the actual OpenGL function call,in this case to glPushMatrix() which takes no parameters.If you are ever unsure about what the different OpenGL functions are doing then you can check the online manual,which can be accessed from the CS2150 wiki page – but just look for the part following GL11.not the whole string. glPushMatrix() is an OpenGL command that allows you to store the current value of the composite model-view matrix (typically) onto the matrix stack.This is a very impor- tant concept and allows you to isolate the effect of subsequent transformations by using glPopMatrix() to recover the value fromthe top of the stack.So in the example code above, the composite model-view matrix is stored on the stack,then a translation is applied using GL11.glTranslatef(0.0f,-1.0f,-6.0f).This translation call modifies the composite model-view matrix,to reflect a translation of 0.0 in the x-direction,-1.0 in the y-direction and -6.0 in the z-direction.Remember x is across,y is up,and z is out of the screen in the world coordinate system,so this means that anything that is now draw is moved zero units across, one unit down,and 6 units away from the viewer. The next command is one we have written for you:drawUnitCube(...) which draws a unit cube on the screen,with the parameters providing information on what colour each face is to be drawn in.We’ll look at the code in a minute.For now just assume you know how the cube is drawn;remember that the translation that comes above this has modified the composite model- view matrix so this cube will be drawn zero units across,one unit down,and 6 units away from where it is originally defined.After the cube has been drawn the composite model-view matrix is then popped off the matrix stack using GL11.glPopMatrix(),so that the composite model- view matrix reverts back to what it was before the call GL11.glPushMatrix().This means that the above translation only affects the single instance of the cube drawn in the above code fragment.Note that the f g brackets around the translation and draw method are not strictly needed,however their presence emphasises that the enclosed code is isolated (in terms of the effect on the composite model-view matrix). Now we’ll look at how the cube is drawn: private void drawUnitCube(Colour near,...) { //the vertices for the cube (note that all sides have a //length of 1) Vertex v1 = new Vertex(-0.5f,-0.5f,0.5f); Vertex v2 = new Vertex(-0.5f,0.5f,0.5f); ... //draw the near face: near.submit(); GL11.glBegin(GL11.GL_POLYGON); { v3.submit(); v2.submit(); v1.submit(); v4.submit(); } GL11.glEnd(); ... } In the above code you see several important things.Firstly we define the vertices (that is points that define the corners) of the cube we want to draw.This is centred about the origin (0,0,0). The vertices of the cube are thus the eight points that make up all the corners.When creating 3D shapes we need to be able to define the vertices. V 1 V 4 V 3 V 2 V 5 V 8 V 7 V 6 x y z Origin (0,0,0) Figure 3:The cube,as defined in the code in Lab1. Figure 3 shows the manner in which the cube is constructed.The vertices each have 3 coor- dinates,the x,y,and z coordinate respectively. On Figure 3 write down the coordinates for all the cube vertices – do they make sense? The vertices are defined to be of type Vertex which is it’s own class.The class enables us to CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 5 store a 3 component vector,as shown below: public class Vertex { private float x;/ ** the x component of this vertex * / private float y;/ ** the y component of this vertex * / private float z;/ ** the z component of this vertex * / / ** * Constructs a Vertex object from its x,y and z components * / public Vertex(float x,float y,float z) { this.x = x; this.y = y; this.z = z; } / ** * Submits this Vertex to OpenGL using an immediate mode call * / public void submit() { GL11.glVertex3f(x,y,z); } ... } Most of the code is quite clear;the class essentially stores the vertex coordinates, and has one significant method,called submit.This code passes the vertex to OpenGL using the command glVertex3f(x,y,z),so that it can be ‘drawn’.Look- ing back at the code to draw the square we see that that the vertices are submitted in the part of the code that draws the faces.OpenGL works by defining objects to be drawn between a glBegin(.) and glEnd() call.In the call to glBegin(.) we need to specify what is being drawn;here we draw a polygon by calling GL11.glBegin(GL11.GL POLYGON).There are a range of permissible drawing modes,as you’ll see in Lab2. You can’t just pass anything in between the glBegin(.) and glEnd() calls.In general you should pass vertices (and normals) within these calls.Note the ordering of the vertices in the call is important;here we pass in v3,v2,v1,v4. Make sure you understand the order of the vertices for all faces – in what sense of rotation are the vertices given (clockwise or anti-clockwise)? In OpenGL vertices must always be given is anti-clockwise order,as viewed from the front (as in the outside of the solid) of the face (so this is quite tricky for the rear face of the cube,since we need to put ourselves ’behind’ the cube and imagine looking at this back face from the front!). In the Lab1 Java code change the order of the front face vertices:what happens? The results will depend on what exactly you changed,but in general the object will not be drawn correctly.One of the most common problems in using OpenGL is that the vertices are not in the correct order,or they are not all on a plane.When OpenGL draws polygons or other shapes,all the vertices of these must lie in a 2 dimension plane (i.e.on a flat thing!).This is most easily achieved by designing your objects to be aligned with the major x,y,z axes.If this is the case,then all the values of one of the x,or y,or z coordinates must be the same for each face (but not the whole 3D object). In the code to draw the squares you will also notice that there is a command near.submit() just before the call to GL11.glBegin(GL11.GL POLYGON).This sets the colour of the near face - in the call to drawUnitCube(Colour near,...),near is of type Colour which is a class in it’s own right.Take a look at the Java for this class (it is in the Graph- icsLabs directory).You can see this stores information on the colour,which is again a 3 com- ponent vector of floats,this time the components being the amount of red,green and blue light the colour should contain.Again there is really only one method of significance in the Colour class;the submit method,which passes the colour to OpenGL using GL11.glColor3f(red, green,blue).Note that OpenGL is a state machine;when you set the colour in one place in your code,it will stay set,and all objects drawn will use those colour properties until you change it.In the call near.submit() the colour defined for the near face (in this case blue, using a pre-set colour from the Colour class) is used. The final part of the Lab1 code to look at is the method that defines the way we look at the scene,that is the method that sets the base projection and model-view matrices.The code is shown below: protected void setSceneCamera() { //call the default behaviour in GraphicsLab.Set the default //perspective projection and default camera settings ready //for some custom camera positioning below... super.setSceneCamera(); //Set the viewpoint using gluLookAt.This specifies the //viewers (x,y,z) position,the point the viewer is looking //at (x,y,z) and the view-up direction (x,y,z),normally //left at (0,1,0) - i.e.the y-axis defines the up direction GLU.gluLookAt(0.0f,0.0f,10.0f,//viewer location CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 6 0.0f,0.0f,0.0f,//view point loc. 0.0f,1.0f,0.0f);//view-up vector } Note that the GraphicsLab base class already has a complete definition of the projection and model-view matrix setup (which is called by super.setSceneCamera()).If you want to you can take a look at this in the GraphicsLab class.In general I would recommend you leave the projection matrix as it is;recall the projection matrix (GL PROJECTION) is used to define the lens of the camera,i.e.it is used to zoom in and zoom out of the scene.The projection matrix is best changed using the GLU.gluPerspective command – to see how this works look it up using the OpenGL online manual. The modelview matrix (GL MODELVIEW) is used to position and point the camera,i.e.to say where it is in space,and where it is looking at (and also what direction is up).In general you will always be working with the model-view matrix.The GLU.gluLookAt command,from the OpenGL utilities library (GLU),is a very easy way to position and point the camera.You simple specify the 3D (x,y,z) coordinates of the viewer (where the camera is),the view point (where the camera is looking) and the view-up vector (what direction is up). Move the camera around the boxes to view themfromthe right (hint change only the viewer location),left,above and behind.How do the views differ from the plan views? You should now understand the renderScene method in the Lab1 code.We now need to see if you understand where these cubes that are drawn are in space.To help you keep track of where objects are in the code,we have written some helper functions. Run the Lab1 code,then press the ’x’ key.This shows you a view of the scene,using an orthographic (i.e.like are used in plan drawings;not 3D,no perspective) view of the objects in the scene,as if you were looking directly down the x-axis (i.e.from the right hand side of your screen).The coloured lines show the positive y-axis (green) – that is up,and the positive z-axis (blue) – that is coming out of the screen. Now press the ’y’ key;what do you see?This is like looking from directly above.The red line is the positive x-axis. Now press the ’z’ key - this time the axes drawn are the x- and y-axes,and the view is from directly in front of the scene. To help you orient yourself the tops and bottoms of the boxes are coloured green,the sides red and the front and back faces blue,and these colours are maintained on the plan views. These 3 plan views are very useful when trying to put the objects where you want them to go, and in checking they are where you think they are.The code to plot the plan views is hidden in the GraphicsLab base class – I advise you not to look at it yet;save it for when we look at viewing in 3D in the lectures. In the plan views you can also zoom in and out,pressing the arrow keys (up to zoom out, down to zoom in) at the same time as holding down the x,y or z keys. Using the plan views you have,the code and a piece of paper work out how to change the translations of the cubes so they can be stacked on top of each other. It is important that you do this on paper;you should always draw what you want to do,then work it out on paper,before coding in graphics – you can’t hack graphics stuff together easily! Now change the code – you’ll need to modify the GL11.glTranslatef(.) commands to get the cubes to stack on top of one another. Once the cubes are stacked move the view again to check they really stack fromall angles. You might be wondering how such a small amount of code can produce the Lab1 results.The answer is that there is quite a lot of functionality in the GraphicsLab base class.For now I suggest you don’t look at this,but if you are curious the code is all commented and most parts are quite obvious.As we develop more complex programs in later labs you will see how to extend other parts of GraphicsLab.To quit the Lab1 program,just press the Escape key,or kill the window. CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 7 Lab 2:Appearance in OpenGL In Lab1 we looked at the basic operation of an OpenGL program,focussing on making sure you understood how the spatial location of objects was controlled and how viewing worked. We did not really talk about how to change the appearance of the objects. Run the Lab2 code;what do you see?Take a look at the code;what is different fromLab1? Note that in Lab2 we do not set the camera matrices (the projection and modelview matrices) rather we rely on the default implementation in the GraphicsLab base class.This puts the camera at the origin,looking down the negative z-axis,with the y-axis being defined as up. Change the colours on the front faces of the cube to be the colours of a traffic light.You need to check the Colour class to see what colours are available. Making the red and green lights is pretty easy,but what about orange?There are two ways you could do this;either by adding ORANGE as a hard coded colour to the Colour class,or by directly defining the colour yourself.The Colour class has two constructors;one that takes floats in the range zero to one,and one that takes integers in the range zero to 255.If you check on the wiki site you will see a link to a web page that defines the colours,in terms of their integer values in the range 0-255.Looking for orange,there are several options;I like R = 255,G = 127,B = 0.We can pass the new colour into the call to drawUnitCube by creating a new instance of the Colour class using new Colour(255,127,0). Alternatively if you wanted to use the orange colour a lot you could define an ap- propriate constant in the Colour class using public static final Colour ORANGE = new Colour(255,127,0) – this is actually already there,so you can just uncomment it. Also make sure you can also define your own colour in Lab2.java directly. In OpenGL colours,and other properties can be set per vertex.The colours are then interpo- lated across the faces of the objects. Try modifying the draw cube method so that the first four colours passed in are applied one after another to the four vertices of the front face.What is the effect? The code should look something like the below: //draw the near face: GL11.glBegin(GL11.GL_POLYGON); { near.submit(); v3.submit(); left.submit(); v2.submit(); right.submit(); v1.submit(); top.submit(); v4.submit(); } GL11.glEnd(); Make sure you understand why you get the results you see.You might want to refer back to the list of vertices in Figure 3. In addition to the appearance of the object in terms of its colour (which as we shall shortly see is better defined using materials in any case) we can also control the style in which the points, lines and polygons are drawn.Like the colour properties the style properties are also treated as a state machine,so set the once and they will apply to everything that is drawn afterwards until you reset them. The first decision we can make is whether to draw polygons as filled areas,or lines (wire- frame).To make a wireframe view we simply need to specify that the polygons should be drawn as lines. Change the initScene method in Lab2: protected void initScene() { GL11.glDisable(GL11.GL_CULL_FACE); GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK,GL11.GL_LINE); } We need to switch off back-face culling so that both the front and the back faces are drawn, otherwise we will only see the front faces,and the wireframe viewwon’t look right.In specifying the glPolygonMode we can refer to which face (the first argument) which can be GL FRONT, GL BACK or GL FRONT AND BACK.We can also specify the style;commonly used options are GL FILL (the default),GL LINE or GL POINT. Change the style so that the polygons are drawn as points. Notice that the lines are thin and the points very small.These styles can also be changed using glLineWidth( float ) and glPointSize( float ). CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 8 Change the size of the points and the thickness of the lines and see the effect. At this point you might be wondering where the blue front face has gone,but note the order in which the faces are drawn;disabling back-face culling means all faces are drawn;the top, bottom and side ones are drawn over the top of the front face.This illustrates the immediate mode nature of many OpenGL commands;the effects are drawn directly to the framebuffer (i.e.the pixels are set to the given colour once the glEnd() command is called),so anything that draws onto the the same pixel later in the frame just removes what was first there.Since we make all these changes in the initialisation,the effect will persist for all objects drawn.If we want to make changes that apply only to one object we need to change the drawing state for one object and the reset it for the next one. Try to make the top cube be drawn in a wireframe manner,with all other cubes as solid objects.Hint:you will need to re-enable back-face culling and you need to modify the renderScene method. Drawing your objects as wireframe,especially when you use different colours on different faces can be very useful when you are trying to understand why a solid object does not render correctly – a sort of visual debugging. Lab 3:Construction in OpenGL Building 3D models is an important part of graphics programming.Typically in a real-life situ- ation you would use a range of tools to help you build your 3D models,using existing models (aka code re-use) and a carefully designed GUI.But here you will learn the hard way (I believe this is an important skill if you are to master the more advanced tools and understand their limitations!),using pencil and paper. Open Lab3,and run the program.What does it do?Look at the code - do you notice any differences from Labs 1 and 2? The graphical changes are quite obvious;only a single cube is created and it is quite red,and a bit rotated. But there is a more significant change to the code.We have started to use display lists.Display lists are a feature of OpenGL that allow objects to be pre-defined and pre-compiled.In many systems this means the graphical objects are then stored on the GPU memory rather than in system memory,and thus their use is very much faster since there is no interaction with the system bus when they are rendered.Display lists are also quite reminiscent of retained mode graphics packages,since they are kept in memory and drawn only on rendering.In general it is a good idea to use display lists;the main reason is speed.However they should only be used for rigid bodies - if there are transformations within a display list these will only be evaluated at compile time (which should happen in the init method),otherwise all benefits are lost,indeed there are significant disadvantages.So use display lists for the rigid parts of objects - they can still be used in a larger object that will be animated,but the display list can only contain rigid sub-elements.You will see more examples later in the labs. Look at the code that defines the display list,and make sure you can follow it. Now we want to add a simple triangular roof to the cube,to make it into a house.We will proceed as follows: 1.We will draw the roof on paper,at the origin 2.We will work out the roof’s vertices (relative to the origin) 3.We will then add the necessary code to draw the roof (at the origin) 4.Prior to drawing the roof (in OpenGL),we will move to the top of the cube,so that it is drawn above,not inside the cube. Guidelines for drawing objects We could draw the house as a whole,by adding new vertices to the cube.However,this is not CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 9 recommended in practice.The reason for this is that you might want to draw several houses, with different sized roofs.Having 2 objects,one for the base of the house (a cube) and one for the roof (a triangular prism,see image below),makes it a lot easier to create different looking houses.In general,when you want to draw a complex object,you should try and split it into simple,reusable 3D objects and design each of these independently.You can then put the simple objects together using transformations. Take a pen and a piece of paper.We will make the roof a triangular prism rather than a pyramid (left shape below). Figure 4:A triangular prism(left) and a pyramid (right) Draw the roof.Make it big enough,so you can add names for the vertices later. Choosing the origin This is a very important step,as all transformations you apply to an object are relative to the origin.When choosing the origin of an object,ask yourself whether the object presents any symmetry.If so,you probably want to make the origin coincide with the centers (or axes) of symmetry.Does our roof present any symmetries?To find symmetries,ask yourself the question:can the object be split in 2 so that both parts are the mirror of each other?Or is there an axis around which the object can be rotated by and still look exactly the same? The roof presents 2 reflection (i.e.mirror) symmetries,shown below(figures a and b).It makes sense to put the origin on the line where the 2 symmetry planes (in gray) meet (figure c).Where on that line does not really matter.However,since we will need to translate the roof so that its bottom face lies on the top face of the cube,setting the origin on the bottom face will make it easier to work out the required translation later. Set the origin of the roof so that it lies at the intersection of the vertical symmetry line and the bottom face. The origin is the point of coordinate (0,0,0).Note that when designing new objects,we imagine that we are working in an empty world.So the origin of the new object is not related to the origin of the previous scene (the scene with the cube). a) b) c) Figure 5:Reflection symmetries and their intersecting line Add the x,y and z axes to your drawing.These are repre- sented as arrows starting from the origin and following the right hand coordinate system(x to the right,y to the top,and z towards us). x y z Give each of the 6 vertices a name,e.g.V 1 ,...,V 6 . Given that the origin is the point (0,0,0) and that the roof fits within a unit cube (i.e.width = height = depth = 1),work out the coordinates of each vertex. Work out the order in which to pass the vertices for each face of the roof.Remember that you must pass the vertices in counter-clockwise order,from the point of view of someone looking at the face from the outside of the object. CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 10 Now that you have computed the vertices and the faces,you will want to add a method drawHouseRoof to the code,which declares the vertices and draws the faces of the roof. Using the ShapeDesigner Because implementing new objects can be sometimes a bit tricky,I have made a little “utility” to help you in the process:the ShapeDesigner.The ShapeDesigner allows you to work with a single shape (i.e.3D object) and visualise it easily.With the ShapeDesigner,you can rotate or move the camera around and change the way things are drawn,by using simple keyboard shortcuts. In the Package Explorer,open the Designer package.This package contains 2 classes: AbstractDesigner and ShapeDesigner.The AbstractDesigner class you need not worry about – it is an abstract class (you had probably worked that one out) which provides most of the functionality for the ShapeDesigner.Open the ShapeDesigner class.It is a very basic class,with only 2 methods: the main(...) method,which just runs the ShapeDesigner, the drawUnitShape(),which draws a single shape (the one we are designing).For now,I’ve simply copied over the code fromthe drawUnitCube method so something gets drawn when you run the ShapeDesigner for the first time. Run the ShapeDesigner.You should see our good old unit cube in white wireframe.You can change the way the object is viewed using the following controls: Key Action Tab Switch between point/wireframe/polygon drawing modes A Toggle colours Up Move the camera away from the shape Down Move the camera closer to the shape X Rotate about the world’s X axis Y or C Rotate about the rotated Y axis (explication below) Z Rotate about the object’s Z axis Shift Invert the direction of rotation (hold key while rotating) Space Reset the view to its initial state The colour toggle only works if you submit colours for the faces using the submitNextColour() method.See below. Experiment with the controls.Make sure you can rotate the object,change its appearance (drawing mode and colour) and reset the view.The rotation system is a bit complicated.It essentially follows a gimbal (see).The X rotation is about the world’s X-axis (which doesn’t move) and the Z rotation is about the object’s Z axis (blue line).However,the Y rotation is about an axis which depends on both the others and is hard to visualise.You might find it easier to not use the Y rotation and stick to the other two, which are more intuitive.These two rotations are sufficient anyway to show the object from any angle. To create a new shape in the ShapeDesigner,all you need to do is delete the body of the drawUnitShape() method (leave its signature) and start coding your own vertices and shapes.When declaring the faces,you can submit your own colours as usual,e.g. Colour.RED.submit(),or you can use submitNextColour() instead,which cycles through a list of predefined colours and also allows you to toggle between white and colour modes. In the ShapeDesigner,delete the body of the drawUnitShape() method and add the decla- rations for the roof’s vertices,as done in drawUnitCube(),but using the coordinates you have worked out.You can test the vertices as you go by drawing them with the following statement, e.g.for vertex v 1 : GL11.glBegin(GL11.GL_POINTS); v1.submit(); GL11.glEnd(); You can add the other vertices between the glBegin(...) and glEnd() statements. Once you are happy with your vertices,remove the code above so they don’t get drawn anymore and add the statements to draw the 5 faces.To take advantage of the automatic colouring,remember to use submitNextColour() before declaring the face.When designing the faces of an object,it is usually recommended to work on one face at a time.So once you are happy with a given face,you can comment out its code and move on to the next face. When all faces look ok,you can uncomment them all and draw the full object. Common implementation problems are to do with getting the order of the points about the face correct (anti-clockwise) and the points not all lying in a plane (a polygon is flat,so all its vertices must lie on a same plane!). Once you have the code to draw the full roof,copy the drawUnitShape() method over to Lab 3,rename it to something more meaningful like drawUnitRoof() and remove any call to submitNextColor() (this only works in the ShapeDesigner).Create a display list for your roof,which will call drawUnitRoof(). Depending on how you chose the origin for the roof object,you might well need to call a translation after you draw the house base (the cube) to put the roof on top of the house,but CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 11 remember the other transformations that are applied before the base is drawn will also be applied to the roof – which is what you want!This means if you move the base of the house (e.g.rotate it,as is done here) then the same thing will be applied to the roof,so the house won’t fly apart. Maybe you didn’t sort the colour of the roof;make it something appropriate. You might feel your house is too big or too small.This is very easy to change in OpenGL. The most simple way to make it smaller here is to move it further away from us:change the z-value of the translation in the renderScene method to a larger negative value,say -50. What does this do? Of course this only makes the house look smaller,it is clearly really the same size! One important point to note here is that the order of the transformations in the renderScene method is critical. Change the order of the rotation and translation in renderScene.Can you explain what happens - remember that pressing the x,y and z keys gives the plan views in all labs. OpenGL applies the transformations to the composite transformation matrix,by multiplication on the right (that is the the composite transformation matrix C gets updated by the current transformation matrix,T,in the following manner:C T C) – this means the transforma- tions are applied in the opposite order to which they appear in the code.In the original code we have: protected void renderScene() { //position the house GL11.glTranslatef(0.0f,-0.5f,-5.0f); //rotate the house a little so that we can see more of it GL11.glRotatef(35.0f,0.0f,1.0f,0.0f); //draw the base of the house by calling the appropriate //display list GL11.glCallList(cubeList); } In the above code it is the rotation that is applied to the house (cube) vertices first,and then the translation to move the house away and down a little.Changing the order means the house is translated first,then rotated,which is probably not what we wanted to do!In general,we want to rotate objects about their centres (not always of course) and in most of the code we will show you,the objects are defined so that their centres are at the origin,thus rotation (which is always about the origin) should be applied before translations in general.Clearly if you want to rotate an object about another point,then you need to translate the object first.We will come back to this when we look at animation. The other way to make the house smaller is to scale it.There is a command glScalef(sx,sy,sz) which allow you to scale an object by a factor sx,sy,sz about the x,y and z-axes respectively.Apply this to house. What effect does the positioning of the scale command in the renderScene method have? Can you explain this? The most important part of this lab is that you have understood how to define a new object in OpenGL. CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 12 Lab 4:Lighting and materials in OpenGL To make 3D graphics look realistic you need to be able to define lighting.OpenGL has support for a range of lighting models.The models we discuss in the lectures;ambient (coming fromall around equally),diffuse (from a direction but scattered in all directions) and specular (shining off an object,like reflection) are all quite easy to implement.When you set up the lighting properties,using up to 8 separate lights,you also need to set the material properties of the objects in the scene,to determine how they respond to light. Open up Lab4.java - this now has a house,but it looks all wrong if you run the code;note we have added the roof for you,so you can check if your roof is correct by comparing it with the roof in this code. Notice there are some newelements to the initScene method (for nowignore the commented part): protected void initScene() { //global ambient light level float globalAmbient[] = {0.2f,0.2f,0.2f,1.0f}; //set the global ambient lighting GL11.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, FloatBuffer.wrap(globalAmbient)); ... //enable lighting calculations GL11.glEnable(GL11.GL_LIGHTING); //ensure that all normals are automatically re-normalised //after transformations GL11.glEnable(GL11.GL_NORMALIZE); ... } We typically set the lighting in the initialisation (lighting is also part of the OpenGL state ma- chine,so once set it remains that way until you alter it).Of course we can also include lighting within our rendering methods (normally we just switch themon and off here in fact);this is only sensible when we want to change lighting during the course of the execution of the program (for example we might want to switch off a light if a key is pressed).In general you should try to avoid unnecessary changes of OpenGL state;so if you want to use the same lighting model all the time,as here,make sure this is set up in the initialisation so it is not reset each time the render process is called. In the above code two things are done.Firstly an ambient lighting model is defined globally (i.e.this ambient model applies everywhere).In general specific lights in OpenGL have a position,so their ambient lighting value does not always make sense,although they will add some illumination to the global ambient light field.The ambient lighting is set quite low,since values for lights should be in the range of 0.0 – 1.0;this is done so the house object is visible, but so that later the ambient light won’t dominate.Note the rather unpleasant necessity of having the use the FloatBuffer.wrap method to pass the arrays to OpenGL;this is just something you’ll have to remember to do for all lighting related commands. The other OpenGL commands in the above code,enable the lighting model - this can be switched on and off at will,but I suggest that in general you leave it switched on.The automatic re-normalisation (to unit length) of surface normals is also switched on;again I suggest you always enable this. There have also been changes in the renderScene method: ... //how shiny are the front faces of the house //(specular exponent between 0 and 128) float houseFrontShininess = 2.0f;//Not at all shiny! //specular reflection of the front faces of the house float houseFrontSpecular[] = {0.1f,0.0f,0.0f,1.0f}; //diffuse reflection of the front faces of the house float houseFrontDiffuse[] = {0.6f,0.2f,0.2f,1.0f}; //set the material properties for the house using OpenGL GL11.glMaterialf(GL11.GL_FRONT,GL11.GL_SHININESS, houseFrontShininess); GL11.glMaterial(GL11.GL_FRONT,GL11.GL_SPECULAR, FloatBuffer.wrap(houseFrontSpecular)); GL11.glMaterial(GL11.GL_FRONT,GL11.GL_DIFFUSE, FloatBuffer.wrap(houseFrontDiffuse)); GL11.glMaterial(GL11.GL_FRONT,GL11.GL_AMBIENT, FloatBuffer.wrap(houseFrontDiffuse)); ... There is quite a lot happening in the above code;in particular the material properties for the front (that means outward facing) faces of the house cube are being set.Normally 3 main properties must be set for the materials;the ambient reflection coefficients,the diffuse reflection coefficients and the specular reflection coefficients and exponent.In general the ambient and diffuse reflection coefficients,set for red,green and blue light,should be the same (as they are in the above code) - using different values is not physically realistic.Remember that all reflection coefficients must also be in the range 0.0 – 1.0.This also applies to specular reflection,but here we also need to set the specular exponent,which determines howshiny the object looks – the higher the value the more shiny it will appear (the maximum value is 128). You might notice a fourth value is also used;this is the so called alpha value and provides a CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 13 method for creating transparency;we will not cover this so always leave the final value at 1.0. Every face that is to be rendered must be assigned a material value,but again materials are part of the OpenGL state machine;once set the material properties will be applied to all objects rendered until they are changed.This is why a newset of material properties are defined before the roof is drawn. Run the code and look at the results.It does not look very interesting or 3D – any idea why? If you just get a black screen look closely - raise the ambient lighting to have values of 0.5 for each component and see what happens;then return these to their original values of 0.2.So far we have only set the ambient light,and this light has no directional preference,so it just looks like we have used colours again;to get the 3D effect we need to add some directional light.That is your next job. Uncomment the code in the initialisation that sets up the first light.The code is show below. Run the code and notice the effect.Can you explain what you see? The code we have uncommented looks like: //the first light for the scene is white... float diffuse0[] = { 0.6f,0.6f,0.6f,1.0f}; //...with a dim ambient contribution... float ambient0[] = { 0.1f,0.1f,0.1f,1.0f}; //...and is positioned above and behind the viewpoint float position0[] = { 0.0f,10.0f,5.0f,1.0f}; //supply OpenGL with the properties for the first light GL11.glLight(GL11.GL_LIGHT0,GL11.GL_AMBIENT, FloatBuffer.wrap(ambient0)); GL11.glLight(GL11.GL_LIGHT0,GL11.GL_DIFFUSE, FloatBuffer.wrap(diffuse0)); GL11.glLight(GL11.GL_LIGHT0,GL11.GL_SPECULAR, FloatBuffer.wrap(diffuse0)); GL11.glLight(GL11.GL_LIGHT0,GL11.GL_POSITION, FloatBuffer.wrap(position0)); //enable the first light GL11.glEnable(GL11.GL_LIGHT0); This code sets the properties of the lights that are applied to the scene.Here we set a low level of ambient light fromGL LIGHT0 - note we can have up to seven other lights in the scene as well.We also set the diffuse and specular components of the light;physically these ought to be the same,as they are set in this example,but sometimes they can be set differently to achieve strange looking effects.I do not recommend this.We also have to position the lights in the scene;this is quite important since it will determine where the illumination falls,although by default distance is ignored in OpenGL and only the vector direction is important.Finally we need to enable the light,so it is used.Individual lights can be set up in the initialisation and enabled and disabled within the program,to simulate switching lights on and off for example. Press (and hold down) the r key;this rotates the house and allows you to see the lighting effect much more clearly. The rotation is the first example of animation;the code to performthe animation is quite simple. We add a field called houseRotationAngle to the Lab4 class;this field is used in the rotation transformation that is applied to the house prior to drawing: GL11.glRotatef(houseRotationAngle,0.0f,1.0f,0.0f); The code that modifies the rotation angle is in the checkSceneInput method: protected void checkSceneInput() { //Rotate if the r key is pressed if(Keyboard.isKeyDown(Keyboard.KEY_R)) { houseRotationAngle += 1.0f * getAnimationScale(); //Wrap the angle back around into 0-360 degrees if (houseRotationAngle > 360.0f) { houseRotationAngle = 0.0f; } } } If the animation is too slow this can be modified by setting the animation scaling factor in the main method: public static void main(String args[]) { new Lab4().run(WINDOWED,"Lab 4 - Lighting",0.01f); } where the value,0.01f,is the value of the animationScale field in the GraphicsLab base class.If the rotation is too slowon your computer make this number bigger;if it is too fast make CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 14 it smaller.Try to remember to use this in your coursework,since then we have a simple method to speed up or slow down your animation so it runs at a sensible speed on the computers we mark your work on!More on animation later. Experiment with moving the light about - what happens if you put the light on the other side of shape (i.e.along the negative z axis)? Change the material properties of the house to simulate the walls being whitewashed (hint: you should only change the material properties). Change the lighting so that it simulates a sodium(orange) street light at night;do not change the material properties. Change the lighting and materials so that the house seems to be by the sea (i.e.bright light) and is painted yellow. If you have time,try to add a door to the house (this will simply be a rectangle with different material properties;choose any colour you like.Remember to start with pencil and paper. Lab 5:Quadrics and textures in OpenGL In this lesson you will learn how to use textures (bitmaps that are applied to objects to enhance detail without adding greatly to the complexity of the geometry) and quadrics.Quadrics are widely used in OpenGL to define objects that are curved (in reality of course they are simply made up of many small polygons),so they are great for spheres,cylinders,cones and disks. Open the Lab5 project and run it.What do you notice? We’ll start with the most dramatic change;the use of textures.In practice we have hidden much of the complexity of using and applying textures in the GraphicsLab base class – you can take a look,but I don’t advise you to change things here!The code to load the textures from file is in the initScene method: //load the textures groundTextures = loadTexture("Lab5/textures/grass.bmp"); This loads the texture from a bitmap called grass.bmp in the Lab5/textures directory. Take a look at the raw texture – i.e.open the bitmap in the default viewer (e.g.paint).What do you notice? In general I suggest you stick to using bitmap formats for your textures and keeping them square with a dimension of 2 n 2 n ,e.g.128 by 128 or 512 by 512.Other sizes should work with OpenGL but you cannot guarantee this for all hardware.The texture then needs to be applied to the polygon in the renderScene method: //draw the ground plane GL11.glPushMatrix(); { //disable lighting calculations so that they don’t affect //the appearance of the texture GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); GL11.glDisable(GL11.GL_LIGHTING); //change the geometry colour to white so that the texture //is bright and details can be seen clearly Colour.WHITE.submit(); //enable texturing and bind an appropriate texture GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glBindTexture(GL11.GL_TEXTURE_2D,groundTextures.getTextureID()); //position,scale and draw the ground plane using its display list CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 15 GL11.glTranslatef(0.0f,-1.0f,-10.0f); GL11.glScaled(25.0f,1.0f,20.0f); GL11.glCallList(planeList); //disable textures and reset any local lighting changes GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glPopAttrib(); } GL11.glPopMatrix(); This code might seemquite complex at first glance;there is certainly a lot going on here.First and push-pop pair isolate any transformations applied to the ground plane. Then we see a new use of push and pop,this time on the attribute stack.Using GL11.glPushAttrib(GL11.GL LIGHTING BIT) we are able to tell OpenGL to store (push) the current lighting settings on to the attribute stack.This enables us to save the set- tings,and recover them later.We then turn the lighting off,using glDisable() and set the background colour to white (so the texture is drawn cleanly).Only then do we apply the texture,first enabling the use of 2D textures and then finally binding the texture using GL11.glBindTexture(GL11.GL TEXTURE 2D,groundTextures.getTextureID()) – this is then applied to all polygons that followand have defined texture coordinates,so after drawing the suitably transformed ground plane we have to remember to disable the texture and retrieve the old lighting settings fromthe attribute stack.In this example we have not used lighting and textures together,but we will show you how to do this later. The only thing that remains is to link the textures to the geometry in the scene: private void drawUnitPlane() { Vertex v1 = new Vertex(-0.5f,0.0f,-0.5f);//left,back Vertex v2 = new Vertex( 0.5f,0.0f,-0.5f);//right,back Vertex v3 = new Vertex( 0.5f,0.0f,0.5f);//right,front Vertex v4 = new Vertex(-0.5f,0.0f,0.5f);//left,front //draw the plane geometry.order the vertices so that the plane //faces up GL11.glBegin(GL11.GL_POLYGON); { new Normal(v4.toVector(),v3.toVector(),v2.toVector(), v1.toVector()).submit(); GL11.glTexCoord2f(0.0f,0.0f); v4.submit(); GL11.glTexCoord2f(1.0f,0.0f); v3.submit(); GL11.glTexCoord2f(1.0f,1.0f); v2.submit(); GL11.glTexCoord2f(0.0f,1.0f); v1.submit(); } GL11.glEnd(); ... Here we link the texture coordinates to the vertices of the ground plane object.We need to remember to do this for all objects that we want to draw with textures attached.Again you will need to get paper and pen out to check that the attachment is correct.In general square textures are most easily applied to rectangular objects;we will not treat more complex cases here,although there are plenty of examples on the internet. Using textures is really quite simple.Notice at the moment that the sky is rather bland (indeed it picks up the last material properties defined;in this case the materials applied to the roof. We have supplied a file in the Lab5/textures directory called daySky.bmp. Modify the code to load this and apply it to the sky plane. We have also supplied a file called nightSky.bmp - apply this to the sky plane instead and adjust the lighting to make the appearance more realistic (make sure you turn the sun into the moon - make it white,not yellow). To make the moon appear to glow you need to set the GL EMISSION material property – this causes the object to appear to emit light,useful for objects you want to glow.Hint:don’t forget that OpenGL is a state machine;once you set the GL EMISSION property it will apply to all objects unless you turn it off. If you are not sure how to use emission then you an check the manual,but it follows the pattern of other material properties. The other new feature is the use of quadrics;there are several we can use,and LWJGL wraps these nicely.The sun in the scene which looks like a sphere is drawn using a quadric: new Sphere().draw(0.5f,10,10); The call to the draw method of the Sphere class takes three parameters;these are the radius of the sphere in world coordinate units (in this case 0.5 units),and then the number of slices CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 16 (around the equator) and number of stacks (pole to pole) used to make up the sphere.LWJGL has reasonable documentation,so you can always explore the methods by accessing the Javadoc at. Change the size,and the number of slices and stacks to see their effect.In general it is not a good idea to have too many stacks and slices since this produces very complex geometry and will slow down the application. We’ll explore other quadrics later,but for now this illustrates how easy they are to use. How could you change the sun to be rugby ball shaped?Hint:no need to change the quadric;use transformations. One important point to note is that if you want to use quadrics they need to be imported at the top of the class file: import org.lwjgl.util.glu.Sphere; Just to check you are following the placement of objects in the scene use the x,y and z keys to view the plan views of the scene.Do you understand these? Lab 6:Animation in OpenGL In this lab we will show you how to construct animations,using all the features we have seen thus far. Open and run the Lab6 project.There is quite a lot going on in the scene,indeed everything we have covered thus far is applied. Looks at the world model using the plan views. The model now has several additional features;a tree has been created using quadrics: Look at the code – in particular look at the parts used to create the tree – make sure you understand this. The code is much more complicated (at least in terms of the number of lines),but does not have anything substantially new.Note that we now have more fields;these are being used to store ID’s for display lists,and variables used to control the animation. The animation is quite simple;the moon can set and rise. Press the l key to lower the moon – can you see in the code how this happens? In this example the animation is driven by user input:when the user presses the l key the boolean risingSunMoon field is set to false (it starts being set to true,i.e.at the start of the programthe moon has aleady risen).The checkSceneInput() method is used to monitor the user interaction with the code: protected void checkSceneInput() { if(Keyboard.isKeyDown(Keyboard.KEY_R)) { risingSunMoon = true; } else if(Keyboard.isKeyDown(Keyboard.KEY_L)) { risingSunMoon = false; } else if(Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { resetAnimations(); } } The other options are to press the r key to make the moon rise,and the space bar to reset the CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 17 animation.If the l key is pressed then in the updateScene method we check to see whether the moon should be rising or setting,and the setting (falling) option will be chosen: protected void updateScene() { //if the sun/moon is rising,and it isn’t at its highest, //then increment the sun/moon’s Y offset if(risingSunMoon && currentSunMoonY < highestSunMoonY) { currentSunMoonY += 1.0f * getAnimationScale(); } //else if the sun/moon is falling,and it isn’t at its lowest, //then decrement the sun/moon’s Y offset else if(!risingSunMoon && currentSunMoonY > lowestSunMoonY) { currentSunMoonY -= 1.0f * getAnimationScale(); } } In the above code there are two possibilities;the moon should be rising,or falling.These are determined fromthe boolean value and whether the moon has yet reached its maximumor minimumelevation.If this is not the case the currentSunMoonY is incremented/decremented by an amount scaled by the animationScale to control the overall speed of the animation,as described in Lab4. Change the speed of the animation so it runs fast (e.g.change the scale in the main method run call to 1.0.Make it too slow.If you scale all the animations you script with a single scale then you can easily adjust the overall speed. Press the space bar to reset the animation. It is very useful to be able to reset the animations,so you should try and include this in your coursework.Here it is quite simple and achieved in the call to the resetAnimations method: private void resetAnimations() { //reset all attributes that are modified by user controls //or animations currentSunMoonY = highestSunMoonY; risingSunMoon = true; } which simply resets the animation variables to their initial values. Most animations are achieved by changing transformations applied to objects.In this simple example the animation is directly controlled by the user.In general this method of scripting animations is good in terms of allowing the user to have control over what happens,and when. However,it is often better to have a timer running and script animations as a function of the time (this is show in the extension labs).It is important to realise that animation can also involve lighting,materials and other properties.Combining all these allows some sophisticated effects to be achieved,and this is the aim of the coursework. Modify the animation so that when the moon sets the lighting gets even darker.Hint:you’ll need to change the lighting properties;there are several ways to do this – I’d probably create a turnOffMoonLight method that changes GL LIGHT0 to have simply a very low ambient level. Now allow the user to get the sun to rise by pressing the s key (this should only work if the moon has set).Hint:again you’ll need to change the lighting,the materials of the sun/moon, and ideally also the sky texture.This is quite complex and should take some planning and time. If you want a real challenge try to create a complete story by using a time variable to script the rise and fall of the moon and sun.To make it really realistic you should ideally use sine and cosine functions for the gradual changes in lighting levels as the various celestial bodies rise and fall.Only attempt this if you have time! It is a significant challenge;come back here if you have looked at the extension labs and understood what is there first. CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 18 Extra labs:useful examples in OpenGL These extension labs are designed to showyou a variety of different aspects of using OpenGL; they should be very helpful in the coursework.There is less to do here,but you must spend some time looking at them(the comments should be helpful!),and it is worth attempting some of the exercises. Solar System Select and run the SolarSystemlab. This example shows the application of simple time scripted animation of the Earth and Mars (with their moons).Note the x,y,and z keys still work if you want to see what is going on. Key features of this example are the use of glPushMatrix/glPopMatrix to construct a hier- archical scene graph (or equivalently isolate the transformations appropriately).For example we want the Earth’s moon to orbit around it (thus this is a child element in the scene graph and the Earth’s rotation is also applied to the Moon) Look at the scene graph for the code and the renderScene method - it is well commented; make sure you understand why the animation works as it does and why the glPushMatrix/ glPopMatrix are sited as they are. The other important aspect is the use of single time variable,timeday,to construct the anima- tion.Note this variable is used in all the transformations in the renderScene method. Make sure you understand the various rotations in the renderScene method;can you explain the units of time? Add Mercury and Venus;I have no idea how fast these orbit (or whether they have moons) but a quick internet search should reveal the answers! Borg Cube Select and run the BorgCube lab.Anthony is very proud of this so make sure you go WOW! 1 This example shows the use of lighting and textures and animation.The actual lighting that is 1 Anthony isn’t teaching the labs anymore,but we’ll pass the word on to him! changed in the animation is the emission property that makes the cube appear to glow with different intensities as it rotates. Take a look at the code and make sure you understand it;again the comments are pretty self explanatory. Modify the code so that the Borg cube can spin off into the distance (it will disappear behind the sky plane quite fast but you can fix this).This is quite a simple exercise. If you are feeling adventurous try to make the cube accelerate away.Note that if an object has constant acceleration a,then the velocity at a time zero will be v = 0 and for times in the future v = at,so the distance travelled,d,(i.e.the offset) will be d = at 2 . Animated Person Select and run the AnimatedPerson lab. Figure 6:An overview of the Person and associated classes. This example shows several features;for one there are several classes being used,shown in Figure 6.The example creates a Person object - note the constructor - take a look at the person class definition – there are two constructors available. CS2150 Computer Graphics Lab Notes:OpenGL (in Java) 19 Create a version of the person to mimic Dan (short and a bit wider than is ideal!). The main benefit of using other classes for objects in your scene is the hiding of complexity in these objects;if all the code for this example were in a single class it would be very difficult to read;here the person is responsible for creating and rendering themselves.The animation is all done in the main class,so it is easier to follow,but this could also have been delegated (indeed it might have been easier to follow if it had). Can you get the person to wave (or make some other gesture)?This is quite challenging, so don’t try this unless you have time. Can you make the person look rather more realistic;either using more materials or maybe a texture or two?Again this is only for the dedicated! Summary These labs have taken you from a basic 3D Java application using OpenGL and LWJGL to a quite complex animation.We have covered a lot of material.I really want to emphasise two things: 1.Graphics requires that you use pen and paper;you need to start with the idea on paper; don’t try to hack the code.This means a scene graph and a sketch of the world space and the objects therein. 2.Feel free to extend what we have provided for you in undertaking the coursework;these labs are meant to provide examples that you can learn from;make sure you read the code and comments – this should explain most things! If you have any comments feed them back to us;that is the only way we can make things
https://www.techylib.com/el/view/boringtarp/computer_graphics_lab_notes_opengl_in_java
CC-MAIN-2018-09
refinedweb
11,560
62.27
Quickstart: Connect to your own Python code Use any back-end﴾s﴿ you like Anvil allows you to connect to Python code anywhere and make Python function calls directly from your app. Follow this quickstart to call a Python function on your own machine from an Anvil app. Create an app Log in to Anvil and click ‘New Blank App’. Choose the Material Design theme. Enable the Uplink Click on ‘Uplink’ in the Gear Menu : You’ll see this dialog: Click the green ‘Enable Uplink’ button. You’ll get a randomised id for your app. You can also use a ‘client’ Uplink key that only gives the permissions available to client-side code. You can use this to connect to untrusted code with a restricted set of permissions so your data remains secure. We’ll stick with the server key for this quickstart. Install the Uplink library On your own computer, install the Uplink library (ensure you have Python installed). pip install anvil-uplink Connect a Python script to your app Create a file called hello.py with the following contents: import anvil.server anvil.server.connect("<your Uplink key>") @anvil.server.callable def say_hello(name): print(f"Hello from your own machine, {name}!") anvil.server.wait_forever() Replace the "<your Uplink key>" string with the Uplink key from your app. Run the script. You should see output like this: Connecting to wss://anvil.works/uplink Anvil websocket open Authenticated OK Call your local function from your app Back in the Anvil Editor, close the Uplink dialog and click on the ‘Code’ tab to see the Python code for Form1. You will see a few lines of pre-written code. Your Form is represented as a class called Form1. It currently has only one method, the __init__ method. At the end of the __init__ method, write this line: anvil.server.call('say_hello', 'Anvil Developer') Run your app Now click the ‘Run’ button at the top of the screen. Go back to where your script is running. It should have printed this message: Hello from your own machine, Anvil Developer! You’ve successfully connected your own machine to your Anvil app. Copy the example app Click on the button below to clone a finished version of this app into your account. This gives you power A script that runs anvil.server.connect() can do anything an Anvil Server Module can. It can: - call functions in your Anvil Server Modules or in any other Uplink-connected script, using anvil.server.call - use Data Tables directly - check which user is currently logged in You can use the Uplink to connect to any environment that runs Python. That includes Jupyter Notebooks. This means you’re not limited by what Anvil provides - you can do anything you can do on your own machine, and use Anvil’s features wherever they make life easier. Many people use Anvil as an add-on to their existing systems, to provide a UI or simple email client, for example. You’re not even limited by what Python can achieve - a Python process makes the Uplink connection, but since Python can make system calls, you can launch any process you like from your Anvil app (great for automating machinery or running automated tests!) Next up Want more depth on this subject? Read more about connecting your app to any external Python code. Want another quickstart? Every quickstart is on the Quickstarts page.
https://anvil.works/docs/uplink/quickstart.html
CC-MAIN-2020-29
refinedweb
571
74.49
According. For example, while learning to code, it goes without realizing that you made a few mistakes. Sometimes, you aren’t aware that you’re committing errors and leaving gaps in your programs. It also reflects that you are taking it easy. Whereas learning to program is a tough task, everyone will accept who’s done it. But the good part is that you can learn from the mistakes. You can take them as opportunities to grow. So, you shouldn’t be ashamed if you made one. In fact, each mistake leaves an important lesson to learn that you carry till you become an expert. And a good programmer never runs away, instead accept them as milestones in his path to development. Nonetheless, in this article, we’ve laid down a few of the Python programming mistakes and tried to give a solution for each of them. To begin with, you can go through the following checklist to help you avoid basic Python programming mistakes. It lists some of the key elements of a program/application and lays down a few points for improvements. - Identifiers: Make sure all your identifiers are meaningful. Avoid single letter and names like temp/flag. - Modularization: Split up logic using functions and classes. Don’t reinvent a library routine. - Formatting: Careful while indenting your code in Python. Use spaces instead of tabs and follow a consistent indentation pattern. - Comment Vs. Docstring: Python supports Docstring. It’s more convenient than using traditional comments. Make sure all your functions have a Docstring. - Code Analysis: Run a tool like PyLint on your code. It helps catch low hanging fruits like undefined vars, basic typos, un-used code, etc. - Unit Tests: Don’t miss to unit test your code. Use test modules like <unittest> or <unittest.mock> and deliver a dev tested code. - Code Profiling: Never guess the unknown, instead find them. Add modules like <timeit> or <cprofile> to locate hidden issues in your code. If you are a keen learner and wish to excel in Python programming, then do follow the below two posts as well. Now, check out the TOC (table of content) to flip through the list of common Python programming mistakes. 1. Ignorant of Python Scoping Rules (LEGB). 1.2 LEGB Rules. 1.1. LEGB Example. 2. Misconceive Identity as Equality. 3. Irrational use of Anti-patterns in your code. 3.1. Use of Java styled getter and setter functions. 3.2. Irregular use of Spaces with Tabs. 3.3. Underutilization of Python’s exception block. 3.4. Return inconsistent type values from functions. 3.5. Incorrect type checking. 4. Imports leading to circular dependency. 5. Misusing the <__init__> method. Let’s now review the common mistakes and the actions you should take to fix them. Common Python Programming Mistakes to Avoid. 1. Ignorant of Python Scoping Rules (LEGB). If you aren’t aware of Python scoping rules, then there is a high probability of you making mistakes. It’s because Python uses a little different approach for scoping variables than other programming languages. For example, it allows accessing the variables declared inside loops or if statements from outside. It could be a bit confusing for someone coming from a C/C++ background. Here is a sneak overview of the Python Scoping Rules a.k.a. LEGB. - L – stands for Local. It encompasses (identifier/variable) names specified within a function (using def or lambda) and not declared using the global keyword. - E – stands for Enclosing function locals. It includes a name from the local scope of any/all enclosing functions (for example, using def or lambda). - G – refers to Global entities. It includes names operating at the top-level of a module file or defined using the global keyword. - B – refers to Built-ins. It spans names that are preassigned as built-in names such as print, input, open, etc. The LEGB rule specifies the following order for namespaces, meant to be used for searching the names. Local -> Enclosed -> Global -> Built-in. Python LEGB Rules At a Glance. So, if a particular <name->object> mapping isn’t available in the local namespaces, it’ll then be looked up in the enclosed scope. If it doesn’t succeed, then Python will move on to the global namespace, and carry on searching the Built-ins. If it fails to find the name in any namespace, then a NameError will get raised. To understand LEGB rules in detail, consider the below example. It showcases the practical usage and impact of the Python scoping rules. In this example, we’ve used four functions to demonstrate the application of scoping rules in Python. LEGB Example. 1. Function: <access_local()> – It uses a local variable named as “token” (which also exist in global namespace) and initializes it with some value. Then, it queries the local and global namespaces to confirm its presence in both of them. And finally, print the “token” variable to make sure that it isn’t referencing the global variable. 2. Function: <access_enclosed()> – It has a for loop and initializing the token variable inside the loop. Then, it checks the global namespace that it includes the token variable too. Next, it prints the value of the token variable, which is the value set in the enclosed for-loop. It proves that variables defined in enclosed scope have a higher precedence than the global variables.Function: <access_global()> 3. Function: <access_global()> – In this function, first, we are confirming the presence of token variable in global namespace. And then, printing its value which remains same as we’d set at the onset i.e. at the global level. 4. Function: <id()> – Here, we’ve created our own definition of the built-in “id()” function. And as per the LEGB rules, built-ins have the least precedence. So whenever we call the “id()” function, Python will refer the one available in the global namespace. 5- NameError – As said above, the use of an undefined variable throws the NameError. You can see that happening with the last statement of the below code. In that line, we tried to print “token1” which resulted in the error. Sample Code. token = 'global' def access_local(): token = 'local' if 'token' in locals() and 'token' in globals(): print("Yes, token is in both local and global scope.") print("But value of token used is = (" + token + ")\n") def access_global(): if 'token' in globals(): print("Yes, token is in global scope.") print("Value of token used is = (" + token + ")\n") def access_enclosed(): test = 1 for test in range(5): token = 'enclosed' pass if 'token' in globals(): print("Though, token is in global scope.") print("But value of token used is = (" + token + ")\n") def id(token): return 1 access_local() access_enclosed() access_global() print("%s = %d\n" % ("token length", id(token))) print(token1) Here is the output of the above Python code. To interpret the below result, please refer the description given in the example. Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux Yes, token is in both local and global scope. But value of token used is = (local) Though, token is in global scope. But value of token used is = (enclosed) Yes, token is in global scope. Value of token used is = (global) token length = 1 Traceback (most recent call last): File "python", line 27, in <module> NameError: name 'token1' is not defined 2. Misconceive Identity as Equality. Another common mistake that Python programmers commit is by mistaking <is> for <equality> while comparing integers. Since Python uses to cache integers, so they may not get aware of this error. To grasp this concept, let’s consider the following two examples. Example-1. In the first example below, we’ve used two variables named as <sum> and <add>. And each of them stores the sum of two integers. Then, we are comparing the two variables with equality (==) operator. It’ll return true as both the variables hold the same value. Next, we are testing them using the identity (“is”) operator, but that too returns true. The reason is Python allocated the same address for both of them. You can confirm it from their id values printed at the end. But the programmer didn’t realize how come the two distinct operations (“==” and “is”) yield the same result. And did the mistake unknowingly. Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux sum = 10 + 15 => None add = 5 + 20 => None sum == add => True sum => 25 add => 25 sum is add => True id(sum) => 25625528 id(add) => 25625528 However, it’s going to cost him in the next example. Example-2. In this example, we’ve considered long integers to use. The catch here is that Python only caches integer between -5 to 256. Whereas the large numbers do occupy their separate boxes to sleep. Hence, while matching large integers with the identity (“is”) operator wouldn’t yield the same result as you saw in the previous example. 300 + 200 is 500 => False 300 + 200 == 500 => True The takeaway here is that the programmers should pay attention to the concept first before making blind use of any constructs. However, you can read more on how Python deals with integers and voice any doubts in the comment box. 3. Irrational use of Anti-patterns in your code. In general, an anti-pattern is a design approach to a commonly occurring problem that tentatively solves it but with possible side-effects. Here, we are discussing a few of Python anti-patterns that programmers may tend to use while coding. 3.1. Use of Java styled getter and setter functions. It’s often in Java termed as a best practice to define get/set functions for accessing members of a class. And you can see this pattern being applied in applications using Java Hibernate Framework. On the contrary, such a use of functions in Python leads to extra code with no real benefit. Anti-pattern example: Implement a Python class in Java-style. What’s best for Java does not eventually be the same for Python. So if you are from Java background, you must cautiously think the way things work in Python. class Employee(object): def __init__(self, name, exp): self._name = name self._exp = exp # Java-style getter/setter def getName(self): return self._name def setName(self, name): self._name = name def getExp(self): return self._exp def setExp(self, exp): self._exp = exp emp = Employee('techbeamers', 10) print("Employee-1: ", emp.getName(), emp.getExp()) emp.setName('Python Programmer') emp.setExp(20) print("Employee-2: ", emp.getName(), emp.getExp()) Approach-1: How should you do it in Python. In Python, it’s alright to access or manipulate a class member directly. And, usually, the use of protected or privates is scarce in Python. The members in Python are also public by default until you prefix them using <_> or <__>. This way, you can just emulate them to behave like protected (with _) or private (with __). Python obfuscates the names of variables starting with the <_> or <__> prefix to alienate them from the code outside the class. You should see the code below after we removed the get/set functions. class Employee(object): def __init__(self, name, exp): self.name = name self.exp = exp emp = Employee('techbeamers', 10) print("Default: ", emp.name, emp.exp) emp.name = 'Python Programmer' emp.exp = 20 print("Updated: ", emp.name, emp.exp) Approach-2: Use built-in <property> to work like get/set functions. In some situations, when it’s mandatory to hide the members, then you can use the property decorators to achieve getter/setter functionality. That’s how you can modify your code. class Employee(object): def __init__(self, exp): self._exp = exp @property def exp(self): return self._exp @exp.setter def exp(self, value): self._exp = value @exp.deleter def exp(self): del self._exp emp = Employee(10) print("default: ", emp.exp) emp.exp = 20 print("Updated: ", emp.exp) 3.2. Irregular use of Spaces with Tabs. The PEP 8 guidelines affirm that Python code should consistently use four spaces for indentation and probit using tabs. Though, it’s just a piece of rules which no standard Python engine enforces. But that’s the way you should follow to make your code manageable and error free. Anti-pattern example: Spaces mixed with tabs. Here is a piece of Python code holding a class indented with tabs and two methods, one is using spaces and the other one has tabs for indentation. The code runs fine on execution but misses the PEP 8 guidelines. # indented with tabs class Sample: def record_sample(): # indented with spaces print("Recored the sample!") def list_sample(): # indented with tabs print("Listed the sample!") Refactored: Convert Tabs to Spaces. The solution is to refactor your code to convert the tabs into spaces. There are many ways to do it. 1. You can edit the settings of your text editor and set it to insert four spaces instead of a tab. 2. If you are on Linux and using VIM, then use the <:retab> command to do the job for you. It’ll swap tab with no. of spaces defined in the tab settings. 3. You can also run the script <reindent.py> for auto-indentation. You can find it under the path <Python install dir>Tools\Scripts\reindent.py>. # indented with spaces class Sample: def record_sample(): print("Recored the sample!") def list_sample(): print("Listed the sample!") 3.3. Underutilization of Python’s exception block. While learning or adapting to a new language, we do consider walking through the essentials but walk over the extras. However, we shouldn’t overlook a topic something like exceptions. Knowing and utilizing exceptions can make your application works even in exceptional conditions. Sometimes, we get to use them but in a way that’s never going to help us. Let’s look at one such example followed by a solution that guides on implementing exceptions efficiently. Anti-pattern: Not using exceptions at all. Below is an example of weak error handling. It’s just confirming for an obvious fact. But overlooking the following conditions. - What if “debug.log” exist, but there comes some error while removing it. The code will abort without any informative message from the application. - You won’t want to see your code dying on a step that doesn’t impact the rest of the execution. import os # Testing the obvious, while overlooking the EAFP principle. if os.path.exists("debug.log"): os.remove("debug.log") EAFP is a common slang often used by Python programmers. It stands for <easier to ask for forgiveness than permission>. It expresses a notion of using exceptions for handling errors relating to undefined variables or files etc. Solution: Use try-except to avert any eventuality. Here is the same code wrapped in a try-except block. It’s now in a format as per EAFP convention. Interestingly, the except clause is set to show the befitting error message. import os try: os.remove("debug.log") #Raised when file isn't available. except Exception, OSError: print (str(OSError)) #Output #[Errno 2] No such file or directory: 'debug.log' 3.4. Return inconsistent type values from functions. You should check if your function is returning a value of a type that its caller doesn’t expect. If it does, then better update that condition to raise an exception. Otherwise, the caller would always have to verify the type before processing it further. You should avoid writing such code as it leads to confusion and increases complexity. Consider the below example and the refer to the solution given next. Anti-pattern: Returning in-variant types. In the below example, the function get_error_message() returns error messages corresponding to an error code. But in the case of a non-existent error code, it returns None. It leads to ambiguous code which is hard to maintain. And the caller will have to check it explicitly. def get_error_message(code): if code == 200: return "ok" elif code == 404: return "not found" else: return None status = get_error_message(403) if status is None: print("Unknown error.") else: print("The status is {}".format(status)) Solution: Raise an exception for unknown values. The ideal approach for handling unexpected conditions is by employing try-except block and raise an appropriate exception. It also fits in such conditions because the function won’t return any data. So instead of returning any invalid or unknown value, better it throws an exception. You can refer the code below which is the updated version of the above example. Now it’s much cleaner and doesn’t require checking for an additional data type. def get_error_message(code): if code == 200: return "ok" elif code == 404: return "not found" else: raise ValueError try: status = get_error_message(403) print("The status is {}".format(status)) except ValueError: print("Unknown error.") 3.5. Incorrect type checking. Sometimes, the programmers use to call <type()> in their code to compare the datatypes. Instead, they should use <isinstance> for type checking. This method does even have the ability to identify a derived class object. Hence, it is the best choice for type-checking. Anti-pattern: Weak type-checking example. The below code would fail to match the type of <emp> with Employee class. Though, the programmer would have thought that it would work. class Employee(object): def __init__(self, name): self.name = name class Engineer(Employee): def __init__(self, name, exp, skill): Employee.__init__(self, name) self.exp = exp self.skill = skill emp = Engineer("Python Programmer", 4, "Python") # Bad if type(emp) is Employee: print("object emp is a Employee") Solution: Strong type-checking example. Here is the right way to perform type checking of an object. class Employee(object): def __init__(self, name): self.name = name class Engineer(Employee): def __init__(self, name, exp, skill): Employee.__init__(self, name) self.exp = exp self.skill = skill emp = Engineer("Python Programmer", 4, "Python") # Good if isinstance(emp, Employee): print("object emp is a Employee") 4. Imports leading to circular dependency. In Python, import is also an executable statement. Each import clause leads to the execution of a corresponding module. Also, any function or a class embed in a module doesn’t come to life until the related code (in def or class) gets executed. Hence, importing a module recursively may cause a circular dependency in your program. For example, let’s assume we’ve two modules mod1 and mod2. The mod1 has import call to load mod2. It contains the following code. # module mod1 import mod2 def mod1_func(): print("function in mod1") To understand the reason of circular dependency, let’s imagine the following sequence of code. 1. You load the mod1 from your main program. The main program will then read the mod1 and process it. Since it’s loading the mod2 on the top, so Python will get on to reading it next. 2. Till this point, Python has got in both <mod1> and <mod2> under the sys.modules object list. But <mod1> still hasn’t received any definition because Python is currently executing the <mod2> module. 3. Now, to make a case of circular dependency, let’s add an “import mod1” statement into the mod2 module. So while executing the “import mod1” call, Python will reference back to the empty mod1 object. 4. In this situation, any call to mod1 entities (def or class) from mod2 would result in failures. # module mod2 import mod1 # The below call would fail as a circular dependency side-effect. mod1.mod1_func() Solution. There can be two most likely solutions to the above problem. 1. Modify the program to eliminate the recursive imports. You can offload some functionality to a new module. 2. Another approach could be to displace the affected imports (mod2) to the tail of the calling module (i.e. mod1). Hence, relocating the “import mod2” call towards the EOF in module mod1 will resolve the circular dependency issue. 5. Misusing the <__init__> method. Just like constructors in C++, you’ve <__init__> method in Python. It automatically gets called when Python allocates memory to a new class object. The purpose of this method is to set the values of instance members for the class object. And it’s not a good practice to explicitly return a value from the <__init__> method. It implies that you want to deviate from the purpose of this method. If that is the case, then better you choose a different method or define a new instance method for what you wish to accomplish. Let’s establish the above fact with some examples. Example: Misusing the <__init__> method. In this example, the code is trying to return the work experience of an employee from the <__init__> method. But It’ll result in an error “TypeError: __init__() should return None”. class Employee: def __init__(self, name, workexp): self.name = name self.workexp = workexp self._avgsal = workexp*1.5*100000 # causes "TypeError: __init__() should return None". return self._avgsal emp = Employee("Python Programmer", 10) Example: Adding a new property to fix <__init__> error. To solve the above issue, we’ll move the desired logic to a different instance method. You can call this method once the class object is ready with initialization. class Employee: def __init__(self, name, workexp): self.name = name self.workexp = workexp self._avgsal = workexp*1.5*100000 @property # Relocated the logic for returning work exp to a new method. def getAvgSal(self): return self._avgsal emp = Employee("Python Programmer", 10) print(emp.getAvgSal) So that were a few Python programming mistakes and their solutions we wanted to share with you. However, the list is too big to fit in one post. So we’ll keep posting the useful 🙂 programming mistakes in future as well. Summary- Common Python Programming Mistakes to Avoid. Hello, we believe this post had a lot for you to learn and apply in your daily work. You may not use them directly, but you can still avoid making such mistakes in your code. Finally, if you’ve any such “Python programming mistakes” to share, then let the world know about it. Also, you liked the stuff discussed here, then don’t mind it sharing it further. Help us grow and grow with us. Best, TechBeamers In relation to inconsistent mixing of spaces vs tabs, that has been prohibited since Python 3.0 – you can use one or the other, but not both. If a file or other piece of source code includes a mixture, the compiler will raise TabError. This same behaviour can be requested in Python 2.7 by passing `-tt` on the command line (or just `-t` to get warnings instead of errors). Nice summary – these are definitely some of the key issues folks coming to Python from C/C++ are likely to struggle with. Note that the current `access_enclosed()` example isn’t actually creating a closure, as for loops in Python don’t define a new scope (generator expressions and, in 3.x, comprehensions, do, but that’s not applicable to the code at hand). Instead of a loop, that example needs to define a nested function, so that there are 3 scopes involved (inner locals, outer locals, globals). Thanks for putting up such a profound view. I’ll follow up with the recommendations made.
http://www.techbeamers.com/python-programming-mistakes/
CC-MAIN-2018-26
refinedweb
3,886
68.16
Hi Andrei, > The operational question is: should the package > name be net.eclipsefp.ocaml or something other ? I would suggest that the general prefix for all plugins from the project should be net.sf.eclipsefp.*, which is in accord with the usual Java / Eclipse conventions. Everything below can be structured freely by us. I would say, we should divide the packages roughly into subprojects, that means net.sf.eclipsefp.common.* - language-independent common stuff net.sf.eclipsefp.haskell.* - Haskell net.sf.eclipsefp.ocaml.* - OCaml etc. This means of course also changing all the existing stuff from using the de.leiffrenzel.fp.* namespace to using net.sf.eclipsefp.*. I think I will do that sometimes in the near future, but this is something that must be done careful (many ids etc. in xml files are affected) because it is so error-prone, so I will do it on an occasion where I have at least a free weekend ... It is also somewhat of a problem for people who have an older version, because installing the new net.sf.eclipsefp.* plugins and features may leave the old de.leiffrenzel.fp.* stuff in place, and they could interfere with each other. We will have to ask users to completely remove the old plugins when installing the new version. > ? Yes, you are right about the common structure. This follows also the recommendations of Erich Gamma and Kent Beck in their 'Contributing to Eclipse', which is, btw, a good read for details on Eclipse and Plugin Development. The base plugin contains usually branding, Welcome content (that is, stuff that gets displayed on the Intro pages) and other global configuration (like what is in the About dialog) for the plugins collected in a feature. The thing to keep in mind is that features are only a mechanism for servicing (that is, installing, updating, licensing), but contain no actual funtionality, not even icons. Once all plugins of a feature are installed, it is in principle unnecessary and unused in the workings of the Eclipse platform itself. It comes only into play again if you want to update/re-install/disable. But there is some global stuff, like about texts, icons, etc., which is not associated with a particular plugin, but rather with the bundle. And it is the convention to have these things in a plugin that has the same plugin id as the feature id of the corresponding feature. Some parts of the Eclipse platform (e.g. the About dialog) expect their configuration (about icons, about texts) in that plugin. I believe that these thing will be change in the future a little bit. Some of the plan items in the Eclipse project plans say that the configuration issues (branding) should be decoupled from the update issues (feature organization). But I don't know the exact details of the plans (they are usually hidden in some Bugzilla feature requests on the eclipse.org site). It is also often the case that you have not multiple plugins, but only one in a feature. (Where you have a small tool in one plugin but want to add a feature to make that plugin servicable.) In such a case, the natural thing wuld be to have an equally named feature and plugin, and you would then have the branding and the code both in the plugin. Another case where you need the base plugin is when you have not a feature for the Eclipse platform, but an RCP application (standalone Eclipse-based application). In that case you have some global things to implement (application runnable, basic workbench configuration) which also would have their place in the base plugin (not in the core/ui/... plugins), as it is more or less generic runtime stuff. > - I don't understand (or can't find) the > dependencies between plugins, sure they should be > specified somewhere ? They are declared in the plugin.xml. If you open the plugin.xml editor, there is a tab named 'Dependencies'. You must declare all plugins on which the plugin depends. Once you have declared a plugin A dependent on a plugin B, you can use all (public) classes and all extension points of B in developing the plugin A. > Besides, I don't know nothing about deployment, but > I'll worry about this later, and read about it. Most > of my reading material on eclipse is now dated (2.x), > and I hope it's not too different. No, there is not much difference in these things in Eclipse 3; but the support in PDE has somewhat improved. It is not a big issue and can be done easily later. (But it is needed whenever you want to make it possible for the user to use the Update Manager, and it is for instance also required at Yoxos.) Hope that explaines a bit :-) Ciao, Leif View entire thread
http://sourceforge.net/p/eclipsefp/mailman/message/1597781/
CC-MAIN-2015-32
refinedweb
810
72.05
#include <packet.h> #include <packet.h> List of all members. Single byte form of consolidated header message. Three byte form of consolidated header message. Data. Data formats. Data field. First byte. Functional addressing. Header type. Single byte form of consolidated header. Primary ID. Message ID high 3 bits. Message ID low 4 bits. In-frame response (IFR). Packet length. Normalization bit for in frame response (only valid with VPW). Priority Zero is highest priority, 7 is lowest. Physical addressing. Single byte header packet. Source address. Target address. Functional target address type. Addressing mode. Message type see HS3000, p. 254, table 6.
https://media.defcon.org/DEF%20CON%2012/DEF%20CON%2012%20presentations/Nothingface/html/unionotto__packet.html
CC-MAIN-2021-39
refinedweb
101
55.91
Hi All, Quick question regarding HTML. Is is possible to use simple mathematical functions such as division within html code? I am pulling a variable from a DB that gives me durartion in hours and i want to display it in working days. I.e Divide by 8. Is this possible in HTML or would i have to use JS or some server side scripting? Thanks in advance, M. Not possible with only HTML. Didnt think so, was just chancing my arm to see if any bright sparks out there could show me the light. Cheers for the quick response. M. There is no Maths in HTML. There is no Arithmetics, nor Algebra, nor Geometry. HTML is just a markup language. It transfers and displays some text and picture in a document copied in user's browser and let the user to navigate from a web document to another using the Hyper links capabilities. It migh create, also, interactive forms. That is all. What you need is a programming language or at least a scripting language. There are 2 main classes of web programming languages: client-side/scripting (i.e : javascript) and server-side (i.e : php, asp, java, ... and the list is huge here). Client side javascript is dynamic and asynchronously, while server-side need the changing of the session. So... Which are your needs now? Last edited by Kor; 05-09-2008 at 04:44 AM. KOR Windows Forum Register as or Find a freelancer Offshore programming Let me give you some more information on what i am trying to achieve here: I am creating an email that pulls a figure from a DB and places it in my HTML based email. I.e "You worked 400 hours this month." Where the number 400 is pulled from the DB. However the figure is in hours and i want to display it in days (i.e divide by 8) I tried embedding JS but because Outlook displays emails as HTML the JS is never executed. I am about to try it by embedding php into the html but i have a feeling i will get the same result. I do not want to change the values in the DB before i pull them. Any thoughts? M. What pulls the information from the database Great wit and madness are near allied, and fine a line their bounds divide. I am using software that has prebuilt namespaces that i can call which are assigned to specific fields in the DB. So as such all that is called in html is something like: You have worked #HoursWorked# Hours M. Php didnt work either..... M. Show us the HTML part of the document Does the server you are runing on even support PHP? .. Last edited by Ballochio; 05-09-2008 at 06:18 AM. Where #ExpectedDuration# returns a number in hours and i want to divide it by 8. FONT is deprecated. use CSS. Give your span an id: Code: <span id="expDur" style="font-family:Arial;#Service.ExpectedDuration#</span> And in HEAD of the document you may use this javascript piece of code: Code: <script type="text/javascript"> onload=function(){ var txt=document.getElementById('expDur').firstChild; txt.nodeValue=txt.NodeValue/8; } </script> <span id="expDur" style="font-family:Arial;#Service.ExpectedDuration#</span> <script type="text/javascript"> onload=function(){ var txt=document.getElementById('expDur').firstChild; txt.nodeValue=txt.NodeValue/8; } </script> I tried JS before i posted. It doesnt work because the JS never gets exectuted because emails are sent in pure HTML. Oh, I see... It's an E-mail... In this case there is nothing you can do, except for transforming that #Service.ExpectedDuration# at a server level before sending the mail. There are currently 1 users browsing this thread. (0 members and 1 guests) Forum Rules
http://www.webdeveloper.com/forum/showthread.php?181038.html
CC-MAIN-2014-41
refinedweb
636
76.62
Member Since 4 Years Ago San Diego 3. virgiltu left a reply on Passing Object To Blade Vue @YEZAWHEIN - Thank it got me a bit closer but since I needed an object this was the answer {!! json_encode($products->inventory) !!} virgiltu started a new conversation Passing Object To Blade Vue I am trying to pass this object to blade via vue for v-for but I cant seem to be able to get the array to work. My View @{{ item.comment }} const app = new Vue({ el: '#app', data: { options: [{{ $products->inventory }}], }, export of $products->inventory [{"id":1,"products_id":13,"location":"Mentor","option":1,"value":1,"qty":4435,"comment":"435435sdfgsdgs","status":"","created_at":"2019-05-11 02:36:56","updated_at":"2019-05-11 02:36:56"},{"id":2,"products_id":13,"location":"Mentor","option":1,"value":2,"qty":4534,"comment":"resgdfgsdg","status":"","created_at":"2019-05-11 02:36:56","updated_at":"2019-05-11 02:36:56"}] virgiltu left a reply on Foreach In Blade Directive ? Never mind figured it out. virgiltu started a new conversation Foreach In Blade Directive ? Here is my issue. I have a list of modules in a database and I need to loop through them a lot. I am trying to figure out if there is a simple way to do this. I tryed a blade directive but it does not seem to work as it only seems to dump the txt and not the PHP. '''' @foreach ($content as $item) @if($item->section == 'home_text1') {!! $item->body !!} @endif @endforeach ''' Really simple if the the item is home_text1 than show value body. virgiltu left a reply on Blade Checkbox And Eloquent @JLRDW - I am guessing with laravel there is much much shorter way but this did get it to work. $manufacturer->drop_ship = (!request()->has('drop_ship') == '1' ? '0' : '1'); $manufacturer->import_only = (!request()->has('import_only') == '1' ? '0' : '1'); $manufacturer->status = (!request()->has('status') == '1' ? '0' : '1'); $manufacturer->save(); blade <input type="checkbox" name="status" data-plugin="switchery" data-color="#1bb99a" {{ $manufacturer->status ? 'checked' : ''}} > if anybody has a shorter way please let me know. I guess I could just pars this out into a function so I dont have to rewrite it. virgiltu started a new conversation Blade Checkbox And Eloquent I can do this as a longer version but I am sure there is a short way of doing this and I am missing it. In my database I have a table Manufacturer and one of the fields is status (boolean) Migration is set to boolean but the database saves it at 0 an 1 . When I try to edit the filed I set the boolean to checked. However that returns ON or OFF ending up in an error. My Blade checkbox input type="checkbox" name="status" checked data-plugin="switchery" data-color="#1bb99a" {{ $manufacturer->status ? 'checked' : '' }} > My Controller manufacturer::find($request->id)->update($request->all()); I know I could brake down each one but I have a lot of fields and there is no need to brake down the Request. All the help is appreciated. virgiltu left a reply on Elquent Relation To VUEjs actually i think i figured it out. Is this the correct option. @foreach ($options as $option) <option v- @{{ option.name }} </option> @endforeach virgiltu started a new conversation Elquent Relation To VUEjs I am trying to create a cascade drop down menu. The example is simple. Create an option lets say colors and add colors to it, blue red green etc. What I did. Create table for both options and value. Create a relation ship has many on the color side. now when I pull do : FYI using blade @foreach ($option->value as $value) {{ $value->name }} @endforeach I get Green, Blue , Red. - Great that works Now I am trying to create something like this. I figured out that I can pull my options in Vue by using this {!! json_encode($options) !!} however how can I iterate through each option so create the value for the second drop down. Thank you for all the help. I am still going through tutorials but this one is taking a lot longer that I would like and I honest gave up. virgiltu left a reply on Submitting Multiple Forms And Fields virgiltu left a reply on Submitting Multiple Forms And Fields Never mind I figured it out. name="option[0][option_image]" virgiltu started a new conversation Submitting Multiple Forms And Fields I am trying to recreate the functionality of this image. In short you can create an option and inside this option you can add more values. The code has a table named option and a table called values. Than there is a pivot table between the two. I am guessing this is the best option. In the create form you can keep adding values as you can see. My question is. How can I submit multiple value in the same from. I am guessing this will only be one form with extra value added as text and submitted once the entire from is sent. Maybe I am looking at this wrong. Just wanted to get some ideas. virgiltu left a reply on Laravel + Vuejs/Vuefire + Firebase +1 virgiltu left a reply on Firebase Not sure how to do it with freebase but I see that you can do it with mdbootrap. There is a free version and also the paid one. Search in the side is called brandflow . Honestly the push notification is simple and you get free ones but I still cant figure out how to use the vue version with Laraval. virgiltu started a new conversation How To Add Blade Slot In Vue? I am trying to minimize the amount of times I am using the new vue instance from my pages. I am building an admin panel that has multiple views but I am trying to keep the layout and just add what I need for vue from each page. Is this the best way of going about it? Again there are a few other pages and I am not sure if i should just keep putting the new vue on each one. My Layout page. <script> Vue.use(VueMaterial.default) new Vue({ el: '#app', @{{ vue }} }); </script> My home page @slot('vue') <script> data: { names: ['joe', 'mike', 'alex'] } </script> @endslot virgiltu left a reply on App For IPhone/iPad To be honest I can see a really good use for it. I hate that I cant download the entire play list to watch on the plane. Yes I fly a lot and I see others watch programming tutorials on Udemy. Currently I have to use a YouTube to mp4 and than to load them on my iPad. Y ipad or tablet you ask? Because we don’t have to wait to get till 10k feet in order to watch and I don’t have to pull a bulky laptop out. In any case I really hope we get something at some point. virgiltu started a new conversation How To Set One Picture To Default ? I have been trying to figure this out for about a day and a half now. I am trying to upload images with something like dropzone js, as it seems to be working well with vue. However how can I set one of the images as default? Lets say that I upload 5 images but only one need to be default. Also i am loading all of them in a database as json_encode. So result will be something like this. { "default": "main1.jpg", "images": { "img1": "image2.jpg", "img2": "image3.jpg" } } virgiltu started a new conversation "php Artisan Migrate" Works But Not Website I cant seem to figure out y the php artisan migrate works but not the website. Under the website i get the nice SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) Obvious i have it set correct under the .env as the migration works I also did php artisan cache:clear with no luck. Is there another command i should be doing here to get it to refresh. Background:: I had another server running and it worked before. I had to update the version and now because I have a password it does not seem to work. If i removed the password from the server it seems to work. Somewhere it seem that my .env file is getting from cache or something. I very much appreciate it. virgiltu left a reply on Json Data Type Failing In Migration So I finally found a resolution. Just install MariaDB 10.2 from the website and since my host still runs 10.1. Amazon E2 has a free instance of MariaDB 10.2 and MySQL 5.7 that support JSON. This is till a temp solution till a solid MongoD solution is made for laravel. Thank you all for the ideas. I just hate a work around. virgiltu left a reply on Json Data Type Failing In Migration Cronix, you are correct. Sadly I need that as I am looking to store Images links and some product specification. I know that I can do separate tables in this case as the user should be able to filter products by some specifications. Not my favorite. I am actually looking at some MongoD drivers that I found. But I think I need to dive more into Laravel before I move to that. virgiltu left a reply on Json Data Type Failing In Migration Multumesc Sergiu virgiltu left a reply on Alternative To Json Date Type? Or maybe I am doing something wrong. Anybody has any idea y the migration is failing? This is my server Information. Database server Server: 127.0.0.1 via TCP/IP Server type: MariaDB Server version: 10.1.31-MariaDB - mariadb.org binary distribution Protocol version: 10 User: [email protected] Server charset: UTF-8 Unicode (utf8) Here is my migration $table->increments('id'); $table->string('productName'); $table->string('slug'); $table->text('description'); $table->decimal('price', 8,2); $table->decimal('dicountPrice', 8,2); $table->tinyInteger('discount'); $table->text('tags'); $table->unsignedTinyInteger('storeID'); $table->unsignedTinyInteger('rating'); $table->boolean('status')->default(true); $table->json('specs')->nullable(); $table->json('images')->nullable(); $table->decimal('shippingPrice',4,2); $table->boolean('freeShipping')->default(false); $table->json('comparison')->nullable(); $table->json('moduless')->nullable(); $table->timestamps(); Here is the error Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'json null, `images` json null, `shippingPrice` decimal(4, 2) not null, `freeShip' at line 1 (SQL: create table `admin_products` (`id` int unsigned not null auto_increment primary key, `productName` varchar(191) not null, `slug` varchar(191) not null, `description` text not null, `price` decimal(8, 2) not null, `dicountPrice` decimal(8, 2) not null, `discount` tinyint not null, `tags` text not null, `storeID` tinyint unsigned not null, `rating` tinyint unsigned not null, `status` tinyint(1) not null default '1', `specs` json null, `images` json null, `shippingPrice` decimal(4, 2) not null, `freeShipping` tinyint(1) not null default '0', `comparison` json null, `moduless` json null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci) virgiltu started a new conversation Alternative To Json Date Type? Since json is not support in most MySQL installations is there another way to storing Json ? Can I store it as txt? would that be an acceptable solution? *really wished laravel supported MomgoDB out of the box. what a pain is to deal MySQL and relational tables. virgiltu left a reply on Move Outside Php Trust me I know the question was stupid. But as I said before, I was more interested into the non blocking IO. But as somebody here said, I can just build that part of the app in node as an API. Thanks for all the responses. virgiltu left a reply on Move Outside Php My question was more pointed to the async functions and the ability to handle a much larger number of requests than php can. virgiltu started a new conversation How To Make A Menu Menu With Data From The Database I am going through some video and I am bit lost. Any help will be appreciate it. I understand the concept of routes > model > controller and views. So if I have a view I will pull data from a controller and model via a route. However if I have a view that @yields a header that includes a menu. How can I make the menu item data available to the header at all times and only calling it once. I cant imagine that I have to constantly call the database to pull the menu items in each controller and push it to the view. Is there a way for a yield section to pull its own data? My guess is that I did not go into the tutorial videos far enough. virgiltu started a new conversation Move Outside Php Is there a plan for Laravel to ever move outside the php environment. Maybe something like phalconphp or under a nodejs system? virgiltu left a reply on Mongodb Support For Laravel Package I honestly left Laravel in favor of Node because of SQL about a year back. I mean at what point do people not realize the disadvantage of a database that was last updated in 2016. Lets throw more servers at it in order to scale is not a very price favorite or computation ideal move. I love laravel dont get me wrong, but I absolutely hate having to deal with SQL. Even presenting that to any of my customers puts me into an edge to lose a customer. If there is anything that any company is trying to walk way from is SQL. When the conversation comes about database, almost all customers say no to SQL, and there for a huge reason y laravel is never a an option for a project. In any case today was my first day back to Laravel in some time, and yes I paid for the subscription plan all this time. I was just in hopes to see some changes in the database department. Guess not. virgiltu started a new conversation Relationships With Eloquent I though that maybe I am doing something wrong, but after doing it numerouse times, I keep getting the same result. I am fallowing this video but I always get NULL when asking for $f->actors. Any ideas. <?php namespace App; use Illuminate\Database\Eloquent\Model; class Film extends Model { protected $table = 'film'; protected $primaryKey = 'film_id'; public $timestamps = false; public function actors() { return $this->belongsToMany(Actor::class, 'film_actor'); } } virgiltu left a reply on Trying To Get Property Of Non-object Thank you guys, I really appreciate the help. virgiltu started a new conversation Trying To Get Property Of Non-object This has to be a really stupid question but here it is. I have $category['id'] = 0; I am trying to pull it with this return $category->id; I know i can use $category['id'] but i need the above one so i do not have to reuse code. virgiltu started a new conversation Global Variable Or Middleware Maybe somebody can help me out so I dont have to rewrite a lot of code. I need to pull my categories from the db so :: $categories = categories::all(); Into the header so i dont have call this every time in all my controllers. Now my structure looks like this. header.blade.php - header Items -----< Trying to bring data from $categories = categories::all(); home.blade.php - Home page has header @yeld product.blade.php - Product Page has header @yeld category.blade.php - Category Page has header @yeld Thank you virgiltu started a new conversation Bug Found..... When creating an application, laravel keeps bringing up the cache file instead of the new file made. Lets say that you make a user.blade.php and you change it, after some time laravel will not update the cache file. I honestly went as far a removing everything from the file and laravel kept open it like nothing was wrong. It keep rendering the files from storage>framework>views I have been working on it for a few hours. I had to do a flush to get it to work again. Few hours later same issue. virgiltu left a reply on Fatal Error: Call To A Member Function Save() On Integer Thank you so much for the help. virgiltu started a new conversation Fatal Error: Call To A Member Function Save() On Integer Can somebody please tell me y this does not work. $product = products::whereSlug($slug)->firstOrFail(); //Update Views $product->increment('views')->save(); However this will work just fine DB::table('products')->whereSlug($slug)->increment('views'); virgiltu started a new conversation Laravel As PHP Extension Laravel is a great platform, but is there a reason this was not built like PhalconPHP as a PHP extension? I would only assume that it would skyrocket to the top of the Framework list for speed and friendliness. I like Phalcon a lot but the lack in documentation and videos just makes it really hard to understand how to get things done. virgiltu started a new conversation Updating Expiration Date In The Database Ok I know stupid title =). I am creating a website that has many products for sale. I need the prices of every product to update based on when they were posted. For example I have a product posted today at 12:04PM. What I want, is for the application to change the price every day at 12:04PM. I understand that a CRON will do that, however I am just trying to figure out if the server will take a toll trying to updated every price in the database. My best guess will be to write the cron every minute and pull the products that match the time and then update them. Will every minute be a huge issue? Or does anybody know of a better way? Also I am expecting to have a lot of products, i would say over 200k if not more. Thank you virgiltu started a new conversation Using Enum Before I go ahead and build a new table, i figured i would ask for some help. I have a field in MySQL table. shipping enum('Next Day', '2 - Days'); When I pull as set for my product I get "Next Day" {{ $product->shipping }} What I am looking to get is the 0, 1, 2. ....... and so on. Also what i cant figure out is how to get a list of all the enum items. In a form I can do this but what i need is to be able to pull these values from the database. The only ideas is to create a relational database. {{ Form::select('shipping', [ ''Next Day', '2 - Days'] ) }} virgiltu left a reply on Blade Text Output Never mind I guess i have to use an editor to get this done. virgiltu started a new conversation Blade Text Output Ok this is a stupid question. I know it but it is really irritating and I know i fixed it some time ago but now it is just not working. I am adding a text area to my form and the data imputed is something) However when i output it via {{ $product->specs }} or {!! $product->specs !!} i) Any idea how to fix this. virgiltu left a reply on Parsing Data, Helpers, To View Excellent, i understand now. virgiltu left a reply on Parsing Data, Helpers, To View That is understandable, i have been trying to do exactly that as you can see in my code above where each price is passed through and generated as the days array. However the issue I am having at that point is that i can only generate it for one product and not 100 products that i need to display. And that is where I got stuck. The view example above got me closer to what i was looking to do, however it seems that you can run any type of loops inside the helpers function as it will be run once for some reason. I know there is a faster and much more scream line way to do this. virgiltu left a reply on Parsing Data, Helpers, To View Is it me or can we not run for loops in the helpers file. I even tryed this and all i got was one result. for ($x = 0; $x <= 10; $x++) { $output = "The number is: $x <br>"; return $output; } The number is: 0 virgiltu left a reply on Parsing Data, Helpers, To View Thank you so much that is what i was missing, i knew some stuff just not close enough. the MSPR was the price of the item. virgiltu started a new conversation Parsing Data, Helpers, To View This might be a nube question. Here is my scenario. Trust me i have spend hour on this with no good results. My Controller is pulling Products:all() from the database. One of the fields in the database is the MSRP price of the product. What i need to is pull drop the price for 10 days as you can see in the picture here. I was able to do it for one product, but i cant figure out how to do it for all the product in the result and than push it to the view. I know this is a mess but here is what i have so far. This is my controller right now public function index() { $products = products::all(); $categories = categories::all(); return view('homepage',compact('products','categories')); } This what i would like to do with every msrp value $msrp = $product[msrp]; $dayposted = "2016-1-26"; $cDate = Carbon::parse($dayposted); $today = $cDate->diffInDays(); $days = []; $i = 1; $percent = 0; for($n=0 ;$n<10; $n++) { setlocale(LC_MONETARY, 'en_US.UTF-8'); if ($i == $today) { $day = array_add(['day' => 'Day '.$i], 'price' , number_format( $msrp * ((100-($i10))/100),2, '.', '')); $day = array_add($day, 'class', 'today'); $price = number_format( $msrp * ((100-($i10))/100),2, '.', ''); } elseif($i == 10) { $day = array_add(['day' => 'Final'], 'price' , number_format( $msrp * ((100-($i10))/100),2, '.', '')); $day = array_add($day, 'class', ''); } else{ $day = array_add(['day' => 'Day '.$i], 'price' , number_format( $msrp * ((100-($i10))/100),2, '.', '')); $day = array_add($day, 'class', ''); } array_push ($days, $day); $i++; } This is my view @foreach ($products as $product) @foreach ($days as $day) @if ($day['class'] == 'today')${{ $day['price'] }} @elseif ($day['class'] != 'today') ${{ $day['price'] }} @endif @endforeach @endforeach And this is what i am trying to achive virgiltu left a reply on Insert Array Of In Database I found a solution using just PHP unfortunately Laravel does not have these built in, using the serialize() and unserialize() functions. Thanks for the help. virgiltu left a reply on Insert Array Of In Database thank you, i was trying to avoid having to request a new table every time i send this request, i am going to look if maybe comma delimited will be the way to go. having to create a new table and search through all of them again seems overkill when i can just swift through the data i already have requested. unfortunately i am paying per request on this projects server so this will add a lot of cost for an extra request in the long term. but thank you for your response, it i much appreciated it. virgiltu started a new conversation Insert Array Of In Database I have a table named videos->watched , i am trying to insert the auth user id as an array in this column. the ides is simple the videos will be watched the controller will add to the array a new id, when the video gets updated the entire column gets dumped and it starts over. Any ideas how i could insert the array? Sadly eloquent seems to think that $array is part of the query and I get an error. Error: Call to a member function update() on integer Array: [{"0":"","user":1}] Code: $array = array(array_add([$watched],'user' ,Auth::user()->id)); DB::table('videos')->whereId($id)->increment('views')- >update(['watched' => $array]); virgiltu left a reply on New Installation Not Working. Hi Kazi, Here is my experience so far. I paid for the laracast videos. However, you will get stuck a lot. It all depends if you installed laravel 4 or laravel 5. To install laravel 5 you will need to install the from the -dev. In any case laravel 5 is much better and simpler in my opinion. However most of the videos you can not fallow. That is because they were made in an earlier version of the dev laravel 5. You have to find the latest videos in order to figure out how it works. And once you do that you will have to read the documentation. Dont get me wrong it is really fun. I hope this helps. O you will have to pay for laracast, because the laravel5 from scratch will not work on the latest released version. annotations is what is missing from the free videos. virgiltu left a reply on Module Import In HomeController So this is what I have so far but I still cant get it to work. I figured if I send the songscontroller to the homeview it will work but I dont think that it correct. HomeController ''' /** * @Get("/") * */ public function index() { $module = 1; return view('pages.home', compact('module')); } ''' HomeBlade @foreach ($songs as $index => $song) <li><a href="/cleardeals/public/songs/{{ $index }}">{{ $song }}</a></li> @endforeach @foreach ($products as $index => $product) <li><a href="/cleardeals/public/products/{{$index}}">{{ $product }}</a></li> @endforeach No Modules set SongsController ''' /** * @Resource("songs") * */ class SongsController extends Controller { /** * @return Resource * */ public function index() { $songs = $this->getSongs(); return view('pages.home', compact('songs')); } ''' ProductsController ''' /** * Display a listing of the resource. * * @Resource("products") */ class ProductsController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function index() { $products = $this->getProducts(); return view('pages.home', compact('products')); } ''' virgiltu started a new conversation Module Import In HomeController I am new so sorry for the stupid questions. I am trying to figure out how to bring some modules in the homeController like this. I have Products, Songs, Books in my database. I am trying to create three modules that will show the latest added in the sql. I have that figured out already. Now I want on my home page to get any of the three modules lets say based on when the variable module == 1 for Products or 2 for songs and so on. I have pages created and views for all these. But I can not figure out how to bring these views in my home page based when that variable. What am i missing or doing wrong. Is this done in the HomeController or in the View?
https://laracasts.com/@virgiltu
CC-MAIN-2019-22
refinedweb
4,465
71.85
Dear all, I am in the process of writing a new SUBTYPEP and TYPEP routines for ECL (A Common-Lisp implementation hosted at SourceForge,). I am almost there, but in comparison to other implementations, I have currently chosen to signal an error when the type specifier is not known to be a type to the system. My decision was inspired by 1) In the definition of SUBTYPEP, the two first arguments are said to be "type specifiers" = "an expression which denotes a type", according to the glossary. 2) A paragraph in the HyperSpec which states that, except for a few pathological cases (SATISFIES, AND, FUNCTION, ...), SUBTYPEP has to determine the type relationship precisely. However 3) In CLISP and CMUCL, when the arguments passed is not a valid type specifier, they both return (VALUES NIL NIL). 4) The ANSI specification says nothing about exceptional conditions in SUBTYPEP. I am wondering whether I should rewrite my implementation to follow "common use" or whether I have misinterpreted the HyperSpec. What do commercial implementations do? What would people find less annoying? To myself, that SUBTYPEP may signal an error has been useful in the last week, as it has pointed out a few errors in other parts of the code. Best regards Juanjo [Please forgive if I am not very responsive next week, but I will be abroad for some days]
http://sourceforge.net/p/ecls/mailman/message/4208564/
CC-MAIN-2015-06
refinedweb
227
60.85
Hi, everyone. I'm completely new to the forum and C++. This is my forth program for the c++ programming class. I don't have a clue what i should do to get my hand on this program. here it is: _________ You are to write a C++ program that will scan a text file and do some elementary analysis that might indicate how difficult the text is to read. In particular, your program will: 1. Determine the average length of all the words in the text 2. Find the longest word in the text and display it 3. Determin the average number of words in each sentence 4. Find the longest sentence and display it "Mr." is not an actual word. You are allowed to use while, if , else condition only, no For condition _________ This is what I got so far, I don't know what I should do next. Thanks,Thanks,Code:#include <iostream> #include <iomanip> #include <fstream> #include <string> using namespace std; int main() { string fileName; string getout; string words; int word_count; string space = " "; ifstream infile; bool run = true; while(run) { cout << "Please insert the file name: "; cin >> fileName; infile.open(fileName.c_str()); if (infile.fail()) { cout << fileName << " cannot be found." << endl; cout << "Please try again, do you want to quit? (y/n)"; cin >> getout; if (getout == "y") { cout << "You decide to stop the program \n"; return 0; } } else { while (run) { cin words; ____help___Please____ } } } return 0; }
http://cboard.cprogramming.com/cplusplus-programming/34268-how-do-i-do.html
CC-MAIN-2014-35
refinedweb
240
82.34
After Bug 171237 has landed is the behavior now that finding a new search result will always center the view to the result. This is a confusing behavior when the next result is only a few lines above/below the current result as it makes the user think he is presented with an entirely new section of text. +1 Moving the view port unnecessarily destroys the user's mental model of the displayed content. The view port should only shift and vertically center if the search result isn't currently visible.). If it is somewhere around the center, the shift would be distracting. (In reply to :aceman from comment #2) >). No, the bug summary and comment 0 clearly request that the content window not shift if the next result is visible. You could make the case that if the next result is close enough (say 5-10 lines) to the top or bottom of the window that the view port should center the next result for context, but you shouldn't shift the view port any more than absolutely necessary to avoid destroying the mental model of the visible content. From reading the comments I assume that smooth scrolling as enabled per default in bug 198964 for "find in page" would solve the commentators issues. By that one sees how far the next result is away from the current. For very long pages that could be an annoyance at least as long bug ug 710372 and bug 202718 are not fixed. Maybe this could be toggled in the find bar similar to "Highlight all". We're not going to add a preference for this, visible or otherwise. Only centering if the found element isn't already near the center seems like a promising possible approach. roc, do any of our existing ScrollIntoView flags do what we need here? (not scrolling if the element is already in the viewport) The closest option is NS_PRESSHELL_SCROLL_ANYWHERE which will scroll the whole target into view somewhere, but won't scroll at all if the target is fully visible. That's what we were using before. The problem is that we can't combine a percentage with NS_PRESSHELL_SCROLL_ANYWHERE. What we really need to be able to do is to separate the preferred scroll position percentage from the control over when to scroll. E.g. we could have, for each axis, -- mWhenToScroll: SCROLL_ALWAYS, SCROLL_IF_PARTIALLY_HIDDEN, SCROLL_IF_COMPLETELY_HIDDEN -- mWhereToScroll: percentage to center on When SCROLL_IF_PARTIALLY_HIDDEN or SCROLL_IF_COMPLETELY_HIDDEN are specified, we would first apply mWhereToScroll to choose a position and then adjust the position to ensure as much of the rectangle as possible is visible. It's probably a good idea to replace the PRIntn percentage parameters with a little struct with those two fields. My paint-the-bikeshed comment. Keep the current behavior to still center the new word *that is already visible*, but instead of jumping right there, change it to a slower scroll as not to "destroy the user's mental model of the displayed content" As a visual idea, think an iPhone if you put your finger on the new word and dragged it to the center of the screen. I think we should fix this before shipping bug 171237. I agree with comment #1. Unless the result of a subsequent Find is beyond the view port (above or below), the page should not reposition. However, I would also reposition the page if the result of a subsequent Find is within the top or bottom very few lines. If the subsequent Find is within the bottom 1-3 lines, opening a tab can cause those lines to be shifted out of the view port (see bug #658188). If bug #658188 is ever fixed, however, then the problem will be at the top few lines. I think comment 7 is a good idea. roc, do you know of anyone who can take this? I'm currently swamped so I can't do it myself, and I think without this we would need to back out bug 171237, which would make me a sad person... Just the usual suspects :-) I believe this feature is currently to-spec, so no need to track for release. If product/UX agree with the feedback and proposed changes (now CC'd), we can either disable the feature for another cycle or take a low-risk fix here. I don't think we want to ship this feature with this bug. Doesn't "back out or quick fix" mean tracking+? FWIW, this UX guy thinks this is actually a UX call. The bug was filed (appropriately so) about a UX issue, and so the question should be: do the benefits of the change (centering find results) outweigh the costs of jumping the page for every result. Allow me to be clear: I completely agree that a smoother scroll to the result is a better solution, or even one where we only jump if deemed necessary. I just also believe that the current behaviour in nightlies (ie: jumping) is a strong improvement over what's in our shipping code. Adding uiwanted, as I don't see why the UX group hasn't been asked to make a judgement call on what clearly seems like a UX issue! I'm on the same page as beltzner here. The product team will work with UX on coming to a recommendation. The feedback so far has been very helpful and highlights many of the concerns, but if comparing to the previous state per bug 171237, this does appear to be a much better experience (although still suboptimal). UX is cc'ed here so we should here from them soon. I was wrong, we don't need to block bug 171237 on fixing this issue. But we should fix this issue, because it's annoying :) Note that the original bug #171237 Summary (in 2002) indicated the need to see the context of the found term. Through several revisions of the Summary, this aspect -- providing space above and below the found term -- remained. No mention in the Summary was made about centering the found term until only a month ago. Repeatedly centering the found term when that term was already in the view port will be very annoying. Actually, it can be disorienting to the user. Created attachment 597952 [details] [diff] [review] WIP: Implementation along the lines of comment 7 This patch separates the where (percentage) and when of scrolling as suggested in Comment 7. At large: 1. Are the values used for consumers correct now that both when and where are specified? 2. Further tuning to ScrollToShowRect(). 3. Testing SCROLL_IF_NOT_VISIBLE and SCROLL_IF_PARTLY_VISIBLE. Inre [2]: The behavior is a bit refined. Currently items in view but more than 1/3 screen from ideal will cause scrolling to the middle of current and ideal. If within 1/3, it's left alone. This does help maintain context a bit better. The downside is if the next match is visible, but near the top, it may actually scroll up, which is a bit jarring. Same if jumping to previous matches near the bottom, it may scroll down while highlighting a higher-up match. Haven't found a good way to detect those cases, but will reexamine it. Comment on attachment 597952 [details] [diff] [review] WIP: Implementation along the lines of comment 7 Review of attachment 597952 [details] [diff] [review]: ----------------------------------------------------------------- ::: layout/base/nsIPresShell.h @@ +158,5 @@ > +#define NS_PRESSHELL_SCROLL_IF_PARTLY_VISIBLE -3 > + > +typedef struct ScrollContentParameter { > + PRInt16 percentageToScroll; > + PRInt16 whenToScroll; Use "m" prefix for fields. @@ +561,5 @@ > * value of 50 (NS_PRESSHELL_SCROLL_CENTER) centers the frame > + * vertically. > + * WHEN is one of: > + * NS_PRESSHELL_SCROLL_ALWAYS means move the frame regardless > + * of its current visibility. That description doesn't match the current behavior of ANYWHERE. Currently ANYWHERE does not scroll if the frame is already entirely visible. It sounds like that's the same as SCROLL_IF_NOT_FULLY_VISIBLE. But the difference isn't all that clear in comment #7 either. Hmm. @@ +563,5 @@ > + * WHEN is one of: > + * NS_PRESSHELL_SCROLL_ALWAYS means move the frame regardless > + * of its current visibility. > + * NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE means move the frame > + * only if it is not visible. "only if none of it is visible" @@ +566,5 @@ > + * NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE means move the frame > + * only if it is not visible. > + * NS_PRESSHELL_SCROLL_IF_PARTLY_VISIBLE means move the frame > + * only if it is not fully visible (including if it's not > + * visible at all). Note that in this case if the frame is I think SCROLL_IF_NOT_FULLY_VISIBLE would be a bit more clear. Is it enough to have just SCROLL_IF_NOT_VISIBLE and SCROLL_IF_NOT_FULLY_VISIBLE, combined with the percentages to scroll to if we need to scroll? Created attachment 598439 [details] [diff] [review] WIP v2: Changes based on suggestions, fix selection scrolling, adds MINIMUM pseudopercentage Fixes an ongoing scroll exiting the view's boundary causing selection to jump all the way to that end. The last version used a percentage of SCROLL_CENTER for that, where this version uses a new SCROLL_MINIMUM (-1). MINIMUM will scroll the minimum needed to get the frame in view. The other main change here is that ALWAYS now means always, so anything that doesn't always scroll will be moved to IF_NOT_VISIBLE or IF_NOT_FULLY_VISIBLE. ALWAYS is needed for, eg, jumping to an anchor based on a URL fragment, which is always scrolled to the top, even if fully visible. That case was previously handled because it would always scroll to the percentage. Old values that used a percentage are equivalent to a percentage and ALWAYS. The old ANYWHERE is equivalent to MINIMUM and IF_NOT_FULLY_VISIBLE. The next revision will update values to properly reflect these equivalences. Comment on attachment 598439 [details] [diff] [review] WIP v2: Changes based on suggestions, fix selection scrolling, adds MINIMUM pseudopercentage Review of attachment 598439 [details] [diff] [review]: ----------------------------------------------------------------- This is great work, we're getting a lot closer to something precisely specified and sane. ::: content/base/public/nsISelectionPrivate.idl @@ +191,5 @@ > + * move to a specific point, but just wants the frame visible. > + * When: A value of -1 means to always move the frame where > + * doing so improves the visibility. -2 for moving the > + * frame only when not visible, and -3 for moving the frame > + * only when not entirely visible. I think you should just refer to nsIPresShell.h for the documentation of ScrollContentParameter. ::: layout/base/nsIPresShell.h @@ +155,5 @@ > +#define NS_PRESSHELL_SCROLL_CENTER 50 > +#define NS_PRESSHELL_SCROLL_MINIMUM -1 > +#define NS_PRESSHELL_SCROLL_ALWAYS -1 > +#define NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE -2 > +#define NS_PRESSHELL_SCROLL_IF_NOT_FULLY_VISIBLE -3 How about moving this all into nsIPresShell for namespace control and then we can have enum { SCROLL_TOP = 0, SCROLL_BOTTOM = 100, SCROLL_LEFT = 0, SCROLL_RIGHT = 100, SCROLL_CENTER = 50, SCROLL_MINIMUM = -1 }; and a named enum for mWhenToScroll, say enum WhenToScroll { SCROLL_ALWAYS, SCROLL_IF_NOT_VISIBLE, SCROLL_IF_NOT_FULLY_VISIBLE }; @@ +158,5 @@ > +#define NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE -2 > +#define NS_PRESSHELL_SCROLL_IF_NOT_FULLY_VISIBLE -3 > + > +typedef struct ScrollContentParameter { > + PRInt16 mPercentageToScroll; Given "minimum", which isn't a percentage, let's call this "mWhereToScroll". @@ +159,5 @@ > +#define NS_PRESSHELL_SCROLL_IF_NOT_FULLY_VISIBLE -3 > + > +typedef struct ScrollContentParameter { > + PRInt16 mPercentageToScroll; > + PRInt16 mWhenToScroll; Then this can be WhenToScroll. @@ +562,5 @@ > * value of 50 (NS_PRESSHELL_SCROLL_CENTER) centers the frame > + * vertically. > + * A value of -1 (NS_PRESSHELL_SCROLL_MINIMUM) means the > + * frame is adjusted into view with minimal change from the > + * current view. The behavior of MINIMUM needs to be clarified. I presume it's supposed to be the minimum that makes the whole frame visible. But what if the whole frame doesn't fit in the viewport? @@ +576,5 @@ > + * try to give it increased visibility. > + * @param aHorizontal How to align the frame horizontally and when to do so. > + * See aVertical above, with the caveat that you should use > + * NS_PRESSHELL_SCROLL_LEFT for a value of 0 and use > + * NS_PRESSHELL_SCROLL_RIGHT for a value of 100. This parameter documentation should move to ScrollContentParameter. @@ +621,5 @@ > + virtual bool ScrollFrameRectIntoView(nsIFrame* aFrame, > + const nsRect& aRect, > + ScrollContentParameter aVertical, > + ScrollContentParameter aHorizontal, > + PRUint32 aFlags) = 0; You might as well fix the indent while you're here. ::: layout/base/nsPresShell.cpp @@ +3154,5 @@ > + NS_PRESSHELL_SCROLL_TOP, > + NS_PRESSHELL_SCROLL_ALWAYS), > + ScrollContentParameter( > + NS_PRESSHELL_SCROLL_LEFT, > + NS_PRESSHELL_SCROLL_ALWAYS), Shouldn't we make this SCROLL_MINIMUM instead of LEFT? @@ +3159,1 @@ > ANCHOR_SCROLL_FLAGS); Move this stuff further to the left so you can put each ScrollContentParameter constructor on a single line @@ +3249,5 @@ > + NS_PRESSHELL_SCROLL_TOP, > + NS_PRESSHELL_SCROLL_ALWAYS), > + ScrollContentParameter( > + NS_PRESSHELL_SCROLL_LEFT, > + NS_PRESSHELL_SCROLL_ALWAYS), Ditto Created attachment 599029 [details] [diff] [review] WIP v3: Address comments, correct parameter values, fix IF_NOT_FULLY_VISIBLE. The main change is moving the scroll parameter parts into the nsIPresShell namespace. Scrolls using MINIMUM will behave as ANYWHERE did, favoring the top/left if the frame is too large to fit. Fixed the IF_NOT_FULLY_VISIBLE logic to allow scrolling if the frame is completely out of view. Updated the rest of the consumers' parameters to match their behavior under the old constants. Reexamining the problem with adjusting the scroll for search mentioned in comment 19. To restate that problem, consider a diagram: |-----!A!-| |---------| | B | | A | | | |!B! | | | > | | | | | | | | | | |---------| |---------| User found the match at A, then scrolled down so that the next match, B, is within the adjustment zone. When the user jumps to B, the view is scrolled up, despite the fact that the next selection is down. The view moving in opposition to the selection direction may confuse the user briefly. A flag could be added by nsTypeAheadFind if the new match is above the previous. If the adjustment would scroll down, but the hint is there, the adjustment doesn't happen, and vice versa. The tradeoff here is scrolling instability. With that change, the scrolling isn't stable (ie, going back from B to A will cause the view to scroll up where going A to B didn't). Simply removing the adjustment would make the scrolling behavior consistent with Webkit browsers (ie, center if not fully visible). Shall we review the patch you've got before worrying about that? Review can proceed. The patch mentioned in comment 25 is not much code (about 70 lines longer, but 2/3 of that is context). The third option mentioned would cut the patch by maybe 20 lines. The bulk of the changes will be whatever comes out of review from the current patch, and when UX weighs in the changes should be relatively minor (ie, on the order of changes mentioned above). Comment on attachment 599029 [details] [diff] [review] WIP v3: Address comments, correct parameter values, fix IF_NOT_FULLY_VISIBLE. Review of attachment 599029 [details] [diff] [review]: ----------------------------------------------------------------- A lot of your constructors for ScrollParameters aren't relying on the default parameters when they could. That's worth fixing to make a lot of the calling code shorter. ::: layout/base/nsIPresShell.h @@ +555,5 @@ > + * are given precedence. > + * Other values are treated as a percentage, and the point > + * "percent" down the frame is placed at the point "percent" down > + * the visible area. > + * @param WHEN: Put this comment at the constructor and say aWhen/aWhere instead of WHEN/WHERE. Also document in the constructor what the default values are. @@ +571,5 @@ > + WhenToScroll mWhenToScroll; > + ScrollContentParameter(PRInt16 aWhere = SCROLL_MINIMUM, > + WhenToScroll aWhen = SCROLL_IF_NOT_FULLY_VISIBLE) : > + mWhereToScroll(aWhere), mWhenToScroll(aWhen) {} > +} ScrollContentParameter; How about shortening this name? Maybe ScrollAxis? ::: layout/base/nsPresShell.cpp @@ +3351,5 @@ > > + bool needScroll = false; > + bool canAdjustScroll = false; > + > + // FIXME if next spot is lower, don't scroll up (vice versa) Take this out @@ +3359,5 @@ > + // Used in common among branches > + bool topVis = (aRect.y >= visibleRect.y && > + aRect.y < visibleRect.YMost()); > + bool bottomVis = (aRect.YMost() > visibleRect.y && > + aRect.YMost() <= visibleRect.YMost()); remove unnecessary parens. Use better variable names: topEdgeVisible, bottomEdgeVisible. And move these down closer to where they'll be used. @@ +3360,5 @@ > + bool topVis = (aRect.y >= visibleRect.y && > + aRect.y < visibleRect.YMost()); > + bool bottomVis = (aRect.YMost() > visibleRect.y && > + aRect.YMost() <= visibleRect.YMost()); > + bool fitsInViewY = aRect.height <= visibleRect.height; Just inline this at its single usage point. @@ +3390,5 @@ > + needScroll = true; > + } else if (nsIPresShell::SCROLL_IF_NOT_VISIBLE == aVertical.mWhenToScroll) { > + // Scroll only if no part of the frame is visible in this view > + needScroll = (!topVis && aRect.y < visibleRect.y) || > + (!bottomVis && aRect.YMost() > visibleRect.YMost()); Can't this be simplified to needScroll = aRect.YMost() <= visibleRect.y || aRect.y >= visibleRect.YMost()? @@ +3395,5 @@ > + canAdjustScroll = !needScroll; > + } else if (nsIPresShell::SCROLL_IF_NOT_FULLY_VISIBLE == aVertical.mWhenToScroll) { > + // Scroll only if part of the frame is hidden and more can fit in view > + needScroll = !topVis || !bottomVis; > + canAdjustScroll = !needScroll; It's not clear what canAdjustScroll means. I'm not sure why it's needed at all. You've removed the references to lineSize. That seems like it's probably a mistake. I think this code could be made cleaner by first computing whether we need to scroll vertically. If we do need to scroll, then compute where to scroll by updating scrollPt.y. It might be worth having separate helper functions ComputeNeedToScroll and ComputeWhereToScroll that take ScrollAxis, visibleRect.y, visibleRect.YMost() etc as parameters. Then we could use those functions again for horizontal scrolling. @@ +3500,5 @@ > NS_ASSERTION(mDidInitialReflow, "should have done initial reflow by now"); > > mContentToScrollTo = aContent; > + mContentScrollVPosition = aVertical.mWhereToScroll; > + mContentScrollHPosition = aHorizontal.mWhereToScroll; Shouldn't we save the whole of aVertical/aHorizontal instead of just 'where'? ::: layout/generic/nsSelection.cpp @@ +310,5 @@ > + nsTypedSelection *mTypedSelection; > + SelectionRegion mRegion; > + nsIPresShell::ScrollContentParameter mVerticalScroll; > + nsIPresShell::ScrollContentParameter mHorizontalScroll; > + bool mFirstAncestorOnly; Don't reindent these fields. Created attachment 601455 [details] [diff] [review] WIP v4: Changes based on review comments. The line size is used (for the IF_NOT_VISIBLE case) to require at least a full scroll line within the frame to be considered visible. The IF_NOT_FULLY_VISIBLE handles that by checking that both ends are in the visible frame. It's worth noting the current version of the patch doesn't have any consumers using IF_NOT_VISIBLE. The three uses from the original code are all replaced by the default of IF_NOT_FULLY_VISIBLE. The canAdjustScroll and the associated code was an attempt to adjust the view in cases where the rect was already visible but not in its ideal (as specified as the Where) position. That's the issue mentioned in comment 25. It's removed here, and that kind of tuning can be revisited as a separate patch and/or separate bug if needed. Sudden thought: How will this work if the page is wider than the viewport and showing the next result requires horizontal scrolling? (In reply to David E. Ross from comment #30) > Sudden thought: How will this work if the page is wider than the viewport > and showing the next result requires horizontal scrolling? Currently the same (that wasn't changed by bug 171237): minimally scrolled to get the far edge into the view, preferring the left edge if the target is longer than the view width. Webkit centers horizontally if scrolling is needed. Comment on attachment 601455 [details] [diff] [review] WIP v4: Changes based on review comments. Review of attachment 601455 [details] [diff] [review]: ----------------------------------------------------------------- This is very close! ::: layout/base/nsPresShell.cpp @@ +3327,5 @@ > aRect = frameBounds; > } > } > > +static bool ComputeNeedToScroll(nsIPresShell::WhenToScroll aWhenToScroll, break after 'bool' so the function declaration doesn't have to indent so much. Same below. @@ +3334,5 @@ > + nscoord aRectMax, > + nscoord aRectSize, > + nscoord aViewMin, > + nscoord aViewMax, > + nscoord aViewSize) { aRectSize and aViewSize are not used. @@ +3346,5 @@ > + aRectMin + aLineSize >= aViewMax; > + } else if (nsIPresShell::SCROLL_IF_NOT_FULLY_VISIBLE == aWhenToScroll) { > + // Scroll only if part of the frame is hidden and more can fit in view > + return !(aRectMin >= aViewMin && aRectMin < aViewMax) || > + !(aRectMax > aViewMin && aRectMax <= aViewMax); Shouldn't this be return !(aRectMin >= aViewMin && aRectMax <= aViewMax); or maybe return !(aRectMin >= aViewMin && aRectMax <= aViewMax) && NS_MIN(aViewMax, aRectMax) - NS_MAX(aRectMin, aViewMin) < aViewMax - aViewMin; ? (The second option explicitly checks that more of the frame can be made visible than is currently visible.) @@ +3358,5 @@ > + nscoord aRectMax, > + nscoord aRectSize, > + nscoord aViewMin, > + nscoord aViewMax, > + nscoord aViewSize) { aRectSize and aViewSize are used, but they're just max-min, so just use max-min where you need to. Created attachment 602110 [details] [diff] [review] WIP v5: Update based on comments (In reply to Robert O'Callahan (:roc) (Mozilla Corporation) (away February 21 to March 17) from comment #32) > (The second option explicitly checks that more of the frame can be made > visible than is currently visible.) Went this route, and updated comment under nsIPresShell.h:ScrollAxis to clarify. Consumers can use ALWAYS if they want a specific scroll posture to result. This could go the other way, but if the scrolling is being done to highlight an element, it will either use ALWAYS to put it at a specific point in the view or will have secondary highlight mechanism (such as selection). Comment on attachment 602110 [details] [diff] [review] WIP v5: Update based on comments Review of attachment 602110 [details] [diff] [review]: ----------------------------------------------------------------- Excellent! patching file layout/base/nsIPresShell.h Hunk #1 FAILED at 141 Created attachment 607000 [details] [diff] [review] Unbitrot for checkin, updated commit message to be more descriptive of the actual changes backed out TEST-UNEXPECTED-FAIL | /tests/layout/base/tests/test_scroll_selection_into_view.html | an unexpected uncaught JS exception reported through window.onerror - selection.scrollIntoView is not a function at TEST-UNEXPECTED-FAIL | /tests/layout/generic/test/test_plugin_mouse_coords.html | p2 mouse down Y - got 178, expected 18 TEST-UNEXPECTED-FAIL | /tests/layout/generic/test/test_plugin_mouse_coords.html | p3 mouse down X - got 26, expected 6 Created attachment 607384 [details] [diff] [review] Split off nsSelection::ScrollIntoView into two methods, adjust nsFocusManager::ScrollIntoView To fix the first test failure, this splits nsTypedSelection::ScrollIntoView into two functions. The function signature is reverted so that JavaScript calls only specify where to scroll. A new ScrollIntoViewInternal method is spun off to specify a full ScrollAxis for both axes, and the non-script consumers are updated to use it instead. The scriptable version simply wraps the percentages into ScrollAxis and calls the -Internal version. To fix the other pair of failures, the consumer nsFocusManager::ScrollIntoView needed to be adjusted to use SCROLL_IF_NOT_VISIBLE rather than the default (IF_NOT_FULLY_VISIBLE). An alternative would be to modify the test. Those two failures were caused by the frames being partially visible and being scrolled, where before they weren't scrolled. Comment on attachment 607384 [details] [diff] [review] Split off nsSelection::ScrollIntoView into two methods, adjust nsFocusManager::ScrollIntoView Review of attachment 607384 [details] [diff] [review]: ----------------------------------------------------------------- Excellent! BTW, please get into the habit of requesting review on your patches :-) r+ with the IID rev ::: content/base/public/nsISelectionPrivate.idl @@ +68,2 @@ > > [scriptable, uuid(1820a940-6203-4e27-bc94-fa81131722a4)] You need to put a new IID in here. Sorry I missed this before. Created attachment 607412 [details] [diff] [review] Update nsISelectionPrivate IID Does the implementation of this RFE work when the preference variable browser.findbar.enabled is set to "False", which gives the Find popup in place of the Find tool bar? See bug #748991.
https://bugzilla.mozilla.org/show_bug.cgi?id=720126
CC-MAIN-2016-36
refinedweb
3,686
54.73
Alexandre Badez <alexandre.badez at gmail.com> wrote: > Thanks for your try Cliff, I was very confused :P > More over I made some mistake when I post (to make it easiest). > > Here is my real code: > > with > dArguments = { > 'argName' : { > 'mandatory' : bool, # True or False > [...], # other field we do not care here > } > } > > lMandatory = [] > lOptional = [] > for arg in cls.dArguments: > if cls.dArguments[arg]['mandatory']: > lMandatory.append(arg) > else: > lOptional.append(arg) > return (lMandatory, lOptional) > > So, as you see, we agree each other about "if bool" or "if bool is > True" ;) > > So, my question was how to give it a better 'python like' look ? > Any idea ? > > For a 'python like' look lose the Hungarian notation (even Microsoft have largely stopped using it), increase the indentation to 4 spaces, and also get rid of the spurious parentheses around the result. Otherwise it is fine: clear and to the point. If you really wanted you could write something like: m, o = [], [] for arg in cls.dArguments: (m if cls.dArguments[arg]['mandatory'] else o).append(arg) return m, o Or even: m, o = [], [] action = [o.append, m.append] for arg in cls.dArguments: action[bool(cls.dArguments[arg]['mandatory'])](arg) return m, o but it just makes the code less clear, so why bother?
https://mail.python.org/pipermail/python-list/2007-October/420939.html
CC-MAIN-2014-10
refinedweb
210
68.16
Write, CCompile and EExecute a C++ program that inputs a telephone number as a string in the form (392) 630-1234. The program should use standard function strtok( ) to extract the area code (sequence of digits shown in parentheses) as a token, the first three digits of the phone number as a token, and the last four digits of the phone number as a token. The seven digits of the phone number should be concatenated into one string containing no blanks. Both the area code and the phone number are then sent to the output. The initial part of the program may look as follows (You are free to follow it or to make certain modifications): Hypothetical dialogue may have the form given below:Hypothetical dialogue may have the form given below:Code: #include <iostream > using namespace std; ... ... < other files for inclusion > ... ... #include <cstring > int main( ) { const int SIZE1 = 20; ... ... < other declarations, if needed > ... ... char p[ SIZE1 ]; char * tokenPtr; // store temporary token char * areaCode; // store area code (token 1) char * phone; // store the phone number cout << "Enter a phone number in the form (555) 555-5555: "; cin.getline( p, SIZE1 ); ... ... ... // remaining part of the program } Enter a phone number in the form (555) 555-5555: (392) 630-1234 Output: Area code (token 1) is 392 Telephone number (concatenated tokens 2 and 3) is 6301234
http://cboard.cprogramming.com/cplusplus-programming/96767-help-writing-codes-printable-thread.html
CC-MAIN-2014-35
refinedweb
224
68.4
Numpy is a python package that allows any developer to create an array and make complex calculations on it. There are many inbuilt methods in it and all make efficient and quick mathematical calculations. Suppose you want to find the magnitude of a vector in NumPy, then there are different methods for it. In this entire tutorial, you will learn how to calculate the magnitude of vectors in NumPy using various method. But before going to the coding part let’s know the concept of magnitude and vector. What is a vector? A vector is a quantity that has two independent properties. One is the magnitude and the other is direction. Any quantity that has magnitude but no direction is a scalar. How to calculate the magnitude of a vector? The magnitude of a vector represents the length of a vector. It is represented by the mode of the vector. The formulae for calculating the magnitude of the vector is the below. How to find the magnitude of a vector using NumPy? Numpy provided you to find the magnitude of a numpy very easily. There are different methods to find the magnitude of a vector. We will discuss each of them. Example 1: Using the Formulae The first method to find the magnitude of a vector is using the formulae. In this example, I will first create a function that will take each element of a NumPy array and calculate the magnitude. Execute the below lines of code. import math import numpy as np vector = np.array([0, 2]) def magnitude(x): return math.sqrt(sum(i ** 2 for i in x)) mag = magnitude(vector) print(mag) Output Example 2: Find the magnitude of the vector using the NumPy method The second method for calculating the magnitude of a vector is the NumPy np.linalg.norm() method. It will normalize the elements of the NumPy array. The normalization formula is the same as the direct formulae. Run the below lines of code and you will get the same output as example 1. import numpy as np vector = np.array([0, 2]) mag = np.linalg.norm(vector) print(mag) Output Example 3: Using the NumPy dot() and sqrt() method Numpy provides other inbuilt methods np.dot() and np.sqrt() that will be used to find the magnitude of a vector in NumPy. The np.dot() will calculate the dot product of the elements. After that its result will be passed as an argument for the numpy.sqrt() method. You will get the same result as the above when you will run the below lines of code. import numpy as np vector = np.array([0, 2]) mag = np.sqrt(vector.dot(vector)) print(mag) Output Conclusion Vector uses to represent physical quantities. In Machine learning, it uses to represent numeric and symbolic characteristics of an object in a mathematical way. In fact, It is called features. The magnitude of a vector is very useful in the normalization of the datasets. These are the method to find the Magnitude of a Vector in Numpy. I hope you have liked this tutorial. Even If you have any queries then you can contact us for more information. Join our list Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
https://gmailemail-login.email/how-to-find-the-magnitude-of-a-vector-in-numpy-various-methods/
CC-MAIN-2022-33
refinedweb
550
67.86
On this page are instructions for developers and those wishing to contribute to LinBox. It is intended both for the uninitiated and for the reference of existing developers. If you are installing from a tarred distribution, please see the file INSTALL for basic instructions on how to install LinBox. If you are installing from Subversion, please see the instructions in the section below. LinBox is a template library, so installation requires very little actual compilation. Nearly all of the library is in header files. Directories in the source distribution are as follows, relative to the tree's root: N.B. Though the doc/ directory contains some top-level and tutorial documentation, reference documentation is stored in parallel with the source code, under the src/ tree. LinBox is stored in a Subversion repository at the University of Delaware. To access the latest bleeding edge copy of LinBox from this source, you will need a working copy of Subversion and all of the GNU development tools (e.g. autoconf, automake, GNU make, and so on). To access Subversion: You will need Subversion installed. Also you will need to know how to do a svn login. You will need GNU Autoconf, GNU Automake, GNU Libtool, the GNU multiprecision library (GMP), and a BLAS implementation to compile LinBox. Make sure the bin directories of the first three of those are all in your PATH, e.g. if you have Libtool installed in /usr/local/algebra/libtool, make sure /usr/local/algebra/libtool/bin is in your PATH. Also, if Automake is installed in a place separate from Autoconf, you will need to set the environment variable ACLOCAL_FLAGS to "-I <automake prefix>/share/aclocal", where <prefix> is the install prefix of Automake. Similarly, if Libtool is installed to a separate prefix, you should add "-I <libtool prefix>/share/aclocal" to ACLOCAL_FLAGS, where <libtool prefix> is the install prefix of Libtool. Of the four tools mentioned, only GMP and BLAS are required if you are installing from a tarball. GNU Autoconf, GNU Automake, and GNU Libtool are only required for users of Subversion and those individuals interested in doing major development work on the library. See for GNU Autoconf, for GNU Automake, and for GNU Libtool. svn co svn://linalg.org/linalg/trunk/linbox/ cd linbox ./autogen.sh [--prefix=<prefix>] [options] [options] include the following: GMP is required for the library to compile, so you must specify --with-gmp-prefix=<prefix> if <prefix> is not a standard location such as /usr or /usr/local make install When you want to update your tree with the contents of the LinBox Subversion repository, issue the following command from the linbox/ directory: svn up You should receive some information on what files have been updated. If any files have a "C" before them, this means what you have conflicts with what is in the repository. In other words, you made changes while someone else made other changes and Subversion does not know how to reconcile the two. You will need to edit that file manually, looking for and fixing lines like <<<<<<<<<<< =========== >>>>>>>>>>> that show the sections that could not be reconciled. If you have made changes and would like to commit them to the global repository, issue the command svn ci [<filename(s)>] The optional filename(s) argument specifies what you would like to commit; the default is to commit everything that has changed in the current directory and its descendents. When you enter this command, a text editor will come up prompting you for a log message. ALWAYS ENTER A LOG MESSAGE DESCRIBING WHAT YOU HAVE CHANGED. Failure to do so may result in your changes being backed out by the administrator. When you are done entering your message, simply save and exit the text editor. If you are not a main LinBox developer but would like to submit some addition or modification, your code is welcome. Please email a patch (use 'svn diff' to form a patch) to us and we will consider including it. We use the Linux indentation style, i.e. K&R with 8-space indents. We would like to keep this standard, so please use it for any code submitted to the project. Here is an example: void myFunction (int a, int b, int c) { int d; if (a == 0) { d = 1; } else if (a == 1) { d = 2; myOtherFunction (b, c); } else { d = 3; } } template <class T> class MyClass : public MyOtherClass { int _b; public: MyClass (int a) : MyOtherClass (a), _b (0) { } }; If you are using Emacs, then the text editor may automatically try to use its default GNU coding style when auto-indenting. This yields code that is very hard to read. To fix this problem, all files in LinBox should start with the following line: /* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ Also, to make Emacs default to the more reader-friendly Linux indentation style, add the following to your ~/.emacs file: (add-hook 'c-mode-common-hook (lambda () (c-set-style "linux") (c-set-offset 'access-label '/) (c-set-offset 'inline-open 0))) One more note: as stated below all LinBox files are declared in the namespace LinBox. This causes Emacs to indent all of the source code an extra level. We consider this to be excessive, so the preferred approach is to force Emacs not to indent for that namespace declaration. To do this, just go to the first few lines inside the namespace and pull them back to the first column. Emacs will follow that pattern from there on out. We use Java/Smalltalk conventions for naming classes, methods, and variables. Classes whose names have several words have all the words juxtaposed without underscores, and each word has its first letter capitalized (e.g. MyClass, MyOtherClass). Methods are similar, except that the first letter of the first word is lower case (e.g. myMethod). Global constants should be all upper case with underscores between the words (e.g. MY_CONSTANT). In addition, variables that are members of classes should begin with an underscore to differentiate them from methods and parameters (e.g. int _myMember; int myMember () const;). Directory and file names should be in lower case, with words separated by a hyphen ('-'), e.g. my-file.h We generally avoid abbreviations so as to avoid confusion among users of the library. However, some very commonly used features are abbreviated and some words commonly used together are treated as a single word. For example, we use "minpoly" rather than "MinimalPolynomial" and "Blackbox" rather than "BlackBox". We put all of our declarations in the namespace LinBox. Please put the lines namespace LinBox { ... // Your code here } in all header files of contributed code. All header files should have a set of preprocessor directives to prevent multiple inclusion. If your header file is named my-header-file.h, use #ifndef __MY_HEADER_FILE_H #define __MY_HEADER_FILE_H ... // Your code here #endif // __MY_HEADER_FILE_H surrounding the whole file, except possibly any comments you have at the top. All files should contain a comment at the top indicating the file name, copyright, authors, and licensing. Additional documentation would be useful. You may use any of the files in this library as a template. Key objects must have documentation comments to be processed by doxygen in the creation of our online documentation system. In the reference manual, see the section documenting doc itself for guidelines on these comments. This code is licensed under the GNU Lesser General Public License (see COPYING for details); all contributed code should be similarly licensed. We cannot accept any code that is released under a license legally incompatible with the LGPL, so please either license the code under the LGPL or explicitly place it in the public domain if you are unsure. Technically, code released without a license at all and not explicitly placed in the public domain is incompatible with the LGPL, so licensing it is important. The original author of a program holds the copyright to that program. If another author changes the program, the changes are copyrighted to that other author provided that in the preamble a change is announced and that the places where the changes are made are annodated by the initials of the author and a date. The procedure for adding a file is based on the type of file being added. In the text below <filename> refers to the file you are adding and <dir> refers to the directory where the file you are adding is located. For major changes only: Add an entry to linbox/ChangeLog detailing the IDEAS that are different in LinBox's architecture or implementation as a result of your change. Small modifications, file renamings, and so on do not deserve entries in the ChangeLog -- details like that are generated automatically by Trac. All tests should go in the directory tests. They should be in the form of a standalone program that can run a sensible test with no command line arguments, preferably with a name prefixed by "test-". In the text below, <test> refers to the name of your test binary, e.g. test-minpoly. <mod-test> refers to the result of replacing all "-" and "." characters in <test> with an underscore "_". <test-source> refers to the name of the source file; the procedure works just as well if you have multiple source files. By convention, the name of the source file should be <test>.C test_sparse_matrix_SOURCES = \ test-0-matrix.C \ test-common.C test-common.h <mod-test>_SOURCES = \ <test-source> \ test-common.C test-common.h
http://linalg.org/developer.html
crawl-001
refinedweb
1,588
61.97
public class MUser { private int id; private string username; private string password; private string email; public int ID { set { this.id = value; } get { return this.id; } } public string UserName { set { this.username = value; } get { return username; } } public string Password { set { this.password = value; } get { return this.password; } } public string Email { set { this.email = value; } get { return. Also, I am using SQL2005 without LINQ... Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications. Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial CodeAuthor MyGeneration Microsoft Entity framework cannot handle vendor-specific database.
https://www.experts-exchange.com/questions/27495044/Data-Tier-Generator-for-C.html
CC-MAIN-2018-43
refinedweb
134
61.83
No project description provided Project description Python bindings for bliss-rs. Audio library used as a building block to make playlists from songs. Installation bliss-audio is available for Python 3.5+ via pip: $ pip install bliss-audio Usage from bliss_audio import Song import numpy as np song1 = Song("/path/to/song1") song2 = Song("/path/to/song2") distance = np.linalg.norm(np.array(song1.analysis) - np.array(song2.analysis)) print('Distance between song1 and song2 is {}'.format(distance)) Then you most likely want to analyze a bunch of songs like that, store the result somewhere, and generate playlists on the fly by taking a song and finding the next one by computing the one with the smallest distance to it. Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/bliss-audio/
CC-MAIN-2022-21
refinedweb
143
64.61
I'm playing around with Mojolicious and websockets. I want to send the output of multiple external commands on the server to the webpage. I have no problems with connecting and receiving messages, but I also want to send a message back to the server to stop an external command while letting the others keep sending messages back to the client. I also want to stop checking the external command once it exits. The external command is simply a one-liner that spits out an integer every few seconds. I have two websockets that display the numbers in separate div Mojo::IOLoop->recurring Mojo::IOLoop->remove($id) Mojo::Reactor::Poll: Timer failed: Can't call method "is_websocket" on an undefined value finish use feature qw(signatures); no warnings qw(experimental::signatures); ## other boilerplate redacted websocket '/find' => sub ( $c ) { state $loop = Mojo::IOLoop->singleton; app->log->debug( "websocket for find" ); $c->inactivity_timeout( 50 ); my $id; $c->on( message => sub ( $ws, $message ) { my $json = decode_json( $message ); my $command = $json->{c}; my $name = $json->{n}; app->log->debug( "Got $command command for $name" ); if( $command eq "start" ) { $id = run_command( $ws ); app->log->debug( "run_command for $name returned [$id]" ); } elsif( $command eq "stop" ) { app->log->debug( "stopping loop for $name [$id]" ); # XXX What should I do here? # $ws->finish; # $loop->remove( $id ); } elsif( $command eq "open" ) { app->log->debug( "opening websocket for $name" ); } } ); $c->on( finish => sub ( $c, $code ) { app->log->debug("WebSocket closed with status $code"); } ); }; app->start; sub run_command ( $ws ) { app->log->debug( "In run_command: $ws" ); open my $fh, "$^X -le '\$|++; while(1) { print int rand(100); sleep 3 }' |"; $fh->autoflush; my $id; $id = Mojo::IOLoop->recurring( 1 => sub ($loop) { my $m = <$fh>; unless( defined $m ) { app->log->debug( "Closing down recurring loop from the inside [$id]" ); # XXX: what should I do here? close $fh; return; }; chomp $m; app->log->debug( "Input [$m] for [$id] from $fh" ); $ws->send( encode_json( { 'm' => $m } ) ); }); return $id; } I played around with this a bit. Logioniz's answer made me think that I shouldn't be polling or handling the filehandle details myself. I still don't know where it was hanging. Instead, I used Mojo::Reactor's io to set a filehandle to monitor: sub run_command ( $ws ) { my $pid = open my $fh, "$^X -le '\$|++; print \$\$; while(1) { print int rand(100); sleep 3 }' |"; $fh->autoflush; my $reactor = Mojo::IOLoop->singleton->reactor->io( $fh => sub ($reactor, $writeable) { my $m = <$fh>; chomp $m; $ws->send( encode_json( { 'm' => $m } ) ); } ); return ( $fh, $pid ); } When I'm done with that command, I can unwatch that filehandle and kill the process. I finish the websocket: elsif( $command eq "stop" ) { $loop->reactor->watch( $fh, 0, 0 ); kill 'KILL', $pid or app->log->debug( "Could not kill $pid: $!" ); $ws->finish; } I still don't know why remove($fh) doesn't work. I figure I'm leaking some IOLoop things doing it this way.
https://codedump.io/share/hxowWZKWadjc/1/shutting-down-a-mojoioloop-recurring-event-connected-to-a-mojo-websocket
CC-MAIN-2017-04
refinedweb
480
50.3
UI-driven Jest test-generation package for Recoil selectors You're an independent developer or part of a lean team. You want reliable unit tests for your new React-Recoil or React Hooks app, but you need to move fast and time is major constraint. More importantly, you want your tests to reflect how your users interact with the application, rather than testing implementation details. Enter Chromogen. Chromogen is a Jest unit-test generation tool for Recoil selectors and React useState Hooks. It captures state changes during user interaction and auto-generates corresponding test suites. Simply launch your application after following the installation instructions below, interact as a user normally would, and with one click you can download a ready-to-run Jest test file. FOR RECOIL APPS: Chromogen currently supports three main types of tests for Recoil apps: newValueargument and starting state. These test suites will be captured for synchronous selectors and selectorFamilies only. However, the presence of asyncronous selectors in your app should not cause any issues with the generated tests. Chromogen can identify such selectors at run-time and exclude them from capture. At this time, we have no plans to introduce testing for async selectors; the mocking requirements are too opaque and fragile to accurately capture at runtime. By default, Chromogen uses atom and selector keys to populate the import & hook statements in the test file. If your source code does not use matching variable and key names, you will need to pass the imported atoms and selectors to the ChromogenObserver component as a storeprop. The installation instructions below contain further details. FOR REACT HOOKS APPS Chromogen currently supports one main type of test for React Hooks Apps: Currently, these test suites will be captured only for the useState Hook. We are working on adding testing for the useReducer Hook in the near future. We are always open to suggestions to meet the needs of our userbase. Want to see this or any other feature added to the package? Let us know! Chromogen's official demo app provides a ready-to-run Recoil frontend with a number of different selector implementations to test against. It's available in the demo-todofolder of this repository and comes with Chromogen pre-installed; just run npm install && npm startto launch. Before running Chromogen, you'll need to make two changes to your application: atomand selectorfunctions from Chromogen instead of Recoil Note: These changes do have a small performance cost, so they should be reverted before deploying to production. npm install chromogen ChromogenObserver should be included as a direct child of RecoilRoot. It does not need to wrap any other components, and it takes no mandatory props. It utilizes Recoil's TransactionObserver Hook to record snapshots on state change. import React from 'react'; import { RecoilRoot } from 'recoil'; import { ChromogenObserver } from 'chromogen'; import MyComponent from './components/MyComponent.jsx'; const App = (props) => ( ); export default App; If you are using pseudo-random key names, such as with UUID, you'll need to pass all of your store exports to the ChromogenObserver component as a storeprop. This will allow Chromogen to use source code variable names in the output file, instead of relying on keys. When all atoms and selectors are exported from a single file, you can pass the imported module directly: import * as store from './store'; // ... ; If your store utilizes seprate files for various pieces of state, you can pass all of the imports in an array: import * as atoms from './store/atoms'; import * as selectors from './store/selectors'; import * as misc from './store/arbitraryRecoilState'; // ... ; Wherever you import atomand/or selectorfunctions from Recoil (typically in your storefile), import them from Chromogen instead. The arguments passed in do not need to change in any away, and the return value will still be a normal RecoilAtom or RecoilSelector. Chromogen wraps the native Recoil functions to track which pieces of state have been created, as well as when various selectors are called and what values they return. import { atom, selector } from 'chromogen'; export const fooState = atom({ key: 'fooState', default: {}, }); export const barState = selector({ key: 'barState', get: ({ get }) => { const derivedState = get(fooState); return derivedState.baz || 'value does not exist'; }, });. For example, if we want to test our demo to-do app's filter and sort buttons, we may want to have 10 or so different items with various priority levels and completion states. However, we don't necessarily want 10 separate tests just for adding items. We can instead add one or two items to generate tests for that functionality, then pause recording while we add the other 8 items. Once everything is added, we can resume recording to generate filter & sort tests with all 10 items present. Once you've recorded all the interactions you want to test, click the pause button and then the download button to download the test file. You can now drag-and-drop the downloaded file into your app's test directory. Before running the test file, you'll need to specify the import path for your store by replacing. The default output assumes that all atoms and selectors are imported from a single path; if that's not possible, you'll need to separately import each set of atoms and/or selectors from their appropriate path. | BEFORE | AFTER | | :-----------------------------------------------------------: | :----------------------------------------------------------: | | | | You're now ready to run your tests! Upon running your normal Jest test command, you should see three suites for chromogen.test.js: Initial Render tests whether each selector returns the correct value at launch. There is one test per selector. Selectors tests the return value of various selectors for a given state. Each test represents the app state after a transaction has occured, generally triggered by some user interaction. For each selector that ran after that transaction, the test asserts on the selector's return value for the given state. Setters tests the state that results from setting a writeable selector with a given value and starting state. There is one test per set call, asserting on each atom's value in the resulting state. Before using Chromogen, you'll need to make two changes to your application: useStatefunction from Chromogen instead of React. Chromogen has engineered useStateto track state changes. npm install chromogen Import HooksChromgenObserver. HooksChromogenObserver should wrap the parent most component of the user's app (usually inside of index.js). import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { HooksChromogenObserver } from 'chromogen'; ReactDOM.render( document.getElementById('root'), ); Chromogen has engineered React's useStateHook to include a state change tracker. Wherever your app imports useStatefrom React, import useStatefrom Chromogen instead. By default, Chromogen requires a second parameter in the useState hooks as idto generate a test suite for the user's application. import React from 'react'; import { useState as hooksUseState } from 'chromogen'; const App: React.FC = () => { const [elements, setElements] = hooksUseState([0], "id"); return (...) };. Once you've recorded all the interactions you want to test, click the pause button and then the download button to generate the test file. You can now drag-and-drop the downloaded file into your app's test directory. You're now ready to run your tests! After running your normal Jest test command, you should a test suite for chromogen.test.js. The current tests check whether state has changed after an interaction and checks whether the resulting state change variables have been updated as expected. Install Chromogen DevTool Extension If the injected buttons interfere with the functioning or layout of your application, you can also control Chromogen through an optional DevTool panel. As soon as Chromogen detects that the panel has been opened and loaded, the injected buttons will disappear from the application view. The recording and download buttons on the panel work exactly the same as outlined above. Note: You may also access the DevTool can be added as an unpacked extension by running npm install && npm run buildin the dev-toolsubdirectory and loading the resulting buildfolder. We expect all contributors to abide by the standards of behavior outlined in the Code of Conduct. We welcome community contributions, including new developers who've never made an open source Pull Request before. If you'd like to start a new PR, we recommend creating an issue for discussion first. This lets us open a conversation, ensuring work is not duplicated unnecessarily and that the proposed PR is a fix or feature we're actively looking to add. Please file an issue for bugs, missing documentation, or unexpected behavior. Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps us prioritize what to work on. For questions related to using the package, you may either file an issue or gmail us: chromogen.app. Logo remixed from ReactJS under CC BY 4.0 and Smashicons via README format adapted from react-testing-library under MIT license. All Chromogen source code is MIT licensed. Lastly, shoutout to this repo for the original inspiration.
https://xscode.com/open-source-labs/Chromogen
CC-MAIN-2021-43
refinedweb
1,491
54.93
Public Class TemplateHandler Implements ITemplate Private Sub InstantiateIn(ByVal container As Control) Dim cmd As Button = New Button() cmd.ID = "cmd" cmd.Text = "HI" AddHandler cmd.Click, New EventHandler(AddressOf Dynamic_Method) container.Controls.Add(cmd)ige- Have you created your own ITemplate class or related namespace? -saige- Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and exploring the core foundations for app libraries. Open in new windowYou can read more about interfaces here: -saige- Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial
https://www.experts-exchange.com/questions/29148579/ASP-net-ITemplate-oroblem.html
CC-MAIN-2019-26
refinedweb
123
52.76
Real time Barcode and QR Code scanner Edit Project description zbarcam Real time Barcode and QR Code scanner using the camera. It's built on top of Kivy and pyzbar. How to use Simply import and instanciate ZBarCam in your kvlang file and access its symbols property. #:import ZBarCam kivy_garden.zbarcam.ZBarCam #:import ZBarSymbol pyzbar.pyzbar.ZBarSymbol BoxLayout: orientation: 'vertical' ZBarCam: id: zbarcam # optional, by default checks all types code_types: ZBarSymbol.QRCODE, ZBarSymbol.EAN13 Label: size_hint: None, None size: self.texture_size[0], 50 text: ', '.join([str(symbol.data) for symbol in zbarcam.symbols]) A full working demo is available in src/main.py. Install Ubuntu Install system requirements (Ubuntu 18.04): make system_dependencies Install zbarcam: pip install zbarcam Then import it in your Python code via: from kivy_garden.zbarcam import ZBarCam Android Build for Android via buildozer, see buildozer.spec. Contribute To play with the project, install system dependencies and Python requirements using the Makefile. make Then verify everything is OK by running tests. make test make uitest Troubleshooting Android ValueError: Empty module name More likely an import issue in your .kv file. Try to from zbarcam import ZBarCam in your main.py to see the exact error. It's common to forget Pillow in buildozer.spec requirements section. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/zbarcam/
CC-MAIN-2022-27
refinedweb
238
53.07
notimeout, timeout, wtimeout - control blocking on input #include <curses.h> int notimeout(WINDOW *win, bool bf); void timeout(int delay); void wtimeout(WINDOW *win, int delay); The notimeout() function specifies whether Timeout Mode or No Timeout Mode is in effect for the screen associated with the specified window. If bf is TRUE, this screen is set to No Timeout Mode. If bf is FALSE, this screen is set to Timeout Mode. The initial state is FALSE. The timeout() and wtimeout() functions set blocking or non-blocking read for the current or specified window based on the value of delay: - delay < 0 - One or more blocking reads (indefinite waits for input) are used. - delay = 0 - One or more non-blocking reads are used. Any Curses input function will fail if every character of the requested string is not immediately available. - delay > 0 - Any Curses input function blocks for delay milliseconds and fails if there is still no input. Upon successful completion, the notimeout() function returns OK. Otherwise, it returns ERR. The timeout() and wtimeout() functions do not return a value. No errors are defined. Input Processing, getch(), halfdelay(), nodelay(), <curses.h>, XBD specification, Parameters that Can be Set .
http://pubs.opengroup.org/onlinepubs/7990989775/xcurses/wtimeout.html
CC-MAIN-2016-30
refinedweb
197
58.58
IMUnified: Playing Red Rover With AOL 109 Griz writes: "Looks like the bigger names in the IM business have come together to support a uniform protocol, and to rally behind IETF. AOL is noticeably absent. Check out IMUnified for more information." And practically speaking, it looks like a tough sell even for giant AOL to balk at implementing the same standards that will be available to customers of Excite@home, MSN, Prodigy, Yahoo!, AT&T and others. More greedy corporate BS (Score:1) This won't fly! (Score:1) Now, having said that, if they aren't on board with this thing then it will never get off the ground. I mean, face it: AOL is the internet for most people! Why is the mp3 format big? AOL owns WinAmp. Why is gnutella going to go down in flames as another stupid hacker toy? AOL dumped the project. Big business owns the net now. Better get used to it. Re:AOL's own solution (Score:1) Uhh... Are you a moron, or just trolling? The draft is here [ietf.org] on the IETF's Web site. Section 7 credits the authors, Edwin Aoki and Andy Wick of AOL. -- Re:Nonsense -- Network effect (Score:1) you'll probably need some sort of gateway.. but I think some companies are already doing something similar to this (ie everybuddy or something like that). One Word (Score:1) All of this stuff is already working as we speak. Check out jabber at huh? Re:A Waste of time without AOL. (Score:1) No one I know has more than _1_ ICQ account. (One guy has 2 because his other one got spammed by some stalker.) I've had my account for over 2 years, went through 2 computers and 4 clean reinstalls during that time and 3 ICQ upgrades. Never had to change my account number or get a new one. Never lost my message history file (which now weighs in at over 3 megs). You must be really uninformed or too dense not to save your /db and/or /new_db files (depends on version). When you reinstall don't you save your email client's mailboxes and folders? Or do you just accept as fact that you'll lose all your past email? Do you go to your ISP and request a new email address? Or do you just re-enter your old info after a reinstall? You know, you can do that in ICQ right from the main menu. Maybe you should learn how to do minimal backups before trashing a product for not assuming its users are all dumbasses. Re:Open source protocol? (Score:1) Re:This won't fly! (Score:1) The remaining CompuServe users are not diehards ... they are (with the greatest respect) diestupids. Regards, Ralph. Re:This won't fly! (Score:1) I'll admit CI$ was good (for it's time) for technical info (though not as good as Compulink (CIX) in the UK I reckon - CI$ won only for it's international access). Access to the Web via vanilla ISPs killed CI$ - better to get that technical info direct from the suppliers' website (or Usenet) rather than via some CI$ forum. (The overcharging and low performance helped of course Regards, Ralph. Would it help AOL? (Score:1) Re:Nonsense -- Network effect (Score:1) -- Using @ (Score:1) Re:Its about bloody well time. (Score:1) Ideally, what our company (and a lot of others) would like to do run our own IM network with easy-to-install hub software -- so that we can have control over our own policies and buddy lists, but still talk to the rest of the world. For example, all employees could be buddies of each other. The IM IDs could be the same as our email IDs, so there's one less thing for people to remember. One could imagine IM hubs that integrate with other authentication and message-related servers such as Exchange, Notes, LDAP, or Kerberos. Doing all of this is "possible" but rather pointless if there is not a single standard that all clients and hubs can agree upon. Was AOL Invited? (Score:1) Just a few thoughts Re:Why Unify? (Score:1) Illegal no. Unethical?... I think that's debatable. Is a monopoly unethical? Basically, they make it EXTREMELY difficult for any other developer to make a buck off of IM. Imagine if every cell phone, set-top, application developer (Napster has IM capabilities, no?) has to pay royalties or licensing fees to AOL when they incorporate a messaging solution into their service. I give you AIM, your new master (Score:1) Who needs to speak? I look forward to the day when the telephone is abolished, the world will be much happier place to live; with nice IM chimes instead of phone rings, and plenty of carpal tunnel syndrome to go around. It will be nice to have my whole social life right in front of me in the comfort of my room...it even glows in the dark...oh wait, I think that already happened. I think Louis Armstrong sung it best, when he belted out, "Oh, what a wonderful world". You just can't beat that, not even with a techno bassline. And M$ should open its API, so apps run anywhere (Score:1) M$ talks as if AOL is doing something bad, and it can fix it. Well they already "fixed" my desktop computer and that's all the help I need from them thank you. Actually, maybe they should release all of their API's so all OSes can interpolate. That way I can switch my OS and won't have to worry about having to buy/find new applications. I am sure that M$ would be willing to do this. Perhaps they could add it to the benevolent mission of the IMUnified Group. Yes, free APIs for everyone, I think I'll email Bill Gates. Re:sametime connect. (Score:1) It seems pretty obvious that IBM/Lotus licenses a customized version of AIM for internal use, and so it's no leap of faith to consider that part of that license is interoperability between the two clients. Re:Yep. (Score:1) If we had a history nazi, I'm sure s/he would point out the way certain political parties with narrow popular bases have at various times gained control of parlimentary governments: organize all the haves-not to work together to destroy the powerful haves, then backstab their erstwhile allies so they can rule without having to share the newly acquired power. I'll leave it as an exercise for the reader to determine why the history nazi might think those episodes were relevant to the content of this thread. -- It'll all be over soon. (Score:1) * This assumes that MSN gets AOL/ICQ support yet again, which wouldn't be too hard. Also WMP 7 supports its own skins and plugins, not to mention playlists. Who needs Winamp? Re:It'll all be over soon. (Score:1) imunified? (Score:1) Say, I could use a vaccination. Yeah? Where do you want to go on your vaccination? Would You Say This? (Score:1) Microsoft, essentially, owns the instant communication market. MSN Messenger Service Microsoft, MSN Messenger Service and ICQ (both owned, though not created, by the same company) use radically different, fundamentally dissimilar naming conventions. When you start introducing others into the fray, a unified protocol or client could easily become a hindrance or lead to complications. Microsoft has more-or-less earned (or acquired) the instant messenging market. When something better comes out, I have no doubt that it will take the place of MSN Messenger Service or ICQ. Until then, though, incompatible standards shouldn't be foisted upon them. i'm not trying to troll here, but methinks that if it was MS not joining the standards committee, your attitude (and by extension, the attitude of others on food for thought. AOL will give in (Score:1) If AOL has half a brain, they'll join IMUnified. But then again, AOL users still can't use POP/SMTP. Hmm (Score:1) Re:Nonsense -- Time Warner effect (Score:1) Re:Would You Say This? (Score:1) The only reason AT&T and Standard Oil got split up is because they were ABUSING their monopolies. Re:Nonsense -- Network effect (Score:1) Mark Duell once more... (Score:1) Re:Huh? (Score:1) Re:Where's ICQ (Score:1) Huh? (Score:1) Re:Gimme TALK any day... (Score:1) Also, does TALK allow multi-party discussions? I assume not... Re:My gloomy predictions. (Score:1) Doesn't unity and standards seem grand? My point is at the last paragraph. It's in these companies interest to not allow any other competing clients. Therefor they do not plan on allowing any OPEN SOURCE clients to communicate on their network. This organisation looks like a very evil thing for open source. Some people think that the will be just able to write a jabber transport to communicate on the network. But they should expect to have to reverse hack the authenication protocol and be sued for it in the process. My post tries to show this, but I guess I wasn't clear enough. Re:Leftist *trendies* are in vogue (Score:1) You're on your way to realizing the One Truth: everything is a sham. The Right, the Left, and everything in between. Even everything on Slashdot. Have a nice day. This tiny jewel of cynicism brought to you by Microsoft. ---------///---------- All generalizations are false. Re:Yep. (Score:1) Okay, I feel better. ---------///---------- All generalizations are false. Re:Happy FreeBSD User (Score:1) I prefer the more old-school approach that you get with FreeBSD's "custom" installation: I choose exactly which packages go on my box, the disk partitioning and labeling, et cetera. OpenBSD's install is almost as good. You can do almost the same with Red Hat's "expert" install, but it takes much, much longer. Slackware probably has one of the best current GNU/Linux installs. IMHO, of course. I just wish that the default kernel had all of the UDMA packages included, so I could've installed directly to an ATA/66 drive instead of switching to a normal ATA/33 IDE bus, installing, recompiling, changing fdisk and rdev, and switching busses again. Sure, it only takes a half-hour to do the whole deal, but if frickin' FreeBSD has proper UltraATA/66 support in the default kernel, shouldn't all GNU/Linux distros? (Except Debian, of course. Right, Rob? Any post-1979 code is just "too wild and unruly" for you Debian freaks. ;-p) Let's get even more offtopic. Installing x86 Solaris for the first time was pretty interesting. 'Twas the first opportunity I had to actually install Solaris on a box, (don't have the dough for a Sparc, heh heh), and it was a pleasant (if unsettling) surprise. Solaris 8 is even more flashy. For those who have never seen it, you start off in text-mode and are allowed to scan/configure devices, then choose where to boot a kernel from. Boot kernel, do a quick fdisk, and set up the console. Then you're thrown right into OpenWindows to install the actual software. Set up the system and partitions, along with the packages to install. You can read propaganda about new and cool features while-you-wait and swap CDs (20-40 minutes, in my experience). Then reboot, and bam, after the normal boot messages, you go right into CDE login. Pretty slick. As I've ranted about before, Sun had user-friendly UNIX done quite some time ago. Okay, enough offtopic-ness for now. Enjoy that coffee, brother/sister. ---------///---------- All generalizations are false. Re:Q: Jabber? (Score:1) Re:MSN only playing for one reason.... (Score:1) ESR on AOL and IM openess (Score:1) Last year, ESR blasted AOL over attempting to close up the AIM protocol after it had oppened it. Look here [linuxtoday.com]. NOTE: I put this link in a comment in another thread, but it might be of more general interest. Suppose you were an idiot. And suppose that you were a member of Congress. But I repeat myself. Gorilla tactics..... (Score:1) ------------------------------------------ If God Droppd Acid, Would he see People??? Re:Gimme TALK any day... (Score:1) Why this is a good thing (Score:1) IMUnified does say that it will "make publically available" specifications in their press release, which means that open-source messaging clients could (and will) be built around it, with the compatibility of bigger messaging clients as well as all the benefits of being open source. Re:Gimme TALK any day... (Score:1) Everybuddy (Score:1) Re:A Waste of time without AOL. (Score:1) Well, obviously, they were busy. *eye roll* (Score:1) To this i say, IRC. Re:Would it help AOL? (Score:1) Sure they could. They could fire the people that made the decision. Just who do you think owns ICQ? Open source protocol? (Score:1) I mean, how difficult can it be? Isn't it basically a lowend version of telnet with a candy coating (for messaging, file-transfers, etc.) Granted, voice chat would be a little more difficult, but as Yahoo has demonstrated recently, you can write a reasonable voice chat system with Java and get away with it being under 80K. Re:Would You Say This? (Score:1) but aol's primary product is its network (Score:1) so it's fine and dandy if imunified wants to create a large competing body, but asking AOL to join is asking them to give up their primary product--access to the aol network. if you can download yahoo messenger and talk to aim folk for free, what's making you go to the aol website and looking at all the banners and 50 free hours! pop-ups? if you breathe wrong on aim, you get sent to an aol sign-up page. having a large subscriber base is not monopolistic. this seems a little like us news & world report and time demanding access to newsweek's mailing lists so they can offer "a wider range of services." 70 million clueless users though (Score:1) A broader view of Instant Messaging (Score:1) Imagine, I want to access info off of my PC at work from home. I had an IM based service on my PC at work and an IM based client that built queries to the IM service. The client "system" communicates with the service "system" to get the requested info (such as my schedule for the day) all via IM. Realize that what IM does is allow two "hosts" to communicate anywhere on the net (firewalls be damned). This could be a new standard communications medium for n number of new services. We should fight that the CLIENT API gets standardized (or at least opened). This may not happen, but at least the servers could interoperate and you could use an "open" source system like Jabber [jabber.org] for the development of the new innovative services. Where's ICQ (Score:1) Re:Yep. (Score:1) oligopoly: a market situation in which each of a few producers affects but does not control the market Now I will use this new word in a sentence: sametime connect. (Score:1) AOL/ICQ can work together/Importance of AOL (Score:1) Also, these numbers about AIM having more people than ICQ are not very reliable if they are going by the number of registered screenames vs. the number of registered ICQ UINs. I only know one person who has more than one ICQ#, but I know quite a few people have have more than five screenames. Somehow I think this could throw the numbers off. Sometimes you by Force overwhelmed are. Re:Q: Jabber? (Score:1) Sometimes you by Force overwhelmed are. Re:Everybuddy (Score:2) Eric -- Re:Nonsense -- Network effect (Score:2) Actually, they seem to have partially joined ICQ to AIM at some point. Why else can I log into AIM, which I just started using recently, using my ICQ uin/password? I think a better way to say it is they'll never join them in a way that doesn't help them. bash: ispell: command not found AOL's own solution (Score:2) Take your current screen name, and add an @ and the service's domain name - for example, AIM user Foo becomes Foo@aol.com, while Yahoo! Messenger user Foo becomes Foo@yahoo.com (notice, different namespace = no conflict). Each user authenticates themself via their own service (MSN Messenger users give Microsoft their MSN Messenger lusername and password, not an AOL screen name and password), so you don't have a big inter-company security nightmare. Each company sets up servers to relay IM messages and other information (such as whether a particular user is online) between their own service and other services. Each company then adds IMX records to their DNS zone file - Instant Messaging eXchange servers, used to relay IMs similar to the way MX records specify SMTP servers to relay mail for a particular domain. These relay servers authenticate each other based entirely on this DNS information, using a callback mechanism (server im.foo.com finds that im.bar.com is the IM exchange server for bar.com and sends a greeting, then im.bar.com checks to see that im.foo.com is the IMX for foo.com and sends a reply, then im.foo.com sends a final message indicating that the authentication has been completed). This way, anybody can set up an IM service and interoperate with all the other services, without having to register themselves with any centralized body - all they need is a domain name, which everyone has anyway. It's been awhile since I read the spec, but that's the basic gist of it. Sounds good to me, and it's been submitted to the IETF, so I don't see why people are still pissed off at AOL. Remember, AOL came up with this themselves, voluntarily. Besides, as far as I know, they haven't done anything to try to prevent people from using other services. People just use AIM because AIM is better than the alternatives - either for technical reasons, or just because everyone else uses it. -- Re:A Waste of time without AOL. (Score:2) As a matter of fact, I don't know anyone personally who has just _1_ ICQ account. Probably since if you have to reinstall ICQ you are screwed anyways - you don't have any of your contacts since ICQ is a client-based trust protocol, althought they can see you. At least with a new account you: -don't have to remember a password -don't have old people you removed from your list still seeing your presence online (and IP address). As far as AOL submitting their open architecture design, it was horribly incomplete and more importantly - not implemented. AOL has had exactly zero percent participation in the IETF process, and basically submitted a quick draft proposal to help their Time-Warner merger case with the FCC. It met (by my estimates) about 50% of the IETF working group's requirements for a protocol, and would never be supported anyways because it only describes inter-server communication; no client communication. Re:The MSN Coalition (Score:2) It is a good thing (wow, that's scary) that they're involved in this. Re:but aol's primary product is its network (Score:2) Re:What about IRC? (Score:2) Re:Where's ICQ (Score:2) a flaw in your logic (Score:2) Re:Gimme TALK any day... (Score:2) MSN only playing for one reason.... (Score:2) The next step - assuming anyone cares if it is worth fighting over (there is no direct revenue stream) a Microsoft IM client will be installed as part of the WinME desktop, and with any upgrade of any MS product (just like IE is now) and will offer to replace AIM/ICQ for you. The rest of the players are an irrelevancy. Re:Nonsense -- Network effect (Score:2) -- IMHO, encryption isn't that bad of an idea. (Score:2) So, I'm not against encryption in them. (Though Kerberos is a funky choice for this, I'm trying to imagine a KDC for tens of millions of users, and failing. -- Re:Just say NO to monolithic messaging (Score:2) Jabber may be open, and it may be a step in the correct direction (each domain runs their own service, which scales a heck of a lot better to the global Internet), but it's really, really icky on the inside. XML is a bad choice for protocol messages. The use of XML carries far too much baggage for a lightweight/automated implementation. I've been thinking for some time about how a good Internet-wide IM system could be used not just to send silly chat messages back and forth, but also to be a method for client-server interaction. The XML message format requires each piece of software to contain an XML parser and also (from what I've seen) limits the kinds of data you can send back and forth. Why not do what HTTP does -- not care about the content, just specify a header format and let arbitrarily formatted data be attached? In addition, Jabber makes the unfortunate choice of not wanting anything to do with crypto on the protocol level; instead, it wants client folk to slap OpenPGP on top of it. This is another bad decision in two ways: That said, it's probably the best we've got right now, and in their favor, the Jabber folk have worked on this for a long time. I do respect them and their efforts (it's a rare open source project that is built to be more than just a copycat of some other software). I'm just not sure what they've come up with is what we need. Its about bloody well time. (Score:2) I mean really, between what all those people offer, there is a client type that can make anybody happy (unless you like ICQ's bloat anyway). Now if they could all talk to each other, that'd be even better, I could choose a client based on how well it works instead of which network has more of my friends on it. AOL has no real interest right now because they have a monopoly to protect, however if this takes off (and as soon as they have it working I'm going to switch over to it, I really really hate AIM and ICQ) then we can end up with two big incompatable networks, oh joy. Well, maybe somebody on the IMUnified side can make a client that doesn't suck, lord knows ICQ hasn't been able to do that since version 2. My gloomy predictions. (Score:2) If I understand it correctly, both the MSN and Yahoo instant messanging protocols had to be reverse engineered. If they wanted people to write competing clients the obvious thing to do is make the protocol public domain. In the instant messanging world having an established user base is like having a sort of standard. Right now AOL has that and so for these companies it's time to gang up on AOL. But think for a moment... If microsoft was in AOL's position how can you be sure they'd care about Unity and interoperability? And when these companies make their own standard protocol, what then? How do they plan on making money? No one pays for an instant messenging client because you can get AOL for free. Are they going to sell server software? I would actually respect them if that was there plan.--especially if they made a GPL server that ran on LINUX The only other conclusion that I can think of is that they plan to continue with their current business model of selling adds. AT&T I can picture as being interesting in a standard protocol for embedded devices and cell phones etc. But the others are going to sell adds. There are two things you don't want to happen when you start selling adds. 1) You don't want people to switch to another provider. This makes me not expect to see Yahoo selling Instant Messenging servers that will compete with them. 2) You don't want people to figure out how to block your adds. This makes me think that yahoo does not want you to make your own client. Writing this I think I begin to realise how this will be done. There are ways that blocking rogue servers and clients can be done. It will be called "Security." MSN will be interoperable with Yahoo because Yahoo will lease the bandwith and cpu cycles that it's clients will use on the MSN mainfraims. People without leases will not be welcome. This will be called "Unity." Welcome to your bright tomorrow. [Disclaimer] I plan to continue my computer science education and perhaps learn enough to program jabber applications some time in the future. Re:Open IM Standard + Encryption = Useful Tool? (Score:2) You could do what you are talking about with PGP pretty easilly with jabber too. The problem is that no one has done it yet. Probably a dozen different clients out there wouldn't mind canabalizing your code if you made the first jabber client that supported PGP. The other problem is that none of the other protocols are advanced enough to be able to handle fairly complex stuff like that. Jabber transport programmers face the same problem elsewhere as well. AIM for example does not support offline message storage. With MSN you can send little messages that say, "Fred has recieved your message and is composing a reply." but with ICQ you can't do that. But I say go ahead and program the PGP enabled jabber client. Thousands of users will love you for it. Gimme TALK any day... (Score:2) But if you really have to communicate on-line in real time with someone--what's the matter with TALK? I miss it. People hardly use it any more, I guess because a shiny AIM interface is prettier than TALKing through telnet or whatever. Just never caught on with the non-geek and non-college-student crowd, I guess, especially with AIM out there. I pray for the day that AOL goes under, though I fear it'll never happen. "AOL: We're the Largest Censor on the Net, With Over 20 Million Subscribers Under Our Heel!" Re:A Waste of time without AOL. (Score:2) Yes, AOL did submit an Open IM Design to IETF, but it just gives a high level discussion of what an IM protocol might be like; it doesn't say anything about how the AIM protocol currently works. And according to this article by ESR [linuxtoday.com], AOL released the AIM protocol, only to make changes to it once Microsoft began using it, in order to lock Microsoft out. So it doesn't seem like AOL really wants to be open with regards to IM. For a full discussion of AOL vs. the rest of the world (with regards to AIM), see this article [zdnet.com]. Suppose you were an idiot. And suppose that you were a member of Congress. But I repeat myself. Re:Gimme TALK any day... (Score:2) Me either. Why would I want to talk to an AOLer? AOL's huge number of IM/ICQ users is probably phony, anyway. If you ever put an AOL disk into your computer, or bought a machine with AOL's client pre-installed, the stupid thing installs, and it's a bitch to remove completely. What about IRC? (Score:2) I've always wondered why someone hasn't designed an licq type interface to IRC. The infrastructure is already there and the protcols and clients are already open. Why not just make a DCC CHAT ready client that works like the instant messaging clients? Re:IMHO, encryption isn't that bad of an idea. (Score:2) Anyway though, I think the original post really was getting at the way that MS "embraced and extended" the kerberos spec itself, and they just mean that MS would do the same thing with the IM spec if one standard becomes prevalent. ie. they'd change it slightly in a way that meant they'd have an advantage. Which they would I bet too! sig: Re:Yep. (Score:2) sig: Re:Would You Say This? (Score:2) And, any references to the MS anti-trust case are not valid here either, because MS weren't convicted of having a monopoly, they were convicted of using unfair business practices to quash competition unfairly. AOL haven't done any such thing, they've just created a product that everyone ended up using, for various reasons. It's a monopoly MAYBE, but monopolies are not illegal. sig: Re:Would You Say This? (Score:2) Okay, so are you goin to ask what part is illegal now? Since last time you asked right after I explained it. sig: Re:This won't fly! (Score:2) CIS was always underpowered and overcharged (esp. in Europe). I jumped when they started playing games with email interconnect with various ISPs they didn't like. Well, there's always going to be someone dissatisfied. I paid 16DM, about 5 Pounds nowadays, if you're British a month. Didn't seem so terrible to me. CIS was the place to go for technical info in easily accessible format as far as I was concerned, and the place to pass on my experience to others. It was one of the originators and leaders in this whole business. And even you might be prepared to agree that AOL's treatment of CIS users was crass in the extreme, if you were still around to experience it. I never had any problem with emails, btw Re:Just say NO to monolithic messaging (Score:3) Not necessarily. XML parsers have now been implemented that are as small as 1.5K of code. And Jabber doesn't use full-blown XML with DTDs, automatic validation, and all that; it uses it for the sole purpose of creating a structured data stream. The Jabber protocol would be excellent for this purpose. We are exploring such possibilities as embedding XML-RPC or SOAP messages in Jabber to promote client-server interaction over the same stream you might use for two-way human-to-human communication. The existing Info/Query mechanism in Jabber already does this, to a certain extent. XML parsers are readily available, and, as I mentioned above, can be quite small. As for percveived "limitations" on data types, any text-format data can be expressed as XML and sent through a message extension. For binary data, we use the jabber:x:oob (out-of-band data) extension to pass HTTP URIs for data retrieval, which keeps the data from having to be sent if the receiving client does not support binary attachments. First of all, Jabber already supports SSL connections (via the OpenSSL [openssl.org] library) for transparent transport-layer encryption. The only drawback here is that not many Jabber clients support SSL. That being said, I would like to see Jabber support crypto at a level in between the transport layer (SSL) and the end-user level (OpenPGP). But it's not going to be supported until it can be done right, as it's my belief that poorly-done crypto support is worse than no crypto at all. And I might also point out that competing protocols either use no encryption, or use something that's a total joke in terms of real security (e.g., ICQ). Then, too, there are US export regulations to consider (and we have very few non-US developers at this point that could mount any sort of Jabber crypto effort). Eric The preceding was my opinion only, and not the official opinions of Jabber.com Inc. [jabber.com] or The Jabber Project [jabber.org]. -- Re:Except it (WinJab) won't compile. (Score:3) I added a readme.txt yesterday (July 25) to the winjab CVS module that should hopefully resolve the component issues. If you have other issues, please contact me directly via email (check the sourceforge site for the addy). I could _REALLY_ use the help and want to be as accomodating as possible. Except it (WinJab) won't compile. (Score:3) I downloaded the CVS version of WinJab a couple of days after it's release (About 16-July-2000). It wouldn't compile. You do expect a little bit of that with Delphi programs - missing components, etc, but this was crazy. I downloaded everthing I could find, and still it wouldn't compile. There was a whole set of XML stuff missing from CVS. God knows where to find that... (And yes, I registered the type library) I code Delphi for a living, so I'd hate to think how much trouble other people would be having. I left a message on SourceForge about it... now there are a whole lot complaining about that same thing [sourceforge.net], but no answers. I'm a little annoyed about this, because I had a look at the code, and I saw a lot of things I could have fixed for very little effort. (Eg, they are auto-creating all the forms in the project at application start-up. That's a bad thing to do, but pretty easy to fix.) I wanted to help, but I couldn't. Open IM Standard + Encryption = Useful Tool? (Score:3) IMUnified comes up with an open standard for instant messaging. Assuming a large enough user base recognizes this as a good thing (and they likely will as the next "upgrade" of Yahoo! IM will be both standards and backwards compatible) then the worry about getting messages to my cohorts (each of whom use different services) dissapears... but what else happens? Well, if there is a single (or, almost single) standard for IM then writing a client that's useful becomes a much easier task. Having, say, a client which knows how to do MIME would be useful in a nubmer of ways, not the least of which is that PGPMIME is a handy way (and one of many) to move around encrypted dated with arbitrary encapsulation (in this case the IM standard protocol). Suddenly a secure IM platform is available with only a few days coding time, and if the poor sod on the other end of my message doesn't know how to interpret PGPMIME (or whatever else I use) all he gets is a nice ASCII block which is conviently labeled, oh, I don't know, "PGP Encrypted Message"... hmmmm, I think I like where this is going. -- Re:Just say NO to monolithic messaging (Score:3) Thanks for the response, Eric. I was beginning to wonder if I'd gotten swallowed up in the flood of crap that's been posted to all the stories lately. One of these days I'm going to relocate to Advogato [advogato.org] and stay there. :-/ I'm not so sure that I'm comfortable with that. I know that with XML's namespace support, you can easily push XML-based formats inside of one another, but that strategy requires (AFAICT) anything that's not expressible in XML to be sent OOB. The OOB mechanism also would therefore require additional protocol support within the client, beefing its code up just a little more. If I'm understanding it correctly, it also offers a security risk where a sniffer could grab his own copy of the OOB file. I would instead implement an inband message send/ack/reject strategy for short messages; and for larger messages or files, an offer/accept/reject message strategy that could transfer content either on the same channel (blocking further messages) or another channel, but without the overhead of additional transfer protocols. This is cool, but it is not the be-all and end-all. I've been over the protocol on a few occasions in the past and I just recently looked at the whitepaper. I don't believe this addresses the issue of how a client attached to one server can authenticate itself to another server to the point of being able to subscribe to presence changes of a user of the latter server. If you had even a simple DSA implementation, you could have the user of the latter server say "I'll accept requests from this public key, this public key, etc." and authenticate based on that. I admire you for taking this stand. This is a fault of those protocols, and something that needs to be corrected by competing proposals. I respectfully submit that it is not an excuse to not implement cryptographic security and authentication. US policy is a pretty darned good excuse, on the other hand. :-/ A Waste of time without AOL. (Score:3) Frankly I don't understand why people still hassle AOL, didn't they submit their Open IM Architecture Design [aol.com] to the IETF? The Important Questions to Ask (Score:3) Otherwise, ladies and gentlemen, this will fail. This has potential (Score:3) Also, I really do hope that this new network supports what Licq (the most used Linux ICQ client) has supported for a while: encrypted messages. If one person using Licq sends a message to another, the message is encrypted (if you turn the feature on). This functionality is ESSENTIAL to the growth of IM if it is ever to be used for business use (as their site suggests it will be). The MSN Coalition (Score:3) After all, they were going against AOL head to head for a while by making MSN Messenger compatible with AIM and then they just gave up. How un-Microsoft like, it seemed back then. So now they engineer this coalition(with the proper IETF backing of course) and they've got a real battle plan again. Obviously they haven't given up. I wonder if messaging clients are something that could be complex enough that you'd get that software rivalry like there was between Netscape and IE. Does anyone care about the quality of their messaging client? Re:This won't fly! (Score:3) they deserve to be as big as they are for helping the masses Tell that to the (ex-)Compuserve users. AOL took over a great service, removed all the interesting technical forums which made it what it was, and foisted their stupid mass oriented childishness on the few diehards remaining. Yep. (Score:4) You've read about these things in history class, kids. Now you can see it as it happens. -- Why should I care? Lets see some real improvement (Score:4) AIM and ICQ work fine... I'm not getting charged for them... there are clients for lots of platforms... so who cares about making a standard to interoperate with them? Only people that see a "market" and wish they were part of it. I really can't bring myself to care until the technology improves. When someone invents the fully distributed datagram-only version with automatic encryption and message signing and no central point of failure, I will be the first to sign up. (I've been muttering about doing that to IRC for years, I suppose I should sit down and code something--except I hate writing GUIs, and that is the part most people would notice.) Until then, unless AOL is doing something weird with my messages, or tries to extract a fee from me, what difference does it make that Micros~1 and whoever else can't join the party? As long as we are going to make a "standard", lets redo the protocol from the ground up and fix all the flaws... and yes, I've seen the IETF draft standard, I think its fugly. Publishing standards for the existing tools would be nice, but what right has anyone to force AOL to open their protocols? Personally I don't see anything sinister in AOL acquiring Mirabilis and Nullsoft and Netscape... they just want to make sure those tools continue to exist, if only so that the value of the Internet experience of their own customers is improved. Or does someone have evidence to the contrary? Just say NO to monolithic messaging (Score:4) What these companies want is to wrest the eyes and clicks of the countless AIM users into using their advertising supported clients. The "open" here is a misnomer that only means "interoperable" which is far from the same thing. It doesn't matter that the huge, dominating overlord is made up of a number of seperate organizations, it's still a huge, dominating overlord. The word for this type of union is "cartel." If you want a real open standard for messaging, you want Jabber [jabber.org]. Jabber is an open standard, it's open source, and most importantly, it just makes sense. There are many reasons why it's better than the current adware messengers, but the best reason is that Jabber is a decentralized network. There's no single, monolithic entity that you must rely on to supply your connectivity. In other words, Jabber is built on the same model of the internet itself. So download Jabber, but don't sign up at jabber.(org|com). No, instead you should start your own server (if you're able), or encourage your ISP to set up a local server. I mean, what would you rather be known as, "foo82351@jabber.com", or "yourname@yourhost.net". Why Unify? (Score:4) AOL, essentially, owns the instant communication market. Instant Messenger AOL-Time-Warner, AOL and ICQ (both owned, though not created, by the same company) use radically different, fundamentally dissimilar naming conventions. When you start introducing others into the fray, a unified protocol or client could easily become a hindrance or lead to complications. AOL has more-or-less earned (or acquired) the instant messenging market. When something better comes out, I have no doubt that it will take the place of AIM or ICQ. Until then, though, incompatible standards shouldn't be foisted upon them. yours, john Jabber (Score:5) I would highly encourage you to visit our site Jabber.org [jabber.org] for all your development needs, and Jabbercentral [jabbercentral.com] for your end user related needs. Even more so we encourage you to download our server and seutp your own system, because we are similar in idea to how email works, anyone can run a server and talk with all the currently existing Jabber servers. With ~20,000 users between just the public jabber.org and jabber.com servers we're growing extremely fast, and we hope that others will take part in our growth. --Temas Jabber ROCKS! Nonsense -- Network effect (Score:5) AOL owns the two largest IM networks, AIM/AOL and ICQ. This system is an obvious one. Why, the rest of the players are tiny. If they merge and can grow, they can become significant. They need to count on users switching to the "standard" so that they can force AOL to play (after which, Microsoft takes over the non-AOL user market). However, AOL still hasn't (to my knowledge, I mostly use AIM as my friends have all switched from ICQ) gotten ICQ and AIM to play nicely. Now, if AOL feels any threat, then they merge the top two messaging clients and get even bigger network effects. Right now, AOL doesn't find it critical... they just don't put effort into ICQ and let everyone drift to AIM. If they needed two, they'd merge the databases. AOL will never join one of these groups. These groups won't make a dent, as Instant Messenger/ICQ dominate the market. It would be suicide to work with this group. Who would download the AOL client if the Microsoft one shipped with Windows and was equivalent (good enough)... Remember Netscape? AOL is too smart for this. Alex
https://slashdot.org/story/00/07/26/0023214/imunified-playing-red-rover-with-aol
CC-MAIN-2018-22
refinedweb
7,413
73.27
Re: how do I convert back a boost shared_ptr into a reference? Discussion in 'C++' started by phlip,: - 1,001 - tom_usenet - Oct 9, 2003 boost::shared_ptr inside stl::listJames Mastro, Nov 13, 2003, in forum: C++ - Replies: - 1 - Views: - 2,194 - Cy Edmunds - Nov 13, 2003 boost::shared_ptr and operator->()Derek, Dec 8, 2003, in forum: C++ - Replies: - 2 - Views: - 705 - Derek - Dec 8, 2003 Problems mixing boost::lambda::bind and boost::shared_ptr..Toby Bradshaw, Jun 1, 2006, in forum: C++ - Replies: - 6 - Views: - 1,930 - Kai-Uwe Bux - Jun 2, 2006 #include <boost/shared_ptr.hpp> or #include "boost/shared_ptr.hpp"?Colin Caughie, Aug 29, 2006, in forum: C++ - Replies: - 1 - Views: - 841 - Shooting - Aug 29, 2006
http://www.thecodingforums.com/threads/re-how-do-i-convert-back-a-boost-shared_ptr-into-a-reference.624409/
CC-MAIN-2015-27
refinedweb
117
59.64
Java Bitwise Operator using efficiently to improve Performance Many of us know the various operators available in Java. But do we really use them all efficiently. Here I am illustrating one simple example which can show the high performance gain with bitwise operatator than the standard solution. Lets calculate the mathematical expression xn i.e. x’s power n. To solve this problem anyone can easily say its just one loop with n times and adding a in that loop. Thats very simple and fast. Really? Lets analyze it, we have just used O(n) complexity to find the result which means 820 will take 20 loop iterations to calculate it. xn = x * x ...... * x (n times) Do we really need so much iterations to calculate it? Following mathematical formula can help us to reduce the O(n) complexity to O(log n) complexity Bitwise operator can be used to achieve this by shifting the bits of power. Following sample code is self explainatory. [java] public class PowerAofB { public static void main(String[] args) { // Basic way with O(n) int a = 9; int b = 12; long result = 1; for (int i = 1; i <= b; i++) { result *= a; } System.out.println(result); // Efficient way with O(log n) System.out.println(ipow(a,b)); } private static long ipow(int base, int exp) { long result = 1; while (exp != 0) { if ((exp & 1) == 1){ result *= base; } //right shifting bytes with sign 1 position //equivalent of division of 2 exp >>= 1; base *= base; } return result; } } [/java] Comparison between basic approach and new approach Image Reference:
https://www.tothenew.com/blog/java-bitwise-operator-using-efficiently-to-improve-performance/
CC-MAIN-2022-21
refinedweb
261
55.95
Code developed for the old 1.x versions of C++CSP will not compile or function the same with C++CSP2. I realise that this is very annoying for those who have already developed programs for C++CSP v1.x, and now have to migrate them. The reasons for this lack of compatibility include: To help all previous users of C++CSP v1.x to convert their programs for use with C++CSP2, I have prepared this guide. I will go through the various areas of C++CSP2 that have changed. Thankfully, almost all of these changes will result in a compile error. So if you go through each compile error, then with the help of this guide you can convert your program to using C++CSP2 properly. Code blocks are provided that show the OLD code, and the corresponding NEW code. #include <csp/csp.h> //OLD #include <cppcsp/cppcsp.h> //NEW The functions used to start and stop the C++CSP2 library have had their names changed (for similar reasons to the above): Start_CSP(); //OLD Start_CSP_NET(); //OLD End_CSP(); //OLD Start_CPPCSP(); //NEW End_CPPCSP(); //NEW The sleep/wait functions used to be members of csp::CSProcess. This caused annoyance if you wanted to call these functions in a class that was not itself a process. So these functions have now been moved to being stand-alone: class SomeProcess : public CSProcess { protected: void run() { sleepFor(Seconds(1)); //OLD, sleepFor was a member of CSProcess SleepFor(Seconds(1)); //NEW, SleepFor is a function in namespace csp Time t; CurrentTime(&t); t += Seconds(1); sleepTo(t); //OLD, sleepTo is a member of CSProcess SleepUntil(t); //NEW, SleepUntil is a function in namespace csp } }; Similarly, yield used to be a member function of csp::CSProcess. There are now two stand-alone yield functions in C++CSP2; csp::CPPCSP_Yield() yields to other user-threads in the same thread, and csp::Thread_Yield() yields to other kernel-threads. CPPCSP_Yield is useful if you are not doing any channel communications or synchronisation and want to allow other user-threads to run. Thread_Yield is perhaps less useful; your thread will be switched out at the end of its time-slice anyway. There are now two process classes; csp::CSProcess and csp::ThreadCSProcess. Usually you will want to use CSProcess as before; if you do not change any of your existing classes from inheriting from CSProcess, everything will work fine as before. For an explanation of the purpose of csp::ThreadCSProcess, click on its link to read the documentation. The constructor of csp::CSProcess used to have two parameters, one which was a mandatory stack size and one which was a mysterious reserve size. This constructor now takes one optional argument (the stack size). The reason for it becoming optional is not that I have added a magical way of determining the right stack size (alas!), but because there is an arbitrary high default value of 1 megabyte. All your existing processes that specify a stack size should be fine as before -- although if you are moving to 64-bit, remember that some of your data types will double in size. You can no longer specify a reserve size -- if you have any code that did specify the second parameter (which is unlikely), simply remove the second parameter. One of the major changes to the library has been in the area of running processes. The new mechanism is explained in detail on the Running Processes page. Below are examples of how to convert your existing code to the new system. It can either be converted as-is, to continue using user-threads, or you can change to using kernel-threads: CSProcess* processA = new Widget; CSProcess* processB = new OtherWidget; Parallel(processA,processB,NULL); //OLD RunInThisThread(InParallelOneThread (processA) (processB) ); //NEW, using user-threads //or: Run(InParallelOneThread (processA) (processB) ); //NEW, using kernel-threads (processA and processB together in a single new thread) //or: Run(InParallel (processA) (processB) ); //NEW, using kernel-threads (processA and processB together in separate new threads) Sequential(processA,processB,NULL); //OLD RunInThisThread(InSequenceOneThread (processA) (processB) ); //NEW, using user-threads //or: Run(InSequenceOneThread (processA) (processB) ); //NEW, using kernel-threads (processA and processB together in a single new thread) //or: Run(InSequence (processA) (processB) ); //NEW, using kernel-threads (processA and processB together in separate new threads) You will notice that the syntax has changed. Gone is the annoying C-style NULL-terminated vararg list, replaced by a new C++ mechanism. Each parameter is bracketed separately -- no commas! There is a new csp::Run method that can take sequential or parallel lists. You can also easily compose parallel sequences or sequenced parallels. All the detail is on the Running Processes page. The mechanism for forking has also changed. The old mechanism involved spawning a process with a given barrier to synchronise on when it was done. The new mechanism uses the Scoped Classes idea. CSProcess* processA = new Widget; //begin OLD Barrier barrier; spawnProcess(processA,&barrier); //spawnProcess was a static method of CSProcess //... Do something ... barrier.sync(); //wait for processA to finish //end OLD //begin NEW { ScopedForking forking; forking.forkInThisThread(processA); //using user-threads, processA remains in this thread //or: forking.fork(processA); //using kernel-threads, processA is in a new thread //... Do something ... } //When forking goes out of scope, it waits for all the forked processes to finish //end NEW The new csp::ScopedForking class is a little different, but ultimately it is easier and nicer than the old mechanism. This way you can't forget to synchronise on the barrier and wait for the processes, even if an exception is thrown. C++CSP v1.x had a single channel input-end type; Chanin. Unbuffered unshared channels supported all its functions, but buffered channels did not support extended input and channels with shared reading ends did not support alting. If you tried to use unsupported functionality, a FunctionNotSupportedException was thrown. This has now been mixed through two major changes: If you use a channel-end in an alt, you will need to change the type from Chanin to AltChanin. You will get compile errors otherwise -- complaining about the lack of an inputGuard() method (although this method itself has now changed -- see the section on Alting below). The changes made to C++CSP to support kernel-threads in C++CSP2 meant that this system could no longer be retained. Although this does help make the library similar, it will make simple parallel communications more cumbersome. The best way to mimic the functionality is to use the csp::common::WriteOnceProcess and csp::common::ReadOnceProcess processes: //in and out are Chanin<int> and Chanout<int> respectively int inInt,outInt; outInt = 9; //begin OLD: ParallelComm pc(in.parIn(&inInt),out.parOut(&outInt)); pc.communicate(); //end OLD //begin NEW Run(InParallelThisThread (new ReadOnceProcess<int>(in,&inInt)) (new WriteOnceProcess<int>(out,&outInt)) ); in.checkPoison(); out.checkPoison(); //end NEW The checkPoison() calls are important. If the old ParallelComm encountered poison, it would throw a PoisonException. Running the sub-processes as above will not detect poison; if the processes do attempt to use poisoned channels, they will fail and stop. To find out if the channels are now poisoned, you must check the poison manually. Even then, you will not know using the above code whether or not the channel communications succeeded before the poison or not. There are other ways of implementing the same functionality as ParallelComm. One option would be to perform the communications sequentially. This would make things much easier, but it is not always possible (this could lead to deadlock). Another option, if you do not mind some buffering, is to use buffered channels sequentially, or to use a csp::common::Id process to achieve a similar effect. One2OneChannel<int> c; Chanin<int> in = c.noPoisonReader(); //OLD Chanin<int> in = NoPoison(c.reader()); //NEW The names of the buffered channels have changed, from One2OneChannelX to BufferedOne2OneChannel. The original names were actually the result of a mix-up but were never changed, until now. Other changes to the buffered channels are detailed in the Buffered Channels section below. The names of the channel buffers have always changed. Previously - in line with JCSP - the channel buffers were derived from the ChannelDataStore class. Copies of buffers were obtained by calling the clone() method of the buffer. In C++CSP2, channel buffers now derive from csp::ChannelBuffer. The interface has changed to be more flexible and support new features - this is only of concern if you previously implemented your own buffers. Instead of a clone() method, copies of buffers are obtained from a channel-buffer factory. //begin OLD: Buffer<int> buffer; One2OneChannelX c(buffer),d(buffer); //end OLD //begin NEW: FIFOBuffer<int>::Factory bufferFactory; BufferedOne2OneChannel c(bufferFactory), d(bufferFactory); //end OLD You will note that the buffer names have also changed. Buffer has become csp::FIFOBuffer and InfiniteBuffer is now csp::InfiniteFIFOBuffer. ZeroBuffer has gone (use an unbuffered channel instead) and csp::OverwritingBuffer has been added. The other major change to buffered channels is that extended input on buffered channels is now supported. The behaviour is roughly intuitive - in the non-overwriting FIFO buffers, the item of data is read from the buffer at the beginning of the extended input but not removed until the end of the extended input. However for the overwriting buffer (to prevent the writer ever blocking), the data is effectively removed at the beginning of the extended input. //begin OLD: class MyProcess { Chanin<int> in; Chanout<int> out; int n; public: void extendedAction() { out << n; } protected: void run() { while(true) { in.extInput(&n,this,&MyProcess::extendedAction); } } }; //end OLD //begin NEW: class MyProcess { Chanin<int> in; Chanout<int> out; protected: void run() { while(true) { int n; { ScopedExtInput<int> extInput(in,&n); out << n; } //extended input finishes at end of scope } } }; //end NEW Anyone who had to use the old method will appreciate the comparative ease of this new version. No more awkward member functions or static functions; the code is inline where you would want it to be. This method is also exception-safe; in the case of an exception being thrown during an extended input (for example, poison), the extended input is still ended safely. More details are available on the csp::ScopedExtInput page. Barrier-ends (csp::BarrierEnd) are always "encased" in a csp::Mobile wrapper: //begin OLD: Barrier barrier; barrier.enroll(); barrier.sync(); barrier.resign(); //end OLD //begin NEW: Barrier barrier; Mobile<BarrierEnd> barrierEnd(barrier.end()); barrierEnd.enroll(); barrierEnd.sync(); barrierEnd.resign(); //end NEW Processes that used to take a Barrier* parameter to their constructor should now take a Mobile<BarrierEnd> parameter. I have now reversed the situation in C++CSP2, returning to the JCSP method. I realise that this will be very confusing to existing C++CSP v1.x users, but I think this tough transition is for the best. It will be less confusing for new users and allows extended inputs to be done in a nice way. Existing alting code will break because the inputGuard method no longer takes a parameter, so you will be able to see where the code needs changing. You must removed the parameter, and instead manually perform the input inside the switch statement. For example: //begin OLD: class MyProcess { Chanin<int> in0,in1; Chanout<int> out; int n0,n1; public: static void extInput(CSProcess* proc) { MyProcess* myproc = (MyProcess*)proc; myproc->out << myproc->n1; } protected: void run() { Alternative alt( in0.inputGuard(&n0), in1.extInputGuard(&extInput,&n1), new RelTimeoutGuard(csp::Seconds(1)), NULL); while (true) { switch (alt.priSelect()) { case 0: //no need to perform input out << n0; break; case 1: //no need to perform input //The real code was in the extended action break; case 2: //timeout out << -1; break; } } } }; //end OLD //begin NEW: class MyProcess { AltChanin<int> in0,in1; //Now AltChanin instead of Chanin Chanout<int> out; protected: void run() { int n; Alternative alt( boost::assign::list_of<Guard*> (in0.inputGuard()) (in1.inputGuard()) (new RelTimeoutGuard(csp::Seconds(1))) ); while (true) { switch (alt.priSelect()) { case 0: //must perform input: in0 >> n; out << n; break; case 1: //must perform extended input: { ScopedExtInput<int> extInput(in1,&n); out << n; } break; case 2: //timeout out << -1; break; } } } }; //end NEW You will notice a few of the other changes; AltChanin must be used for alting channel-ends, instead of Chanin. The guard list that is passed to the Alternative is no longer the clumsy NULL-terminated vararg list, but instead uses the cleaner boost::assign library. Guards for extended inputs are now identical to normal input guards - you simply choose in the switch statement whether to perform an input or an extended input. You can even vary it each time you perform an alt, if you wanted. As before, the Alternative takes care of deleting the guards itself.
https://www.cs.kent.ac.uk/projects/ofa/c++csp/doc/migration.html
CC-MAIN-2017-13
refinedweb
2,113
52.39
SharePoint metadata, site navigation, and publishing site features This article explains how to manage metadata and customize site navigation and publishing site features in SharePoint Online by using the add-in model. It also covers ways to work with common web programming patterns and libraries to help customize SharePoint publishing site branding. Terms and concepts Table 1. Key metadata, navigation, and publishing terms and concepts Prerequisites for using CSOM to brand publishing sites By default, web content published to public-facing SharePoint on-premises websites is available to anonymous users. By default, both CSOM and REST are not available to anonymous users. Important This scenario presents a potentially serious threat to on-premises SharePoint sites. Before you use the remote provisioning model described in Use remote provisioning to brand SharePoint pages to provision branding to publishing sites, make sure that your site's security and permissions are set correctly, and consider the security implications of anonymous access. In the event that the site administrator creates a new web application that includes a site collection that uses the publishing template and also enables anonymous access, anonymous access will be available to every user of the site when the application is uploaded to the add-in catalog. Because anonymous access is enabled for the on-premises SharePoint publishing site, what happens if a user who is not authenticated navigates to the site? If you create a SharePoint-hosted add-in and add a client add-in part to the project, go to Central Administration > Add-ins > Manage Add-in Catalog and create an add-in catalog for the web application, publish the SharePoint-hosted add-in using Visual Studio to create the add-in package, and then upload the add-in package to the add-in catalog. At this point the site collection administrator can add the add-in to the publishing site. The add-in is now available to add to a page on the publishing site. If you edit the main page of the publishing site and publish the add-in to it, the add-in works as expected. Choosing the linked title of the add-in loads the full-page experience. If SharePoint throws an error, this means that the anonymous user does not have access to use the CSOM. This makes sense because CSOM and REST are not available by default to anonymous users. Be aware that disabling Use Remote Interfaces permissions can introduce a security risk In Site Permissions, the Require Use Remote Interfaces permission check box is selected by default. You can clear the Use Remote Interfaces permission check box to allow anonymous users to have access to use CSOM and REST. This decouples the user from Use Remote Interfaces permissions, which grants the user access to SOAP, WebDAV, and CSOM. Clearing the check box also removes the ability to use SharePoint Designer. There might be times when you want to remove the ability to use SharePoint Designer, but still permit the use of CSOM. The Use Remote Interfaces permission check box enables you to let anonymous users use CSOM without requiring them to have Use Remote Interfaces permissions. When the Use Remote Interfaces permission check box is cleared, and you choose the linked title of the add-in to load the full-page experience, SharePoint does not throw an error. Basic error handling code interprets this case as an anonymous user. Caution - When you add apps to public-facing SharePoint sites that use the Publishing template, do not clear the Use Remote Interfaces permissions check box in Site Permissions. Enabling CSOM for anonymous users presents a possible information disclosure risk; it divulges much more information than you would anticipate. That said, even with access to the full CSOM, SharePoint permissions still apply. Anonymous users will only be able to see lists or items that have been explicitly made available to anonymous users. More than what you see on the webpage is available to anonymous users via CSOM and REST. - Unless absolutely necessary, do not clear the Require Use Remote Interfaces permission check box when anonymous access permissions are enabled on a SharePoint on-premises publishing site. Doing so could expose both published and unpublished site content to anonymous users, and could leave your site open to a denial of service attack. Use the ViewFormPagesLockdown feature To prevent users from accessing forms pages (for example, Pages/Forms/AllItems.aspx) in a public-facing SharePoint site, use the ViewFormPagesLockdown feature. It is designed to prevent users from seeing Created By and Modified By information. This feature removes the permission to View Application Pages or Use Remote Interfaces. When this feature is active, users cannot go to Pages/Forms/AllItems.aspx and view items in that library. If CSOM and REST are available to all anonymous users—if the Use Remote Interfaces permissions check box is cleared—although they still can't see Created By and Modified By information in the browser, they can use CSOM or REST to access that information. Configure anonymous access (security trimming) By configuring anonymous access for the web application, you specify the anonymous policy: Deny write—Has no write access . This means that users with anonymous access can't write to the site—even with CSOM or REST code. Anonymous users can only see the information that was granted to them when anonymous access to the site was configured. Unpublished pages are not visible to anonymous users by default. They can only see lists that enable anonymous access. Important If the Use Remote Interfaces permissions check box is cleared, use the permissions model and other precautions to be sure that anonymous users don't have access to things that they should not. Prevent denial of service attacks There is no caching with CSOM. This means that a malicious attacker can query thousands of items from lists simultaneously, all while staying under the default list view threshold and taxing the SharePoint database. This could spread and escalate into a full-blown denial of service attack. Use app-only policy You can use app-only policy with provider-hosted add-ins. App-only policy permits the add-in to perform actions that the current user is not authorized to perform. For example, a user with read-only permissions who is notable to write to a list can use an add-in with app-only permissions to write to a list. For more information, see Authorization and authentication of SharePoint Add-ins and Understanding Authentication and Permissions with Apps for SharePoint and Office (Channel 9 video). Implement SSL When you use the add-in model, implement the Secure Sockets Layer (SSL) protocol to manage security of message transmissions on the Internet. SSL works by the remote website, sending an access token in the HTTP header Authorization with a value of Bearer + a base64-encoded (not encrypted) string. Important SSL protects your SharePoint publishing site from attackers who want to get to an authorization token and exploit that access. Remote provisioning and publishing sites You can use remote provisioning practices to provision branding and other customizations to SharePoint publishing sites. Publishing sites depend on content types and the ContentTypeId, which links content types to page layouts and display templates. Customizing and provisioning SharePoint publishing page content depends on this functionality. Other aspects of custom publishing site provisioning behavior, such as managed metadata services and managed navigation, do not depend on ContentTypeId and are fully supported in CSOM. Other publishing site customization options, such as device channels and display templates, don't require custom CSOM. They depend on Design Manager features, CSS, and HTML. They are post-provisioning customizations that you build from scratch and do not need to migrate. Managed metadata The managed metadata feature, first introduced in SharePoint 2010, enables you to define a custom hierarchy, or taxonomy, of metadata tags for use in SharePoint. If you want to create a custom site navigation, you can use the managed navigation feature, which is built on the managed metadata infrastructure. A taxonomy is a hierarchical classification of words, labels, or terms that are organized into groups based on similarities. The smallest unit in a SharePoint taxonomy is the term. Terms can be grouped into term sets. Term sets can be grouped by affinity into larger groups. For a brief introduction to taxonomy in SharePoint, see A brief introduction to Enterprise Managed Metadata in SharePoint 2010 and Introduction to managed metadata in SharePoint 2010. SharePoint 2013 introduced new APIs and functionality to the managed metadata feature set. Managed metadata programming model For SharePoint, the .NET Server programmability model for managed metadata is defined in the following set of namespaces: The equivalent CSOM classes are in the Client.Taxonomy namespace namespace. Unlike some other areas of the SharePoint object model, for managed metadata, there is a close affinity between the .NET Server programming model classes and members and the CSOM classes and members. The following are some key differences: CSOM does not support content type synchronization. The Group class, which represents the top layer of organization in the TermStore class, is only available in the .NET Server object model. Its equivalent in CSOM is the TermGroup class. The GroupCollection class, which represents a collection of Group objects, is only available in the .NET Server object model. Its equivalent in CSOM is the TermGroupCollection class class. CSOM includes the CustomPropertyMatchInformation and LabelMatchInformation classes that keep custom property and label data in sync with the server. The following table compares classes in the .NET Server object model and the CSOM object model. Table 2. Comparison of classes in the two models Page layouts For publishing sites, the page layout defines the layout of a specific class of pages. It also defines the customizable regions of a page with content placeholders, which are filled in by content from matching regions on page layouts. Page layouts are usually based on a custom content type. Content types define custom content fields that you want to display on a page. Usually, you'll create a custom content type that includes fields that map to the page design you or your design team had previously planned. Custom field controls can include text, images, video, or other types of content. SharePoint provides content types for Article, Catalog, Welcome Page, and more. Access the page layout content types by going to Site Settings > Site Content Types. These default page layout content types can serve as parent content types for a custom content type that you create. All page layout content types inherit from the Page content type. After you create a custom content type, SharePoint displays the columns that the new content type inherited from the Page content type. You can add new site columns to represent new custom fields that you want to display in your page layout. Specify a type for each site column. A type is a value such as "single line of text" or "Full HTML". Consider factors like the degree of descriptiveness or control that the user should have with the field when you specify its type. After you create all the fields that store the content in your page layout, you can create the page layout in Design Manager. For more information, see Create a page layout in SharePoint. After you create the page layout, publish it by going to Site Settings > Master pages and page layouts. An HTML file and an ASPX file are present. The HTML file is the master, and you can use any HTML editor to edit it. After you save the file and publish it, Design Manager incorporates changes and converts the updated HTML file to ASPX format, which SharePoint uses to render the page. To publish the page layout, select the HTML file and choose Publish in the ribbon. To create a page based on the new layout, go to New Page > Page > Page Layouts to see the new page layout in the list of available page layouts. When you choose the new page layout, you should see all the new fields that you specified when you created a new content type for the new page layout. If you view the page and the HTML isn't rendering the way you expect, you can edit the HTML and then use Design Manager to upload the updated file. Site navigation There are four kinds of site navigation: - Global navigation - Local navigation - Structured navigation - Managed navigation Global navigation refers to navigation elements that help users move from one SharePoint site to another. Local navigation refers to navigation within a SharePoint site. Structured and managed navigation are a bit more involved. Structured navigation Structured navigation is a static approach to implementing navigation on SharePoint sites. It usually matches the company's structure, which requires restructuring the SharePoint site navigation. Restructuring work often means moving subsites and/or pages, and refreshing links to point to new targets. Structured navigation might be sufficient for fairly flat, shallow site structures if your company structure (and therefore site structure) is stable for long periods of time. For deeper and more complex site structures, and companies with publishing site navigation structures that need to grow and change dynamically, managed navigation might be a better option. For more information about structured navigation, see How to: Customize Navigation in SharePoint Server 2010. Managed navigation Managed navigation is built on the core publishing site and taxonomy infrastructure. Managed navigation is bound to a single site collection. It uses term sets and terms to define global and local navigation. For example, you can create a term set that defines global navigation overall, and then add terms to that term set for specific navigation elements in the global navigation. You can find more information about managed navigation in the following articles: The following are some key high-level points about classes, methods, and properties in the SharePoint navigation extensibility model for publishing sites: NavigationTerm and NavigationTermSet classes add properties and methods that are specific to managed navigation. Additional state is stored in the CustomProperties property of the NavigationTerm class. NavigationTerm and NavigationTermSet classes have two modes: editable, and read-only. In the .NET Server object model, NavigationTerm objects are stored in the taxonomy navigation cache, which can only be accessed by functions in the TaxonomyNavigation static class. PortalSiteMapNodeProvider objects in the .NET Server object model provide an interface between the data-driven site navigation features and site map data sources. Usually, you write a custom site map node provider to store site maps in an XML file or a data format that's not supported by SharePoint by default. CSOM includes some unique classes and enumerations: The NavigationLinkType enumeration defines the type of navigation node in a navigation tree. You can specify a node as a root node, a friendly URL, or a standard link. The StandardNavigationScheme enumeration identifies the navigation as either global or local. The StandardNavigationSource enumeration includes three choices for both global navigation and local navigation. Each choice represents a state that corresponds to the configuration of underlying providers. The StandardNavigationSettings class manages the global and local navigation schemes. The following table lists the publishing navigation classes in the server object model and their CSOM equivalents. Table 3. Publishing navigation classes Publishing site features SharePoint and SharePoint Online include a few features that are specific to SharePoint publishing sites: Device channels enable you to apply a single publishing site design to multiple devices and browsers. Display templates make it possible to brand and customize the appearance of search-related web parts. Image renditions define the dimensions that are used to display images on pages in SharePoint publishing sites. You can implement these features by using classes in the Publishing namespace of the CSOM programming model. Device channels and device channel panels You can use device channels and device channel panels to optimize your site for phones and tablets. By creating a unique channel for each device you want to target, you can render a SharePoint publishing site in more than one way. You can author a single site once, and then map the site and its content to different master pages and style sheets to accommodate different targets. You create channels by using the Design Manager. After you create a channel, map it to the mobile device or browser with the user agent string of the incoming device. A device can belong to more than one channel. In that case, you can rank channels in the event that a device belongs. For example, if you create a channel for smartphones and a channel for a specific device configuration, you can rank the channels so that devices with the specific configuration get the channel for them, and all other smartphones get the smartphones channel. You can create up to 10 channels (including the default channel) in Design Manager. The default channel captures all traffic not caught by one of the other channels. When you create a new channel, complete the fields listed in the following table. Table 4. Device channels Device channel panels After you create device channels, map a master page to each one. Because master page customizations are increasingly rare, this is often the default master page (seattle.master). If you create a unique master page for one or more device channels, you can reference a different CSS file than the master page for the default channel. Page layouts that you create work with every channel you create. You can use the Device Channel Panel control to differentiate page layout designs between channels. For more information, see Add a Device Channel Panel snippet in SharePoint. The device channel panel is a container control that is mapped to one or more channels. You can add a device channel panel control to a page layout, and the panel will control what content is rendered in each channel. When one or more of those channels are active when the page is rendered, all the contents of the device channel panel are rendered. Use the device channel panel to determine when to include specific content for one or more specific channels. Consider a page layout that includes ten fields. Some of those fields are available to all channels, and some should only be rendered in specific channels. For example, consider a mobile header banner field that only renders on smartphones, or a large custom sidebar that only renders on desktops and tablets. You can also use the device channel panel to change the styling and placement of content on a page by adding channel-specific CSS. For more information, see Brand snippets by using CSS in SharePoint. User-agent strings and device channels A user-agent string is a small string of data that identifies the browser. This information can be sent to the server, which identifies the user agent. Device channels assign a request to a corresponding device channel based on the user-agent string (or substrings) of the device (or browser) the user is browsing from. The front-end web developer creates and sets up channels to capture traffic. For more information, see What Will Windows Internet Explorer Report as the User-Agent String? Order of resolution for device channels When you create multiple channels, put them in the order in which you want them to resolve. The first channel that includes a device inclusion rule that matches the user agent string is used. The following table shows an example of this rule. Table 5. Example of device inclusion rule If order 1 is active, a user requesting a page from a Windows Phone 8 receives device channel 1 labeled Windows Phone 8. A user with any other Windows phone would use channel 2, and everything else would use channel 3. However, using order 2, a user requesting a page from a Windows Phone 8 would always receive device channel 1 labeled Windows Phone and would never use the device channel specified for it. After you define and order device channels, you can apply different master pages to each channel. By default, all channels will use the master page of the default channel. Note CSOM does not include a public API for manipulating device channels and device channel panels. Display templates SharePoint publishing sites use display templates to control which managed properties are shown in the search results, and how they appear in the web part. Only Search web parts use display templates; the Content Query web part is not a Search web part, and does not use display templates. The following table lists the types of display templates, in the order in which SharePoint applies them. Table 6: Types of display templates |Display template|Description| |:-----|:-----| |Control Display templates|Applies to the entire web part, so SharePoint applies it first, and only once. It provides HTML that structures the overall layout for presenting search results. For example, a control display template might provide HTML for the heading and the beginning and end of a list. This template is rendered only once in the web part. | |Group Display templates|Applied second, and is applied once per group to the Search Results web part. | |Item Display templates|Applied last unless a Filter Display template is applied. Item Display templates are applied to each item. This template determines how each item in the result set is displayed in the web part. For example, it might provide the HTML for a list item that is plain text, a list item that contains a picture, or a list item that formats a block of additional links and summary description information to help provide more context for the search results. | SharePoint stores display templates in the Display Templates folder in the Master Page Gallery. Each display template is associated with a content type in the Master Page Gallery. To identify the content type for each display template file while using a mapped drive, use the file name. The event receivers that convert and update master pages and page layouts from HTML to JavaScript also convert display templates from HTML to JavaScript. The conversion and synching is unidirectional; it does not convert from JavaScript back to HTML. Note CSOM does not include a public API for manipulating display templates. Display template structure Each display template contains the following: A title. A header that contains custom elements bounded by a <mso:CustomDocumentProperties>tag. A <body>tag that contains a script block. A <div>tag. The custom document properties provide important information to SharePoint about the display template. Each display template is associated with a content type, which is identified by <ContenTypeId>. You can set other properties that determine whether to hide or show the template in the list of available display templates for the web part, the HTML to JavaScript managed property mapping, the context in which the display template is used, whether a .js file is currently associated with the display template HTML, and whether the conversion from HTML to JavaScript was successful or if warnings and errors were produced. From within the <script> tag, you can reference external CSS or JavaScript files outside the main display templates HTML file. If content approval is required in the Master Page Gallery, all CSS, JavaScript, and other resources files must be published before they are available to master pages and page layouts. For more information, see Require approval of items in a site list or library. The <div> tag contains an ID that matches the name of the display template HTML file. Place CSS or JavaScript that you want to include that customizes how this web part is displayed in the <div> block. Display template processing SharePoint defines display templates in HTML files and JavaScript. If in Design Manager you change an HTML file that contains a display template definition and save changes, SharePoint compiles changes into a JavaScript file that has the same name. SharePoint uses this JavaScript file to render web parts on pages. Important Do not edit the JavaScript file that contains the display template definition. Only update the HTML file. The conversion process requires the HTML file to be XML-compliant. For example, use <br>, not <br/>. For more information, see Convert an HTML file into a master page in SharePoint. Creating new display templates The easiest way to create a new display template is to modify an existing template. Different display templates change the appearance of different search-related web parts, including the Content Search web part, the Refinement web part, the Taxonomy Refinement web part, and the Search Results web part. For more information, see: - SharePoint Design Manager design packages - Configure Search Web Parts in SharePoint Server - Configure properties of the Refinement Web Part in SharePoint Server - Display template reference in SharePoint Server Properties that can be used in display templates Before you start to identify properties that you can use in a display template, locate an existing display template you want to build from and then save it with a new name. Display template code is located within the <mso:ManagedPropertyMapping> tag. <mso:ManagedPropertyMapping msdt:'Picture URL'{Picture URL}:'PublishingImage;PictureURL;PictureThumbnailURL','Link URL'{Link URL}:'Path','Line 1'{Line 1}:'Title','Line 2'{Line 2}:'Description','Line 3'{Line3}:'','SecondaryFileExtension','ContentTypeId'</mso:ManagedPropertyMapping> Next, open Site Settings > Search Schema, and then search for a column name in the Managed property filter box that you want to include in a display template. Select the managed property, and then edit and copy the property name. <mso:ManagedPropertyMapping msdt:'Picture URL'{Picture URL}:'PublishingImage;PictureURL;PictureThumbnailURL','Link URL'{Link URL}:'Path','Line 1'{Line 1}:'Title','Line 2'{Line 2}:'Description','Line 3'{Line3}:'','owsTXTPrice','owsTXTColor'</mso:ManagedPropertyMapping> Note In this example, PictureURL is mapped to the first managed property that is present when search is getting results for PublishingImage, PictureURL, or PictureThumbnailURL. Image renditions An image rendition defines the dimensions that are used to display images on pages in SharePoint publishing sites. You can use CSOM to instantiate and manipulate image renditions. You can specify metadata such as the height, width, name, and version of an image rendition by using the ImageRendition class. You can use methods and properties in the SiteImageRenditions class to read and write image renditions from a site collection. For more information, see SharePoint Design Manager image renditions. SharePoint and web programming techniques SharePoint designers and developers often want to use standard web programming techniques with SharePoint when they design publishing sites. You can use responsive design, adaptive design, or both device channels and responsive design together. Responsive design With device channels, you can build a site once and then target it to multiple devices and browsers. The web development community typically uses responsive design and the "fluid grid" approach to manage how layouts render and to design sites to render correctly on any browser or device. In a responsive design, elements on a page rearrange themselves to fit the user's device and screen orientation. Responsive design is based on the media queries feature in CSS3. It uses media queries to match the width of the device's display and then applies styles on the client side to render the content. Media queries make it possible for a designer to target specific site properties, such as screen width. You can use media queries to create flexible layouts and images, and conditionally call CSS file alternatives. For more information and examples, see: - SharePoint 2013/2016/Online Responsive UI (GitHub) - Responsive SharePoint - Implementing your responsive designs on SharePoint 2013. Adaptive design Adaptive web design (sometimes called adaptive web delivery) is similar to responsive web design. An adaptive design listens for devices or browsers and chooses the optimal way to render pages. The device channels feature in SharePoint is an adaptive design. It delivers adaptive layouts to each device based on page layout, the specifications of each device channel, and the order defined in the device channel panel. Device channels and responsive design together You can use device channels and responsive web design techniques together to build a responsive public-facing SharePoint publishing site. Consider creating a single custom master page for devices, such as phones and tablets, and another for web browsers, and associate each one with a device channel. Then, use fluid grids, flexible images, and CSS3 media queries to craft the best viewing experience for each device and browser that your site needs to support. Add jQuery to a SharePoint site You can add jQuery to a SharePoint site at the site level, the page level, or within sections of a page, such as one of the SharePoint page regions or a web part that you've added to the page layout. You can use a custom action to load jQuery from a document library. Do this if you need to make jQuery available to all pages in a SharePoint site. This approach is flexible but is not easy to control, and this affects the site designer and the administrator. You can store and maintain JavaScript files in the document library, but they can also be accidentally modified or deleted. For this reason, we don't recommend this approach. You can also load jQuery from the SharePoint root by using ScriptLinkControl. You can use the control to insert scripts that are running on a remote site, and modify the scripts without touching the SharePoint installation. The ScriptLinkControl approach makes sense when you want to use jQuery on an application page or in a web part that is displayed on a page. While provisioning with this option is slow and affects performance because jQuery is added to one page at a time, deploying the jQuery file to the SharePoint rule circumvents other legacy requirements. This is helpful if you need to migrate your SharePoint full trust code (FTC) solution to CSOM, and the migration includes moving and refactoring custom JavaScript and jQuery behaviors. Finally, you can use the Content Editor web part to load jQuery from a content delivery network (CDN). This is useful if you need to add jQuery to one or a few pages, including wiki and web part pages. Because you're loading the jQuery file from a CDN, you don't need to store extra files on the SharePoint server, and users get the benefit of a distributed, cached version of the jQuery files. SharePoint calls the jQuery file from the CDN, and you can add custom jQuery code that you author to the Content Editor web part. Build SharePoint provider-hosted add-ins with ASP.NET MVC 5 You can build custom provider-hosted add-ins with the model-view-controller (MVC) pattern in SharePoint. This model separates the application into three interconnected parts. This separates the internal representations of information from the way they are viewed and accepted by the user. The model represents the underlying structure of the software, the view (usually UI elements), and the controller, which are the classes that connect the model and the view. You can wrap ASP.NET MVC content in SharePoint site master page content. In fact, you can use Office 365 APIs to create a SharePoint Add-in with ASP.NET MVC 5. APIs for MVC for SharePoint development are defined in Filters\SharePointContextFilterAttribute.cs and SharePointContext.cs. These APIs wrap the steps that the web project takes to seamlessly communicate to SharePoint in a single call, which simplifies the logic you need to implement. The SharePoint context filter attribute performs additional processing to get standard information when redirected from SharePoint to your remote web application, such as Host Web URL. It also determines whether the add-in needs to be redirected to SharePoint for the user to sign in (for example, bookmarks). You can apply this filter either to the controller or to a view. SharePoint context classes encapsulate all the information from SharePoint so that you can create specific contexts for the add-in web and host web and communicate with SharePoint. For more information, see Learn About ASP.NET MVC and Introducing MVC support for SharePoint Add-ins. See also Feedback Send feedback about:
https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/sharepoint-metadata-site-navigation-and-publishing-site-features
CC-MAIN-2019-26
refinedweb
5,336
52.8
- MongoDB Stitch Tutorials > - Building a Web-based To-Do App > - Integrate the ToDo App with Twilio Integrate the ToDo App with Twilio¶ The following tutorial builds upon the procedure in Building a Web-based To-Do App and integrates the ToDo app with Twilio. With this integration, you can send messages to your Twilio number to add items to the ToDo list. Prerequisites¶ For this app, you need the following: - The ToDoapp set up according to Building a Web-based To-Do App. - A Twilio Account. If you do not have a Twilio account, create one before starting this procedure. You must also create a Twilio project for use with this procedure. Procedure¶ A. Go to your ToDo app in MongoDB Stitch¶ Estimated Time to Complete: ~2 minutes Log in to your Atlas account account and click Stitch Apps in the left-hand navigation. Click on the name of the MongoDB Stitch application you created for the Building a Web-based To-Do App tutorial. B. Configure the Stitch MongoDB Service for Twilio Integration¶ Estimated Time to Complete: ~10 minutes You must specify a namespace for each collection the Stitch MongoDB service accesses. A namespace is a combination of the database name and the collection name. In Stitch, each namespace contains rules and filters that control access to documents during read and write operations. Stitch creates basic rules and filters for the namespace when you create it. See MongoDB Rules for more information. Add the todo.users collection to MongoDB.¶ - Click on mongodb-atlasunder Atlas Clusters in the left navigation pane. - Click on the Rules tab. - In the Rules tab, click New to add a new namespace. Enter the following information: - For Database, enter todo. - For Collection, enter users. - Click Create. Each document in the todo.users collection has the following form: Modify Read Rules for todo.users.¶ To view the read rule, click on the Top-Level Document in the Field Rules view. Modify the read rule at the top-level document to the following and click Save: The new rule specifies that the fields in a document are readable if the _id field in the document equals the id of the user logged in to the ToDo app. For more information on MongoDB read rules, see MongoDB Rules. Modify Write Rules for todo.users.¶ Modify the write rule at the top-level document to the following: The new rule specifies that the fields in a document are writable if before the write operation, either: - The document to be modified by the write operation contains an _idfield that equals the id of the user logged in to the ToDo app ( %%user.id) - The document to be modified by the write operation did not exist; i.e. the write operation results in an insert operation. For more information on MongoDB read rules, see MongoDB Rules. Review All Other Fields Enabled option for todo.users.¶ By default, Allow All Other Fields flag is enabled so that any unlisted fields are readable/writeable as long as the document meets the read/write rules. Alternatively, you can explicitly define all the fields for this collection and disable Allow All Other Fields to control the shape of the documents. Review Filters for todo.users.¶ Click on the Filters tab. Click Delete to delete the default filter, then click Save. For more information on filters, see MongoDB Filters. C. Configure the Stitch Twilio Service¶ Estimated Time to Complete: ~10 minutes Note This section assumes you have a Twilio account and that you have created a project to use with this procedure. Create an incoming webhook to the tw1 service.¶ A MongoDB Stitch Incoming Webhook is a callback URL used by third- party service providers to execute a Stitch function. The function creates a document and inserts into the todo.items collection. To create an incoming webhook for the tw1 service, do the following: Click the Incoming Webhooks tab. Click New Webhook. Configure following properties for the webhook: Configure the function for the twilioWebhook webhook.¶ Hover over the webhook function and click Edit. Modify the function as follows: Copy the following code into the text entry box: The function above queries todo.usersto find the user associated with the originating phone number of the text message. The callback inserts into todo.itemsa document with the user’s owner_idand the text in the message. args.Fromand args.Bodycorrespond to the parameters of the Twilio message. Click Done. Configure the function to send verification codes.¶ In the left navigation pane click Functions and then New Function. Enter the following properties for the function: In the Function Editor set the function code to the following. Copy the following code into the text entry box: The function above sends a text message to recipientcontaining a verification code. It is called from the todoweb client as follows: Click Done. D. Create a Twilio Programmable SMS Service¶ Estimated Time to Complete: ~5 minutes Configure Programmable SMS.¶ - Click Messaging Services. - Click Create new Messaging Service. Enter a Friendly Name to describe the messaging service. For Use Case, select Mixed. - Check the Process Inbound Messages checkbox. For Request URL, enter the Incoming Webhook URLyou created when configuring the MongoDB Stitch Twilio service. For more information on the Twilio Programmable SMS service, including features and pricing, visit twilio.com/. E. Add your Twilio Phone Number as a Stitch value¶ Estimated Time to Complete: ~2 minutes Values are named constants that you can access in Stitch rules and functions. From the MongoDB Stitch UI, do the following: Enter your Twilio number as the value.¶ Enter the Twilio number you selected while Creating a Twilio Programmable SMS Service as a E.164 formatted string. For example, if your Twilio number is (222) 333-4444, enter "+12223334444" (note the included quotation marks). F. Set Up and Run the ToDo Application¶ Estimated Time to Complete: ~5 minutes Associate a phone number with your login id.¶ - Open a browser to access the ToDo app. Sign in with Google or Facebook credentials, depending on which you have set up in the Building a Web-based To-Do App tutorial. - Click Settings. - In the numberbox, enter a phone number from which you will send texts to your Twilio number. - Press the Returnkey. - Upon successful messaging, a verify codebox appears. - Enter the verification code sent to the phone number you entered. - Press the Returnkey. Upon verification, messages sent from the phone number to your Twilio number associated with your messaging service will show up as items in your todo list.
https://docs.mongodb.com/stitch/tutorials/todo-twilio-web/
CC-MAIN-2018-39
refinedweb
1,087
57.57
Closed Bug 684529 Opened 9 years ago Closed 9 years ago Remove script object Categories (Core :: JavaScript Engine, defect) Tracking () mozilla10 People (Reporter: igor, Assigned: igor) References Details Attachments (1 file, 3 obsolete files) +++ This bug was initially created as a clone of Bug #678830 +++ The bug 678830 mostly stops exposing JSScript object wrappers through JS API. But those objects are still created as a mean to reach global objects corresponding to the script and do security checks. We should remove the object wrappers and instead make sure that we always record the global object in the script and use it for security checks. Instead of creating the script objects the patch records compile-time global for the script and uses that in all the users of JSScript::u.object. With one global per compartment that would not be unnecessary but for now this avoids the extra memory bloat. Assignee: general → igor Comment on attachment 561708 [details] [diff] [review] v1 The patch has passed the try server. The new version records in JSScript::u.globalObject (former u.object) the global objects for function scripts if any. That removed the need to store the global in a separated slot in DebuggerObject and eliminated the global object parmeter from a few Debugger functions that was present in v1. Attachment #561708 - Attachment is obsolete: true Attachment #562012 - Flags: review?(jorendorff) v2 was an incomplete patch, this should the real one build on top of the patch from the bug 687966. Attachment #562012 - Attachment is obsolete: true Attachment #562012 - Flags: review?(jorendorff) Attachment #562103 - Flags: review?(jorendorff) Here is a rebased patch Attachment #562103 - Attachment is obsolete: true Attachment #562103 - Flags: review?(jorendorff) Attachment #564983 - Flags: review?(jorendorff) Comment on attachment 564983 [details] [diff] [review] v3 r=me with some nits. In jscompartment.h: >-} > > /* Defined in jsapi.cpp */ >-extern JSClass js_dummy_class; >+extern Class js_dummy_class; >+ >+} /* namespace js */ If it's going to live in namespace js, it shouldn't have js_ at the beginning of the name. In jsscript.cpp, JSScript::NewScriptFromCG: >+ script->u.globalObject = fun->getParent() ? fun->getParent()->getGlobal() : NULL; I assume fun->getParent() is null here iff compilation is not compile-and-go? In jsscript.h, in struct JSScript: > union { > /* >- * A script object of class ScriptClass, to ensure the script is GC'd. >+ * A global object for the script. > * - All scripts returned by JSAPI functions (JS_CompileScript, >+ * JS_CompileFile, etc.) have these globals. "have a globalObject" or "have a non-null globalObject". >+ * - Function scripts have these global if the function comes from >+ * compile and go scrits. "A function script has a globalObject if the function comes from a compile-and-go script." > * - Temporary scripts created by obj_eval, JS_EvaluateScript, and >+ * similar functions never have these globals; for such scripts >+ * the global should be extracted from the JS frame that execute >+ * scripts. "never have the globalObject field set;" >+ /* >+ * Return creation time global or null. FIXME - avoid duplication with >+ * global() that extracts the global from the type information. >+ */ >+ js::GlobalObject *getGlobalObjectOrNull() const { How were you planning to fix this? In vm/Debugger.cpp, DebuggerScript_check: >- JS_ASSERT(GetScriptReferent(thisobj)); >- >+ > return thisobj; > } Stray space charater on that line. Attachment #564983 - Flags: review?(jorendorff) → review+ (In reply to Jason Orendorff [:jorendorff] from comment #6) > > In jsscript.cpp, JSScript::NewScriptFromCG: > >+ script->u.globalObject = fun->getParent() ? fun->getParent()->getGlobal() : NULL; > > I assume fun->getParent() is null here iff compilation is not compile-and-go? Yes, this is true. > >+ /* > >+ * Return creation time global or null. FIXME - avoid duplication with > >+ * global() that extracts the global from the type information. > >+ */ > >+ js::GlobalObject *getGlobalObjectOrNull() const { > > How were you planning to fix this? I will remove those comments. Compartment-per-global would address this in a better way. Status: NEW → RESOLVED Closed: 9 years ago Resolution: --- → FIXED Target Milestone: --- → mozilla10
https://bugzilla.mozilla.org/show_bug.cgi?id=684529
CC-MAIN-2020-45
refinedweb
621
58.28
KDEUI #include <khistorycombobox.h> Detailed Description A combobox for offering a history and completion. A combobox which implements a history like a unix shell. You can navigate through all the items by using the Up or Down arrows (configurable of course). Additionally, weighted completion is available. So you should load and save the completion list to preserve the weighting between sessions. KHistoryComboBox obeys the HISTCONTROL environment variable to determine whether duplicates in the history should be tolerated in addToHistory() or not. During construction of KHistoryComboBox, duplicates will be disabled when HISTCONTROL is set to "ignoredups" or "ignoreboth". Otherwise, duplicates are enabled by default. Definition at line 48 of file khistorycombobox.h. Constructor & Destructor Documentation Constructs a "read-write" combobox. A read-only history combobox doesn't make much sense, so it is only available as read-write. Completion will be used automatically for the items in the combo. The insertion-policy is set to NoInsert, you have to add the items yourself via the slot addToHistory. If you want every item added, use Use QComboBox::setMaxCount() to limit the history. parent the parent object of this widget. Definition at line 66 of file khistorycombobox.cpp. Same as the previous constructor, but additionally has the option to specify whether you want to let KHistoryComboBox handle completion or not. If set to true, KHistoryComboBox will sync the completion to the contents of the combobox. Definition at line 73 of file khistorycombobox.cpp. Destructs the combo, the completion-object and the pixmap-provider. Definition at line 107 of file khistorycombobox.cpp. Member Function Documentation Adds an item to the end of the history list and to the completion list. If maxCount() is reached, the first item of the list will be removed. If the last inserted item is the same as item, it will not be inserted again. If duplicatesEnabled() is false, any equal existing item will be removed before item is added. Note: By using this method and not the Q and KComboBox insertItem() methods, you make sure that the combobox stays in sync with the completion. It would be annoying if completion would give an item not in the combobox, and vice versa. Definition at line 183 of file khistorycombobox.cpp. Emitted when the history was cleared by the entry in the popup menu. Clears the history and the completion list. Definition at line 163 of file khistorycombobox.cpp. Returns the list of history items. Empty, when this is not a read-write combobox. - See also - setHistoryItems Inserts items into the combo, honoring pixmapProvider() Does not update the completionObject. Note: duplicatesEnabled() is not honored here. Called from setHistoryItems() and setPixmapProvider() Definition at line 395 of file khistorycombobox.cpp. Handling key-events, the shortcuts to rotate the items. Reimplemented from QComboBox. Definition at line 340 of file khistorycombobox.cpp. - Returns - the current pixmap provider. - See also - setPixmapProvider - KPixmapProvider Definition at line 438 of file khistorycombobox.cpp. Removes all items named item. - Returns trueif at least one item was removed. - See also - addToHistory Definition at line 235 of file khistorycombobox.cpp. Resets the current position of the up/down history. Call this when you manually call setCurrentItem() or clearEdit(). Definition at line 443 of file khistorycombobox.cpp. Inserts items into the combobox. items might get truncated if it is longer than maxCount() - See also - historyItems Definition at line 113 of file khistorycombobox.cpp. Inserts items into the combobox. items might get truncated if it is longer than maxCount() Set setCompletionList to true, if you don't have a list of completions. This tells KHistoryComboBox to use all the items for the completion object as well. You won't have the benefit of weighted completion though, so normally you should do something like Be sure to use different names for saving with KConfig if you have more than one KHistoryComboBox. Note: When setCompletionList is true, the items are inserted into the KCompletion object with mode KCompletion::Insertion and the mode is set to KCompletion::Weighted afterwards. Definition at line 118 of file khistorycombobox.cpp. Sets a pixmap provider, so that items in the combobox can have a pixmap. KPixmapProvider is just an abstract class with the one pure virtual method KPixmapProvider::pixmapFor(). This method is called whenever an item is added to the KHistoryComboBoxBox. Implement it to return your own custom pixmaps, or use the KUrlPixmapProvider from libkio, which uses KMimeType::pixmapForUrl to resolve icons. Set prov to 0L if you want to disable pixmaps. Default no pixmaps. - See also - pixmapProvider Definition at line 377 of file khistorycombobox.cpp. - Returns - if we can modify the completion object or not. Definition at line 158 of file khistorycombobox.cpp. Handling wheel-events, to rotate the items. Reimplemented from KComboBox. Definition at line 352 of file khistorycombobox.cpp. Property Documentation Definition at line 51 of file khistory.
https://api.kde.org/4.x-api/kdelibs-apidocs/kdeui/html/classKHistoryComboBox.html
CC-MAIN-2019-30
refinedweb
800
60.21
. EF Code First support for RIA Services is the first feature where we’re using NuGet as the first distribution mechanism. Only NuGet offers the ability to release features independently from one another (without flooding your Add/Remove Programs list anyway), and it was a great fit for getting EF Code First support in your hands as quickly as possible. The NuGet package is RIAServices.EntityFramework, and it depends on EntityFramework 4.1. This can be used with WCF RIA Services V1.0 RTM, SP1, or SP2. You can find SP1 and SP2 on our site. We will also roll this feature into the WCF RIA Services Toolkit the next time we put out a release of the entire toolkit. With this release, there is no Domain Service Wizard support for your DbContext classes. So when you do Add New Item and choose Domain Service Class, you won’t see your DbContext classes in the dialog. But with the NuGet package and Varun’s VS Code Snippets, I suspect you won’t miss it much. As Varun mentioned, we will be adding Domain Service Wizard support for your DbContext classes in WCF RIA Services V1.0 SP2. There’s also a small gotcha that you need to be aware of. In order to generate code into your Silverlight project, RIA Services has to inspect your DbContext at build time in order to get the entity types that are available. If you have been using DbContext, you’re likely aware that simply creating and accessing a DbContext can actually create your database in SQL Express. Chances are though, you don’t want this to happen at build time when RIA Services generates code. In order to prevent this, there’s a small bit of code you need to add to your DbContext to null out your database initializer. Varun illustrated this, and I’ll show it below too. When using this feature, you will inevitably get a build warning along the lines of:. This is unavoidable at the moment, and you might have actually seen similar build warnings when using other DataAnnotations attributes that aren’t available in Silverlight. This is where our code generation was trying to be smart, recognizing that your model has an attribute applied from the DataAnnotations namespace, but seeing that the attribute type isn’t available to your Silverlight project. At the time we created that build warning messages, it was safe to assume this meant that you didn’t have a reference to DataAnnotations in your Silverlight project. That is no longer true - EntityFramework 4.1 includes a DatabaseGeneratedAttribute type that is defined within the DataAnnotations namespace, but of course isn’t available in Silverlight. You can just ignore this build warning. Update: Lastly, the day after we released this NuGet package, the Entity Framework team released a June CTP for EF. That CTP is not yet supported for RIA Services. We wanted to first get support in place for the released EntityFramework 4.1 bits, and we’ll work to target EntityFramework 4.2 as soon as we can. Let’s run through a super-quick-start for getting going with RIA Services and EF Code First. This by no means is a guide to how to use EF Code First, but it illustrates how to use RIA Services with it in a basic example. Before you begin, you must have WCF RIA Services (V1.0 RTM, SP1, or SP2) installed on your machine, as well as NuGet. public class BlogContext : DbContext { public DbSet<Post> Posts { get; set; } public DbSet<Comment> Comments { get; set; } public BlogContext() { // Prevent database initialization at design-time // when RIA Services is generating code if (HttpContext.Current == null) { Database.SetInitializer<BlogContext>(null); } }} [EnableClientAccess]public class BlogService : DbDomainService<BlogContext>{ public IQueryable<Post> GetPosts() { return this.DbContext.Posts.OrderByDescending(p => p.PublishDate).Take(5); } public void InsertPost(Post post) { DbEntityEntry<Post> entityEntry = this.DbContext.Entry(post); if ((entityEntry.State != EntityState.Detached)) { entityEntry.State = EntityState.Added; } else { this.DbContext.Posts.Add(post); } } public void UpdatePost(Post post) { this.DbContext.Posts.AttachAsModified(post, this.ChangeSet.GetOriginal(post), this.DbContext); } public void DeletePost(Post post) { DbEntityEntry<Post> entityEntry = this.DbContext.Entry(post); if ((entityEntry.State != EntityState.Deleted)) { entityEntry.State = EntityState.Deleted; } else { this.DbContext.Posts.Attach(post); this.DbContext.Posts.Remove(post); } }} As far as RIA Services / EF Code First goes, you’re done. At this point, you can now go into the Silverlight application and do all of the things you expect to do with RIA Services. As with other DomainServices, your client has no awareness of what data access layer you’re using. Because of this, you can use the new DbDomainService with Silverlight 4, Silverlight 5, or with RIA/JS. Because we don’t have Domain Service Wizard support (until the next release of WCF RIA Service V1.0 SP2), you might want to grab Varun’s VS Code Snippets to make the above code simpler to crank out for each of your entity types. Thanks to the power or NuGet, quite a bit was actually done for you by adding the package reference to RIAServices.EntityFramework. Note that 2-4 in this list matches up with what the Domain Service Wizard would typically do for you. So even though we don’t have wizard support with the NuGet package, you still don’t have to mess with references or web.config to use RIA Services. Thursday, June 30, 2011 1:00 AM This is a wonderful piece of info. I have waited patiently for this bit.RIA Services EF and Code First ROCKS!Thanks and keep it coming. Does this work with the new release of EF JUNE 2011 CTP released today? Hello,I did a sample by following this tutorial and when I compiled I got the following error.Failed to get the MetadataWorkspace for the DbContext typeI am using VS 2010 and RIA SP2I can see other people are reporting same error.Any Guidance will be appreciated.Thanks. Just perfect!Thanks for releasing the package so we don't have to wait till the next release.Keep it up! I am getting the same error message as Uwascan."Failed to get the MetadataWorkspace for the DbContext"I was able to get the sample project to compile just fine, but creating my own solution with the Silverlight app and RIA Service in separate projects results in this error. My models and DomainService is in the RIA Service project.I'd be happy to provide more info if needed.Thanks! Hello, for the Metadataworkspace error it's a problem with your connectionstring. Thanks for the tip, bhugot. I will be honest that we weren't prepared for the MetadataWorkspace errors people have been getting.But yes, this is the error you will get if EntityFramework is unable to connect to your database when being invoked through the Domain Service. Re: Does this work with the new release of EF JUNE 2011 CTP released today?No - not yet. We wanted to first get support out there for the released EntityFramework 4.1, since it's a supported product.The EF June CTP is preview bits, and we'll try to get support in place for this new version as soon as we can. is it considered release quality or beta quality ? should I use it as a CTP or in my production code ? can I use DataAnnotations attributs on my Code First classes and get them picked up by RIA Services without using the Metadata classes ?? Question for you:If I am already using a Repository pattern behind my Domain Service (So my Domain Services never directly query my DbContext -- they calls methods on my repositories), are there any additional benefits to using a DbDomain Service? @guestYou should feel free to use this NuGet package in Production. These are release-quality bits, but we've left them under the Toolkit license rather than putting them in the product. This allowed us to release much sooner, and we'll be able to make changes to support EF 4.2. We'll do our best to not change any API or anything though. @GuestYes, you can definitely use DataAnnotations attributes directly on your Code First classes and eschew the Metadata classes completely. That is one of the biggest benefits of EF 4.1 I think. @JeremyI cannot think of any benefits of using DbDomainService in front of a repository pattern.The repository pattern usage scenario is something we're looking to improve for V2 though, so if you have any thoughts or feedback, feel free to drop me a line through the contact form.. @MarkThanks a ton for that awesome tip! What if you are using IDomainServiceFactory to implement a DomainServiceFactory for use with Unity? Basically, this is the blog post I have implemented: weblogs.asp.net/...It looks as though DbDomainService is derived from DomainService... Hello how can I include related entities without using Includes.With LinqToEntitiesDomainService we could do some Attach but how can I do it with code first? Hello, Any guidance/code on how to incorporate this with AuthenticationBase ? Thank you, Michael Any chances for these things work together (DbDomainService + DomainCollectionView)? I'm trying to do, but not getting success..For reference, the DomainCollecionView i'm mentioning is that: blogs.msdn.com/... Dados = new DomainCollectionView<orc_orcamento>(() => { return _ds.Load(_ds.GetOrcamentosQuery().SortAndPageBy(Dados)); }, _ds.orc_orcamentos); using (Dados.DeferRefresh()) { Dados.SetTotalItemCount(-1); Dados.MoveToFirstPage(); }What I'm doing wrong? This should work with DbDomainService?BTW, thanks for the great info in this topic. Jeff,On 7/8 you wrote "... Yes, you can definitely use DataAnnotations attributes directly on your Code First classes and eschew the Metadata classes completely..."That doesn't seem to work. I can easily load related entities server-side with either EF's .Include function or Assocation attribute. But they never appear client-side unless I specify the Include attribute in metadata. I tried both a DbDomainService and a DomainService with repository pattern.Am I missing something? The [Include] attribute is still needed if you want RIA Services to serialize the related data to the client. But you should be able to put the [Include] attribute directly on the model rather than in a buddy class..Include = Tell EF to fetch the data[Include] = Tell RIA to serialize the dataBecause RIA is DAL-agnostic, we need to have our own mechanism for marking related data as included in serialization. Otherwise, if we inspected all related data properties to see if data was there, and you had lazy-loading in place, we'd send your whole database to the client.Hope this helps,Jeff Yes Jeff, that helped. Tnx.I knew about the difference between .Include in EF and [Include] in RIA, but not that I could put it directly on the model.So does that mean I should define my Model in my RIA Services Web assembly?With ASP.Net I used to create separate assemblies for model and data access code. But adding a reference to System.ServiceModel.DomainServices.Server (which defines the [Include] attribute) in a separate assembly throws a DomainOperationException. Besides, it seems to defy the whole purpose of separating my model out in a separate assembly.Tnx again for your suggestions. Nice post - we had just ruled out Code First due to its lack of playing nicely with RIA services... this has just created me some new work!I notice that the 'AttachAsModified' extension method is only provided for the concrete DbSet class - and not for the IDbSet interface. This is a bit of a pain for testing - since I want to be able to swap in test IDbSet implementations.Is this something that is being looked at - or perhaps there is a simple workaround (other than casting)? Hi Jeff,Thank you for making RIA Services support for EF DbContext / Code First available. It's absolutely awesome!I submitted a sample on code.msdn where I attempted to introduce Unit-of-Work and Repository patterns where IDbSet<T> serves as my generic repository interface and I created a UnitOfWorkDomainService as follows:public abstract class UnitOfWorkDomainService<TContext> : DomainService where TContext : IUnitOfWorkwith public interface IUnitOfWork : IDisposable { int SaveChanges(); }I can then create a concrete domain service as follows: [EnableClientAccess()] [DbDomainServiceDescriptionProvider(typeof(BookClubContext))] public class BookClubService : UnitOfWorkDomainService<IBookClubContext> I am still struggling with trying to decouple a dependency on IObjectContextAdapter in the handling of DbUpdateConcurrencyExceptions. You can find the sample here code.msdn.microsoft.com@davebI found the issue with the AttachAsModified extension method being provided on DbSet<T>, not IDbSet<T>, but I ended up implementing this on my DbContext derived class directly as you can see in my sample on code.msdn. @Remco Blok - I have had some problems when using DomainService directly - and not using DbDomainService... when retrieving a set of objects that contain navigation properties, the navigation properties all get resolved, which means you can end up loading a huge object graph. Perhaps you've seen that and found a solution, but I have found that when using DbDomainService (or LinqToEntitiesDomainService) this problem disappears, though you have to specifically eager load the navigations using the .Include syntax (which suits me fine). @davebDbDomainService sets LazyLoadingEnabled to false on your DbContext, which is what you would have to do yourself if you derive directly from DomainService. I have done this in the UnitOfWorkDomainService in my sample on code.msdn @Remco BlokDoh, that makes me feel foolish... when we first picked up EF we set LazyLoadingEnabled to true - so that we didn't have to explicitly load navigation entities. I'd put 2 and 2 together and got 2 back.I do have another problem. If I try to add any custom logic to my OnModelCreating DbContext override (perhaps to map a column to the storage model), I get this error in my Silverlight project:Failed to get the MetadataWorkspace for the DbContext typeI know my connection string is correct, and if I use ColumnAttribute on those properties everything works...Any ideas? Hi JeffI thought not all dataAnnotations attributes where available in Silverlight. Like you say here: jeffhandley.com/.../DataAnnotationsSubset.aspx Except for the meta classes its a sad sad thing that it did not got ported. I just don't believe it is not portible one way or the other. I am fighting with the "Failed to get the MetadataWorkspace for the DbContext type" error at the moment.I have one connections string I use for internal testing (local SQLEXPRESS) but I need to update that to point to SQL Azure. Once I do the update the build fails, because outgoing 1433 is being blocked. I guess I am surprised that the connection is being actively used at build time.. and in my current situation it is making life difficult.Anyone else had a similar issue or able to offer any tips? Jeff, Please correct me if I am wrong What is the best way to use unity or mef(prism) using wcf ria and code first for domain services?Is it best to refactor silverlight business application? or silverlight navigation application? Is the best pattern unit of work??Thanks Anyone have any inkling of how to get the dbdomain service to be completely accepted by LightSwitch?I can get the LS app to detect the service in the project and the entities.. but the app fails to buildError Jeff,I'm getting the "Failed to get the MetadataWorkspace" error that others have received.What's wierd is this. I'm changing my service from:public class EntityManagerService :DomainServiceto:public class EntityManagerService : DbDomainService<HRContext>In the existing DomainService, I have a private property of HRContext that I new up and an override on Submit that calls SaveChanges. This all works fine until I convert to DbDomainService, that's when I get the build error.Many folks have indicated a problem with their connection string. I don't see this as the problem in my case because, as I said, the DomainService is able to new up the HRContext (which is a DbContext) and query the db, etc.Any suggestions? "Failed to get the MetadataWorkspace" error too ...An if I run my program with this error ... IT WORKS !So my connectionString is correct and my IDs too ...Help ..... Hi Jeff,i have a question for you.I've tested Code First and RIA on one to one, one to many and many to many association.First two work perfectly but on third association type i'm not sure..I've tried on three simple classes:- Worker- Company- HistoryWorkerCompany.HistoryWorkerCompany has four properties:- public virtual Worker Worker { get; set; }- public virtual Company Company { get; set; } - public DateTime EffectiveDate { get; set; }- public DateTime? ExpirationDate { get; set; }When i compile I get this error "Failed to get the MetadataWorkspace". The connection string is ok because ifi use public Int32 WorkerId { get; set; } and public Int32 Company { get ; set; }. It's not very well because iloose navigation properties. Why? Sorry for my bad english =) Regards. Gabriele public class User{ public int UserId { get; set; } public string Name { get; set; } public virtual ICollection<Item> BoughtItems { get; set; }} public class Item{ public int ItemId { get; set; } public string Name { get; set; } public double InitialPrice { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public int? BuyerId { get; set; } public int? SuccessfulBidId { get; set; } public virtual User Buyer { get; set; } public virtual Bid SuccessfulBid { get; set; } public virtual ICollection<Bid> Bids { get; set; } public virtual ICollection<Category> Categories { get; set; }} public class Bid{ public int BidId { get; set; } public double Amount { get; set; } public DateTime CreatedOn { get; set; } public int ItemId { get; set; } public int BidderId { get; set; } public virtual Item Item { get; set; } public virtual User Bidder { get; set; }} public class Category{ public int CategoryId { get; set; } public string Name { get; set; } public int? ParentCategoryId { get; set; } public virtual Category ParentCategory { get; set; } public virtual ICollection<Category> ChildCategories { get; set; } public virtual ICollection<Item> Items { get; set; }} Jeff I would greatly appreciate any updates on entity framework june ctp 2011 for table value functions, code first for silverlight, wcf ria. We do appreciate when you keep us informed! Thank you for your excellent post. I'm also getting the "Failed to get the MetadataWorkspace for the DbContext type '...'." error. When I have ONE DbSet<...> property on the DbContext everything builds correctly. When I add another DbSet<...> property I get the error. Somehow it appears to be having trouble reconciling multiple DbSet properties on the context.Anyone else notice this behavior and/or get past it? Just in case anyone is still getting the "Failed to get the MetadataWorkspace for the DbContext type" errors you can run an additional instance of VS and attach to the instance which is failing to build. If you turn on break on CLR exceptions you can catch the exception which is causing the failure. When using RIA Services SP2 + EF 4.1 Update 1 the Add Domain Service wizard doesnt work (it complaints something about zero argument index).When trying to add DbDomainService manually (or using NuGet provided scaffolding scripts) I get Failed to get the MetadataWorkspace for the DbContext type XXX error. DbContext is very simple (1 entity).Using CodeFirst with model classes and DbContext residing in a separate (from .Web project) assembly. If you guys are still having issues with the "Failed to get the MetadataWorkspace" error, usually it's because you have an Entity with a Composite primary key (an Entity with multiple properties decorated with a Key DataAnnotation attribute).The error you'll usually get when running Unit Tests is: "System.InvalidOperationException: Unable to determine composite primary key ordering for type 'Your Type'. Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys."Basically EF does not know the Order of which Key should come first (not sure why this EVEN MATTERS because it's a Primary Key, who CARES about the friggin order!). Anyway, decorate your Properties with a [Column(Order = x)] attribute and the errors go away. Ok, finally got past all these "Failed to get the MetadataWorkspace..." errors. But now I am running into another issue. It doesn't stop me from building but it's quite annoying to have these "Warnings" show up for no reason. Basically, I have decorated my classes with the Table[TableName, SchemaName] attribute. However, the RIA Services Client generates TONS of warning messages (one for each Table and Column attribute) and just says that it will not generate them because I don't have a reference to "System.ComponentModel.DataAnnotations" (which of course, I do). Basically, I can see that it wants the "Server" reference of DataAnnontations and doesn't recognize that it is in fact generating code for a SL client.Here's the full warning message:"The attribute 'System.ComponentModel.DataAnnotations.TableAttribute' requires a reference to System.ComponentModel.DataAnnotations in the client project 'Client.Services'. Skipping generation of attribute. Please add a reference to System.ComponentModel.DataAnnotations to ensure generation of the attribute."and also:The attribute 'System.ComponentModel.DataAnnotations.DatabaseGeneratedAttribute' requires a reference to System.ComponentModel.DataAnnotations in the client project 'Client.Services'. Skipping generation of attribute. Please add a reference to System.ComponentModel.DataAnnotations to ensure generation of the attribute.Is there ANY way to get rid of these annoying messages that obviously mean nothing since I know it shouldn't even generate these attributes on the Client side? Good work on all of this, Tim!!Sorry there isn't a way to get rid of those warnings. We special-cased the System.ComponentModel.DataAnnotations namespace back in v1.0 as we didn't expect other teams in Microsoft to be creating types in that namespace outside of the actual DataAnnotations assembly. We've been proved wrong there, and the result is the warning. To everybody who get a "Failed to get the MetadataWorkspace for the DbContext" Exception:Try to access the "svc" address, some exception message is there, fix it and rebuild your solution, that exception may be resolved.My English is not good, sorry. This Failed to get the MetadataWorkspace for the DbContext" Exception:SUCK BIG TIME...I get it when i use one or my own drop database initializer... if not then all is good... YOU SHOULD REALLY FIX YOUR SH... If you're getting this error when you try to run or compile the Silverlight project, check out what I do to fix this error:joshmouch.wordpress.com/... Searching for metadataworkspace error I reached to this blog, then I am not getting an answer for my solution.Is this all you can do about a common problem? Do you feel responsibility about your products? If you encourage us to use something you better to provide a strong support for it.Actually I expected RIAServices to raise a more elaborated exception instead of "FAILED". If the connection string has a problem how can I figure out what is the problem? I added the reference over NuGet and now I'm also get the error "Index (zero based) must be greater than or equal to zero and less than the size of the argument list." when I try to add a new DomainService through the wizard. When I remove the references in the project (and clean), the error's gone, but of course, my code first context won't show up.Happy to provide further info... I'm a little disappointed to be honest, usually your stuff works like a charm :( I referenced the wrong version of EF (4.2). My fault :) Great article, but I've tried everything to solve the metadataworkspace error and I cannot find the problem. I can connect to the database using server explorer and I'm using the same connection details in my web.config. I've even specified the connection name in the datacontext constructor.My entity and datacontext is in a class library which is referenced by a WCF RIA Services Class library. THe connection string is in the web.config of the main SIlverlight web project.Is it possible for me to send you a zip of my files? I finally solved the problem through some trial and error. As I'm using a WCF RIA Class library to house my domain service, I needed to add a web.config file to the web project of the class libary with the same connection string in it as in the main silverlight web project. when will be out ef 4.2 support? entityframework.migrations beta 1 requires 4.2, and i would like to move all to ef 4.2 and migrations beta 1 Same question here, will the updated assembly with EF 4.2 support be released soon?Thanks Are we going to see 4.3 support any time soon? Could you please give us some guidance on whether you are offering support for newer versions of EF and what the roadmap is please? This is a very serious question and nobody is getting any answer??????? Now that RIA services team is no more, isn't there a workaround to get rid of those warnings? Hi Jeff,In the DeletePost method above, it seems to me that the state of the entry should be set to Deleted if it is anything other than Detached - not if it is anything other than Deleted.I have seen the logic that you use a number of times on the internet but still can't help but think that it is not correct.Could you please explain the logic or confirm that it should be Detached?Many thanks,Scott Munro I touched base with Rowan Miller from the EF team on this, @Scott. Here's his input..."In reality, the code will actually work because setting something to deleted when it's already detached is a no-op. The else part of the clause will also work for attached and detached entities because Attach will move the entity to the Unchanged state and then Remove will mark it as Deleted."I think you could actually reduce the code to the following and it would still work: public void DeletePost(Post post) { this.DbContext.Posts.Attach(post); this.DbContext.Posts.Remove(post); }"Though you would want to test it in case I am missing something. :-)" Thanks Jeff!I think that I will probably go with something like the following to save on the overhead of changing the state of the entry to Unchanged if it is already attached. public void DeletePost(Post post) { DbEntityEntry<Post> entityEntry = this.DbContext.Entry(post); if ((entityEntry.State != EntityState.Detached)) { entityEntry.State = EntityState.Deleted; } else { this.DbContext.Posts.Attach(post); this.DbContext.Posts.Remove(post); } } ...having said that, the method that Rowan suggested would not involve having to retrieve the DbEntityEntry. I think I might go with his suggestion. fixed "Failed to get the MetadataWorkspace for the DbContext type" Error1 localhost\SQLExpress service must enabled.2 RIA class library's Web project must has a Web.config file (not include to web project) include two sections <connectionStrings> and <runtime>3 DbContext constructor: public XxxDbContext() : base("Server=192.168.1
http://jeffhandley.com/archive/2011/06/30/RIAServicesCodeFirst.aspx
CC-MAIN-2017-13
refinedweb
4,528
56.96
Today's Page Hits: 145 Continuation is an object that represents the execution state of a program at a certain point. We can use continuation to restart the execution from the point stored in it. How about continuations for the Java platform? There are atleast two different implementations of continuations: I've experimented with javaflow. I checked out javaflow sources under, say %JAVAFLOW_HOME% directory (no pre-built binaries available in the site). I tried building it by maven. But failed ... because I need parent pom file! (never mind if you don't understand that -- that is just a build step). Because I am only interested in playing with continuation, I ignored maven build. I just created a NetBeans project and added all source directories of javaflow. I copied dependent libraries (ant.jar, commons-logging-1.0.4.jar, junit-3.8.2.bar, junit-addons-1.4.jar -- I just copied the versions that I had -- check for proper dependency or use maven to build!) under %JAVAFLOW_HOME%\lib directory and added all jars under this directory to netbeans project. I managed to build and produce javaflow.jar under %JAVAFLOW_HOME%\dist. The following is a simple program that uses continuations [this is just slightly modified version of the one in the javaflow tutorial] The output of the above program is shown below:The output of the above program is shown below: import org.apache.commons.javaflow.*; class Test { static class MyRunnable implements Runnable { public void run() { System.out.println("run started!"); for( int i=0; i < 10; i++ ) { echo(i); } } private void echo(int x) { System.out.println("echo " + x); Continuation.suspend(); } } public static void main(String[] args) { System.out.println("main started"); Continuation c = Continuation.startWith(new MyRunnable()); System.out.println("in main after continuation return"); while (c != null) { c = Continuation.continueWith(c); System.out.println("in main"); } } } main started run started! echo 0 in main after continuation return echo 1 in main echo 2 in main echo 3 in main echo 4 in main echo 5 in main echo 6 in main echo 7 in main echo 8 in main echo 9 in main in main The execution seems to "flip-flop" between Test.main and Test.MyRunnable.echo methods!. No, there are no multiple threads here. Single thread of execution produces the output shown above. That is because of continuation. If you don't get that, you may want to read this. The steps used in build, run the above program: javac -cp %JAVAFLOW_HOME%\dist\javaflow.jar Test.javaThe above step created two .class files - Test.class, Test$MyRunnable.class. Continuation implementation works by bytecode instrumenting of the .class files of your application. Either you can instrument the program ahead of execution (during build) or do it at runtime using a special class loader. This being a simple hack exercise for learning, I instrumented these .class files using the following commands: java -cp .;%JAVAFLOW_HOME%\dist\javaflow.jar;%JAVAFLOW_HOME%\lib\* RewriteTool <Test.class >mTest.class java -cp .;%JAVAFLOW_HOME%\dist\javaflow.jar;%JAVAFLOW_HOME%\lib\* RewriteTool <Test$MyRunnable.class >mTest$MyRunnable.class move mTest.class Test.class move mTest$MyRunnable.class Test$MyRunnable.class Actually, there is a better way to pre-instrument .class files for continuation support: there is a javaflow ant task. (the ones that use continuations need to be instrumented. You can leave the other jar files) java -cp .;%JAVAFLOW_HOME%\dist\javaflow.jar;%JAVAFLOW_HOME%\lib\* Test As you may know already, JDK 6 includes javax.script API and Mozilla Rhino based JavaScript engine. There is continuation support in Rhino. But then, that is a topic for another blog entry Posted by Nico on January 20, 2007 at 12:32 AM IST # Posted by Doug Daniels on January 20, 2007 at 03:34 AM IST # Hi Nico: Yes, doing bytecode instrumentation at classload is interesting. javaflow has ContinuationClassLoader class for this. Hi Doug Daniels: It is great that scripting gets attention in the Java platform. Thanks for the references on scripting with games! I'll check out these resources. Posted by A. Sundararajan on January 20, 2007 at 11:05 AM IST # Posted by Doug Daniels on January 21, 2007 at 12:40 AM IST # Posted by Ranjan Bhandari on January 23, 2007 at 04:21 AM IST # Posted by Ranjan Bhandari on January 23, 2007 at 04:22 AM IST # Posted by Jochen "blackdrag" Theodorou on January 25, 2007 at 05:18 AM IST # Hi Ranjan Bhandari: If continuations are implemented as API (like it is done with javaflow or RIFE) there is no change in Java programming language anyway - and therefore no bloating language. Also, if Java VM would support continuations at VM level (as VM primitive so that bytecode instrumentation is not needed), that would help implementing languages that need continuation primitive (like Scheme). Alternate languages on top of JVM is interesting by itself. Hi Jochen "blackdrag" Theodorou": Yes you are right. We need to instrument all the classes whose methods will appear on the stack. Both javaflow and RIFE-continuations implement continuations by bytecode instrumentation. Yes, I agree - the solution is to support continuations at JVM level. But then you may want to read as well. Posted by A. Sundararajan on January 25, 2007 at 09:58 AM IST # Posted by Jochen "blackdrag" Theodorou on January 25, 2007 at 05:38 PM IST # Posted by A. Sundararajan on January 25, 2007 at 07:46 PM IST #
http://blogs.sun.com/sundararajan/entry/continuations_for_java
crawl-002
refinedweb
901
59.5
Standard C Assertions. More... #include <kos/cdefs.h> Go to the source code of this file. Standard C Assertions. This file contains the standard C assertions to raise an assertion or to change the assertion handler. Standard C assertion macro. This macro does a standard C assertion, wherein the expression is evaluated, and if false, the program is ultimately aborted using abort(). If the expression evaluates to true, the macro does nothing (other than any side effects of evaluating the expression). Assertion handler type. The user can provide their own assertion handler with this type. If none is provided, a default is used which ultimately prints out the location of the failed assertion and calls abort(). Set an assertion handler to call on a failed assertion. The default assertion handler simply will print a message and call abort().
http://cadcdev.sourceforge.net/docs/kos-2.0.0/assert_8h.html
CC-MAIN-2018-05
refinedweb
138
60.01
1. There is no ODF requirement that namespace binding be with a prefix. The binding can be with a default namespace (no prefix). 1.1 There is no problem with any of the ODF RNG Schemas with how [xml-names] is supported. 1.2 Although prefixes are always used in the ODF Specification, neither the particular name for the prefix or the use of a prefix are required. (However, a prefix is required if attributes are defined in a namespace. There is no default namespace for attributes.) The namespace binding can be by any means that [xml-names] provides for. For example, the NameSpaceResilience-01- and -02- ODF Text documents at
http://mail-archives.apache.org/mod_mbox/incubator-odf-dev/201108.mbox/raw/%3C008201cc5cf2$f5d85be0$e18913a0$@acm.org%3E/
CC-MAIN-2017-22
refinedweb
111
66.44
hello everyone, i am a beginner in java programming and i usually look in the internet for the solutions of my homeworks in java for my subject and i encountered this code and i really don't understand how it works so please, can anybody can explain it to me please.... i really need your help now!!! Thanks in advance!!! Code : public class Anagram { public void anag(String s1, String s2) { if(s1.length() == 0) { System.out.println(s2); } for(int i = 0; i < s1.length(); i++) { anag(s1.substring(0, i) + s1.substring(i+1, s1.length()), s1.charAt(i) + s2); } } public static void main(String[] args) { Anagram ana = new Anagram(); ana.anag("farm", ""); } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/30729-anagram-program-printingthethread.html
CC-MAIN-2014-10
refinedweb
115
69.38
Subject: Re: [boost] Formal review request: static size matrix/vector linear algebra library (Boost) LA From: Emil Dotchevski (emildotchevski_at_[hidden]) Date: 2010-02-11 02:01:43 On Wed, Feb 10, 2010 at 9:52 PM, <Joel.Falcou_at_[hidden]> wrote: >> Operator [ ] is the best choice, but it can not be overloaded >> generically because it is required to be a member, for reasons that >> are beyond my understanding of C++. > > I don't see why you can't overlaod generically ? Because operator [ ] is required to be a member function. By overloading generically, I mean the way other operators are overloaded in (Boost) LA: they're namespace-scope functions that kick-in for any conforming user-defined vector or matrix type. Emil Dotchevski Reverge Studios, Inc. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2010/02/161771.php
CC-MAIN-2019-22
refinedweb
146
58.79
...making Linux just a little more fun! In Linux Gazette issue #114, we took the first steps towards understanding and interpretation of scientific data by using Python for the visualization. The next step is to reach a quantitative understanding by performing some sensible data analysis, such as fitting a model to the data and thereby extracting useful parameters. This defines the main topic of this part II of Python for scientific use. As with part I, this article will also be centered around a few illustrative examples. I assume that the reader is familiar with either part I of this article or basic Python. As a pleasant surprise, I actually got some nice reader feedback related to Part I of this article. Some readers proposed additional tips & tricks; I have included them here, to the service of other readers who might find it useful (at least I did :-). If you want to try out all the examples on a Wind0ws machine (for some wicked reason), John Bollinger suggested to use os.popen the following way: f=os.popen('pgnuplot.exe','w') Even more intelligently, the following code ensures that the Python script can be run on both Linux and Wind0ws: import os import sys if os.name == 'posix': f=os.popen('gnuplot', 'w') print 'posix' elif os.name == 'nt': f=os.popen('pgnuplot.exe', 'w') print 'windows' else: print 'unknown os' sys.exit(1) JB also pointed my attention to Michael Haggerty's neat project, gnuplot.py, at sourceforge. Cyril Buttay brought to my attention that the default encoding in gnuplot is insufficient if you want to print special characters, e.g. Danish ones like æ, ø, and å on the plots. In order to do so, you need to specify another encoding as described in the gnuplot manual: set encoding {<value>} show encoding where the If the encoding is not changed from the default, the special character might show up on the screen but not in the hardcopy (actually, I think the special characters only work with terminal postscript, but I'm not sure). If the desired special character is not available on your keyboard, it can be accessed though its octal value; e.g., to print a special character such as the Danish å in the title of a plot, set the encoding to iso_8859_1: set title "This is a Danish character \345" which will display This is a Danish character å in the title of the plot. To also use Greek characters, e.g. α (lowercase alpha), one should use {/Symbol a} (this requires terminal postscript enhanced). Similar, Γ (uppercase gamma), is generated with {/Symbol G}. To find special characters and their corresponding octal values for, e.g., iso8859-1 encoding in Linux, just type: man iso_8859-1 or have a look at this postscript file. [ If you're not sure of the exact name of the relevant manpage, just type man -k string, where 'string' is the name, or part of the name of the encoding you're looking for. This will get you a list of all the manpages the names of which contain that string. -- Ben ] The first example illustrates how to fit a model to 2-D data. The :-). Now, let us go through the code of the example. leastsq) is defined; second, the fitting function is defined. scipy.io.array_import.read_array. For convenience x (time) and y (weight loss) values are stores in separate variables.). In the next example we will use the Fast Fourier Transform (FFT) in order to transform time-dependent data into the frequency domain. By doing so, it is possible to analyse if any predominant frequencies exists - i.e. if there is any periodicity in the data. We will not go into too much detail of the underlying mathematics of the FFT method; if you're interested, have a look at some of the many informative pages on the internet, e.g.,, Numerical recipes, etc. Let's take a simple example to get started. Consider temperature measurement at a given location as a function of time. By intuition, we expect such data to have a dominant frequency component of 1/24h = 0.042 h-1 simply reflecting the fact that it is usually warmer during the day (with a maximum around noon) and cooler during the night (with a minimum sometime during the night). Thus, assuming a period with stable weather for, say, one week, we may approximate the the temperature variations as a function of time with a sine wave with a period of 24 h. If we take the Fourier Transform of this sine wave we find that only one single frequency is present (shown as a δ-function) and that it is 0.042 h-1. OK, enough with the simple case, if everything was this simple we wouldn't need the Fourier Transform. Instead we will move to a more complex case where intuition is not enough. The example data we will use is the sunspot activity measurements from year 1700 to year 2004 provided by National Geophysical Data Center - NOAA Sattelite and Information Service. The data set is the yearly sunspot observations available via FTP. The datafile is also included as sunspots.dat. The sunspot data have been used for illustrating the power of FFT with respect to finding a periodicity in sunspot activity in various computer languages, e.g. Matlab and BASIC. The observations that there is (or might be) a correlation between sunspot activity and the global temperature have led to controversy when discussing the greenhouse effect and global warming. The graph below illustrates the sunspot data to be used in this example. The code below shows the python script for analysing the sunspot data. The shown script is a shortened version with some plots removed. The full script is in sunspots.py.txt. 1 from scipy import * 2 import scipy.io.array_import 3 from scipy import gplt 4 from scipy import fftpack 5 6 sunspot = scipy.io.array_import.read_array('sunspots.dat') 7 8 year=sunspot[:,0] 9 wolfer=sunspot[:,1] 10 Y=fft(wolfer) 11 n=len(Y) 12 power = abs(Y[1:(n/2)])**2 13 nyquist=1./2 14 freq=array(range(n/2))/(n/2.0)*nyquist 15 period=1./freq 16 gplt.plot(period[1:len(period)], power,'title "Meas" with linespoints') 17 gplt.xaxis((0,40)) 18 gplt.xtitle('Period [year]') 19 gplt.ytitle('|FFT|**2') 20 gplt.grid("off") 21 gplt.output('sunspot_period.png','png medium transparent picsize 600 400') In the first few lines we import all the necessary packages. In line 6 the sunspot data is imported and stored in the variable sunspot; for convenience the x-values (year) and y-values (Wolfer number) are stored in separate variables. In line 10 we take the fast Fourier transform (FFT) of the sunspot data. As shown in the figure below, the output is a collection of complex numbers (defining both amplitude and phase of the wave components), and there is noticeable symmetry around Im=0. In order to construct a periodogram, i.e. a graph of power vs. frequency, we first compute the power of the FFT signal which is simply the FFT signal squared. We only need the part of the signal ranging from zero to a frequency equal to the Nyquist frequency, which is equal to half the maximum frequency, since frequencies above the Nyquist frequency correspond to negative frequencies. The frequency range is calculated from 0-N/2 as N/(2T) where N is the number of samples and T is the sampling time. The figure below shows the resulting periodogram. Thus, we can see that there is indeed periodicity in the sunspot data, with frequencies around 0.9 standing out. Note that it is easier to see if we use the period (inverse of frequency) instead of frequency on the x-axis. As seen in the figure we have found out (like many others have) that the sunspot activity data from 1700-2004 is periodic, and that the sunspots occur with a maximum in activity approx. every 11 years. The next and final example is a little more complex than the previous ones. The task it should accomplish is to cycle through a number of data files (similar to the ones used in Example 3 of Part I) and take a slice of each data file, corresponding to an X-ray diffraction peak as shown in example 2 in Part I. To this peak a Gaussian (bell) curve should be fitted and the fitting parameters should be stored in a datafile. The extracted parameters: peak position, peak height, peak width, all contain valuable information about the sample under investigation (MgH2, another material for solid state hydrogen storage). The peak position is related to the crystal lattice of the material (actually the interatomic spacing, if we're to be precise), the peak height corresponds to the abundance of the material, and the peak width corresponds to the domain size of the MgH2 crystallites. Furthermore, the script should take two command line arguments, plot and data, enabling plotting of the peak fit as the script cycles through the data files as well as printing out the fitting parameters to the screen. This option is mainly of diagnostic nature. Furthermore, there should be some sort of mechanism evaluating the quality of the fit and in case the fit is poor it should be disregarded. Finally, the scripts should generate a plot of the fitting parameters as a function of time (cycle #). The length of the script approaches 100 lines and will not be shown, but it is stored in the file lgtixrpd.py.txt. In the following section, I will go though the main parts of the script. To run the example yourself you'll have to download and unpack the data files. A), peak position ( B), peak half width ( C), and the background ( D). plotas the first argument, each fit is plotted along the way though the files. In lines 42-53, the state of the fit is evaluated. If, e.g., the amplitude is negative or the peak position is out of bounds, the fit is disregarded and the corresponding fitting parameters are not stored (only zeros are stored). If the script is passed a command line argument called data, the fitting parameters are printed to screen as the data files are cycled through. ggvand a pnmversion of the hard copy is created. The figure below shows the created plot. From the plot, we notice that during heating (linear) of our sample, the peak position shifts towards lower values. According to Bragg's law of diffraction, there is an inverse relationship between the peak position and the lattice spacing. Thus, our sample expands during heating (as expected). We also observe that when the sample has been heated to 400°C for some time, the amplitude starts decreasing, signaling a disappearance of MgH2 due to decomposition accompanied by the release of hydrogen. In this article, a few examples have been given in order to illustrate that Python is indeed a powerful tool for visualization and analysis of scientific data. It combines the plotting power of gnuplot with the power of a real programming language. The SciPy package includes many scientific tools suitable for data analysis. Manuals, Tutorials, Books etc: See also previous articles about Python published in L.
http://www.cyberuse.com/LDP/LDP/LGNET/115/andreasen.html
crawl-003
refinedweb
1,897
63.39
The textbook approach to simple performance analysis is to call. Trouble with threads Profiler Interface. The JVMPI provides a function, GetCurrentThreadCpuTime(), which returns the CPU time in nanoseconds for the current Java thread. It does this no matter which technique you use to map Java threads to OS threads. Despite the nanosecond resolution, the function is not more precise than the underlying operating system. On Windows NT it works in 10 millisecond increments. An extremely simple profiler agent with the ability to access this information consists of the following C++ code: #include <jvmpi.h> // global jvmpi interface pointer static JVMPI_Interface *jvmpi_interface; extern "C" { // profiler agent entry point JNIEXPORT jint JNICALL JVM_OnLoad(JavaVM *jvm, char *options, void *reserved) { // get jvmpi interface pointer if ((jvm->GetEnv((void **)&jvmpi_interface, JVMPI_VERSION_1)) < 0) { return JNI_ERR; } return JNI_OK; } JNIEXPORT jlong JNICALL Java_dk_capgemini_tc_JProf_getCurrentThreadCpuTime(JNIEnv *, jclass) { // return 0 if agent not initialized return jvmpi_interface == 0 ? 0 : jvmpi_interface->GetCurrentThreadCpuTime(); } } This function may be called from a Java program using JNI via the following class: package dk.capgemini.tc; public class JProf { public static native long getCurrentThreadCpuTime(); static { System.loadLibrary("capjprof"); } } The capjprof.zip file (Resources) accompanying this tip contains the source code and make files for Solaris and Windows NT. The resulting DLL or shared object must be put in the library path for the JVM to find, and the JVM must be told to use it with an application. java -Xruncapjprof application The -Xrun option enables the profiler by instructing the JVM to call JVM_OnLoad() in the capjprof library. If you run the application without this option, JProf.getCurrentThreadCpuTime() will return 0. Comparing collection indexing You can try this out with a comparison of indexing into an array, an Arrays.asList, a ListArray, and a Vector. First you need a helper class to support the microbenchmark: class Prof extends dk.capgemini.tc.JProf { String me; long time, cputime; Prof(String name) { me = name; } void start() { cputime = getCurrentThreadCpuTime(); time = System.currentTimeMillis(); } void stop() { cputime = getCurrentThreadCpuTime() - cputime; time = System.currentTimeMillis() - time; } void print() { System.out.println(me + " time: " + time + " ms" + " cputime: " + cputime/1000000 + " ms"); } } The methods to be measured index a number of times and assign the result to a variable so that the loop is not optimized away. Below is the Vector indexing. The other methods look the same except for the type of the collection list parameter. void index(int n, Vector c) { Object o; for (int i=0; i<n; i++) { for (int j=0; j<c.size(); j++) { o = c.get(j); } } } The main method creates the collections with the same contents and makes the comparisons (see capjprof.zip for the full source). The application takes a number of optional parameters controlling the number of elements in the collection (default is 1,000), the number of times to loop (default is 10,000), and whether the methods should be called in sequence or in parallel (default is in sequence). java -Xruncapjprof performance.CollIndex [elements 1000] [times 10000] [threads] My single-processor Windows NT with JDK 1.2.2 using the JIT produces the following results, which show that you should avoid unnecessary synchronization in Vector, because a simple array is much more efficient. With JDK 1.3 RC1, the figures indicate that synchronization has become much more efficient with HotSpot. The reason ArrayList does not perform better than Vector here is that ArrayList.get() contains sloppy code. Make your own version with a better range check if performance matters. Just for fun, try to run the measurements in parallel in separate threads and note the difference in elapsed time and CPU time. Conclusion In this tip, I demonstrated how to utilize the JVMPI to measure execution time and discussed why this approach is best for microbenchmarking. However, there are still problems. An optimizing JVM like HotSpot may fool you with microbenchmarks because overly simple code may escape optimization or be totally eliminated. Additionally, the garbage collector may interfere and use time in a entirely JVM-dependent manner. With JDK 1.2.2, the garbage collection is done in the user thread, whereas a system thread does the work with HotSpot. Under HotSpot, the incremental garbage collection cannot run when using an active profiler agent. You can influence the behavior of the garbage collector by calling System.gc() and by setting initial and maximum heap size when starting the JVM. Learn more about this topic capjprof.zipcontains the source code and compiled versions for Windows NT and Solaris - Java Virtual Machine Profiler Interface (JVMPI) - "Using HPROF to Tune Performance," from the Sun Developer Connection - IBM Systems Journal Vol 39, No. 1 on "Java Performance," includes design rationale for JVMPI - OptimizeIt 3.1 Professional - KL Group's JProbe - "Java on Solaris 2.6" -- a whitepaper that includes performance tips - Sun's Java HotSpot "Benchmarking Questions and Answers" - Java Linux - PerfAnal is a free graphical tool based on HPROF. It was originally published with Java Programming on Linux by Nathan Meyers
http://www.javaworld.com/article/2077596/build-ci-sdlc/java-tip-92--use-the-jvm-profiler-interface-for-accurate-timing.html
CC-MAIN-2016-22
refinedweb
822
56.96
How Did We Build Book Recommender Systems in an Hour Part 1 — The Fundamentals.. So, if you want to learn how to build a recommender system from scratch, let’s get started. Data Book-Crossings is a book ratings dataset compiled by Cai-Nicolas Ziegler. It contains 1.1 million ratings of 270,000 books by 90,000 users. The ratings are on a scale from 1 to 10. The data consists of three tables: ratings, books info, and users info. I downloaded these three tables from here. import pandas as pd import numpy as np import matplotlib.pyplot as plt books = pd.read_csv('BX-Books.csv', sep=';', error_bad_lines=False, encoding="latin-1") books.columns = ['ISBN', 'bookTitle', 'bookAuthor', 'yearOfPublication', 'publisher', 'imageUrlS', 'imageUrlM', 'imageUrlL'] users = pd.read_csv('BX-Users.csv', sep=';', error_bad_lines=False, encoding="latin-1") users.columns = ['userID', 'Location', 'Age'] ratings = pd.read_csv('BX-Book-Ratings.csv', sep=';', error_bad_lines=False, encoding="latin-1") ratings.columns = ['userID', 'ISBN', 'bookRating'] Ratings data The ratings data set provides a list of ratings that users have given to books. It includes 1,149,780 records and 3 fields: userID, ISBN, and bookRating. Ratings distribution The ratings are very unevenly distributed, and the vast majority of ratings are 0. Books data The books data set provides book details. It includes 271,360 records and 8 fields: ISBN, book title, book author, publisher and so on. Users data This dataset provides the user demographic information. It includes 278,858 records and 3 fields: user id, location and age. Age distribution The most active users are among those in their 20–30s. Recommendations based on rating counts The book with ISBN “0971880107” received the most rating counts. Let’s find out what book it is, and what books are in the top 5. The book that received the most rating counts in this data set is Rich Shapero’s “Wild Animus”. And there is something in common among these five books that received the most rating counts — they are all novels. The recommender suggests that novels are popular and likely receive more ratings. And if someone likes “The Lovely Bones: A Novel”, we should probably also recommend to him(or her) “Wild Animus”. Recommendations based on correlations We use Pearsons’R correlation coefficient to measure linear correlation between two variables, in our case, the ratings for two books. First, we need to find out the average rating, and the number of ratings each book received. Observations: In this data set, the book that received the most rating counts was not highly rated at all. As a result, if we were to use recommendations based on rating counts, we would definitely make mistakes here. So, we need to have a better system. To ensure statistical significance, users with less than 200 ratings, and books with less than 100 ratings are excluded. Rating matrix We convert the ratings table to a 2D matrix. The matrix will be sparse because not every user rated every book. Let’s find out which books are correlated with the 2nd most rated book “The Lovely Bones: A Novel”. To quote from the Wikipedia: “It is the story of a teenage girl who, after being raped and murdered, watches from her personal Heaven as her family and friends struggle to move on with their lives while she comes to terms with her own death”. We obtained the books’ ISBNs, but we need to find out the titles of the books to see whether they make sense. Let’s select three books from the above highly correlated list to examine: “The Nanny Diaries: A Novel”, “The Pilot’s Wife: A Novel” and “Where the Heart is”. “The Nanny Diaries” satirizes upper class Manhattan society as seen through the eyes of their children’s caregivers. Written by the same author as “The Lovely Bones”, “The Pilot’s Wife” is the third novel in Shreve’s informal trilogy to be set in a large beach house on the New Hampshire coast that used to be a convent. “Where the Heart Is” dramatizes in detail the tribulations of lower-income and foster children in the United States. These three books sound like they would be highly correlated with “The Lovely Bones”. It seems our correlation recommender system is working. Summary In this post, we have learned about how to design simple recommender systems that you can implement and test it in an hour. The Jupyter Notebook version for this blog post can be found here. If you want to learn more, Xavier Amatriain’s lecture is a good place to start. In a future post, we will cover more sophisticated methods such as Content-Based Filtering, k-Nearest Neighbors, Collaborate Filtering as well as how to provide recommendations and how to test the recommender system. Until then, enjoy recommendations!
https://medium.com/towards-data-science/how-did-we-build-book-recommender-systems-in-an-hour-the-fundamentals-dfee054f978e
CC-MAIN-2017-43
refinedweb
801
65.01
Lesson 12 - Mathematical functions in C++ - The cmath library Lesson highlights Are you looking for a quick reference on the cmath library in C++ instead of a thorough-full lesson? Here it is: Using cmath constants: #include <iostream> #include <cmath> using namespace std; int main() { cout << "Pi: " << M_PI << endl; cout << "e: " << M_E << endl; } Min/max of 2 values: #include <iostream> #include <cmath> using namespace std; int main() { cout << "Min: " << fmin(5, 10) << endl; cout << "Max: " << fmax(5, 10) << endl; } All roundings: #include <iostream> #include <cmath> using namespace std; int main() { cout << "Round: " << round(-0.2) << endl; cout << "Ceiling: " << ceil(-0.2) << endl; cout << "Floor: " << floor(-0.2) << endl; cout << "Truncate: " << trunc(-0.2) << endl; double d = 2.72; int a = (int)round(d); // casting the rounded double to the int type } Abs/signbit: #include <iostream> #include <cmath> using namespace std; int main() { cout << "Abs: " << abs(-10) << endl; cout << "Sign: " << signbit(-10) << endl; } Trigonometric functions: #include <iostream> #include <cmath> using namespace std; int main() { cout << "Sin: " << sin(M_PI) << endl; // almost 0 cout << "Cos: " << cos(M_PI) << endl; cout << "Tan: " << tan(M_PI) << endl; // almost 0 cout << "Acos: " << acos(0) << endl; cout << "Asin: " << asin(-1) << endl; cout << "Atan: " << atan(0) << endl; } Powers, roots, logarithms: #include <iostream> #include <cmath> using namespace std; int main() { cout << "Pow: " << pow(2, 3) << endl; cout << "Sqrt: " << sqrt(144) << endl; cout << "Exp: " << exp(2) << endl; cout << "Log: " << log(100) << endl; cout << "Log10: " << log10(100) << endl; } Dividing whole numbers in C++ always results in another whole number: {CPP_CONSOLE} int a = 5 / 2; double b = 5 / 2; double c = 5.0 / 2; double d = 5 / 2.0; double e = 5.0 / 2.0; int f = 5 / 2.0; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; cout << "d = " << d << endl; cout << "e = " << e << endl; cout << "f = " << f << endl; {/CPP_CONSOLE} The remainder after division (modulo): {CPP_CONSOLE} cout << (5 % 2) << endl; // prints 1 {/CPP_CONSOLE} Would you like to learn more? A complete lesson on this topic follows. In today's lesson of the C++ basics course, we're going to take a look at the cmath standard library. It provides a variety of functions for solving common math problems, we're going to mention the most important of them all. fmin(), fmax(), fdim() Let's start with the simple functions All 3 functions take two numbers of the double data type as parameters. Fmin() returns the smallest number, fmax() returns the largest one. The fdim() function returns x-y if ( x > y) or 0 otherwise. round(), ceil(), floor(), and trunc() All three functions are related to rounding and they all accept a parameter of the double type. Their return value is also of the double type. Round() takes a decimal number as a parameter and returns the number, rounded as a double data type. It rounds in the same way we learned in school (anything over 0.5 is rounded upwards, otherwise the number is rounded downwards). Ceil() rounds upwards and floor() rounds downwards no matter what. Trunc() cuts the decimal part off and leaves the whole number part intact (does not round it whatsoever). We'll certainly be using round() very often. I've used the other functions for things like determining the number of pages in a table (e.g. of a table printed to the console). When we have 33 items and we only print 10 items per page, they would take up 3.3 pages. Therefore, the result must be rounded up since we would actually need 4 pages. If you think that floor() and truncate() do the same thing, think again! They behave differently for negative numbers. Floor() rounds negative numbers down to an even "more negative" number, trunc() always rounds to zero when the input is negative. We round decimal numbers and store them in int variables like this: double d = 2.72; int a = (int)round(d); Casting to int is necessary despite the fact that the round() method returns a whole number. It is still of the double type, due to the fact that all mathematical functions have the same interface. The return types of the following functions won't be mentioned anymore (since they'll all be double). abs() and signbit() Abs() returns the absolute value of its parameter and signbit() returns 1 if the parameter is negative or 0 otherwise. The signbit() function is not supported by all compilers so it's possible that it won't be available everywhere. sin(), cos(), tan() Classic trigonometric functions, all take an angle which has to be entered in radians (not degrees if your country uses them). To convert degrees to radians we multiply them by (M_PI / 180). acos(), asin(), atan() Inverse trigonometric (arcus, sometimes cyclometric) functions, which return the original angle according to the trigonometric value. They're the inverse functions for sin(), cos(), and tan(). The parameter is a function value and the returned value is the original angle in radians (returned as a double). If we wanted to get an angle in degrees, we'd have to divide the radians by (180 / M_PI). pow() and sqrt() Pow() takes two input parameters. The first is the base of the power and the second is the exponent. If we wanted to calculate something like 23, the code would be as follows (don't forget to include the cmath library for all of the examples): #include <iostream> #include <cmath> using namespace std; int main() { cout << pow(2, 3); return 0; } Sqrt() is an abbreviation of SQuare RooT, which returns the square root of the number given as a double. exp(), log(), log10() Exp() returns Euler's number raised to the given exponent. Log() returns the natural logarithm of the given number. Log10() returns the decadic logarithm of the number. Hopefully, you noticed that the method list lacks any general root function. We can, however, calculate it using the functions the cmath library provides. We know that roots work like this: 3rd root of 8 = 8^(1/3). Therefore, we can write: #include <iostream> #include <cmath> using namespace std; int main() { cout << pow(8, (1.0/3.0)); return 0; } ItPP_CONSOLE} int a = 5 / 2; double b = 5 / 2; double c = 5.0 / 2; double d = 5 / 2.0; double e = 5.0 / 2.0; int f = 5 / 2.0; cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d << " e=" << e << " f=" << f << endl; {/CPP_CONSOLE} We divide 5/2 several times in the code. Mathematically, it's 2.5. Nonetheless, the results will not be the same in all cases. Can you guess what we'll get in each case? Go ahead, give it a try The program output will be as follows: Console application a=2 b=2 c=2.5 d=2.5 e=2.5 f=2 We see the result of this division is sometimes decimal and sometimes whole. The data type of the variable we're assigning the result to is not all that matters. What matters most is the data type of the numbers we divide by. If one of the numbers is decimal, the outcome will always be a decimal number. The division of 2 integers always returns an integer. Keep in mind that if you compute the average and want a decimal result, at least one variable must be cast to double. int sum = 10; int count = 4; double average = (double)sum / (double)count; Note: For example, the PHP language always returns the decimal result for a division. When you divide in different programming languages make sure you check how division works internally before you use it. The remainder after division In our applications, we often need the remainder after dividing integers (i.e. modulo). In our example 5/2, the integer result is 2 and the modulo is 1 (what left over). Modulo is often used to determine whether a number is even (the remainder of a division by 2 is 0). You would also use it, for example, to draw a checkerboard and fill in the fields based on whether they are even or odd, calculate the deviance of your position in a square grid, etc. In C++ and C-like languages in general, modulo is a percent sign, i.e. %: {CPP_CONSOLE} cout << "The remainder after 5 / 2 is " << 5 % 2 << endl; // prints 1 {/CPP_CONSOLE} We're done for today. In the next lesson, Solved tasks for C++ lessons 11-12, we'll introduce declaring custom functions, which is very important since doing so allows us to split our program up into multiple logical parts. In the following exercise, Solved tasks for C++ lessons 11-12, we're gonna practice our knowledge from previous lessons. No one has commented yet - be the first!
https://www.ictdemy.com/cplusplus/basics/mathematical-functions-in-cplusplus-the-cmath-library
CC-MAIN-2021-31
refinedweb
1,449
71.14
Opened 11 years ago Closed 11 years ago Last modified 10 years ago #783 closed enhancement (fixed) Add ¨id¨ field to anonymous user object Description I am frequently needing the functionality to allow users to only update their own data and not other peoples data. In my template I tried something like this according to the pythonic principal of least surprise: {% ifequal user.id data.author_id %} #allow user to do something (e.g. show an edit link) {% endifequal %} If the user is anonymous, this fails and shows a traceback, because the anonymous user has not have an ¨id¨ property. Instead I must write this: {% if not user.is_anonymous %}{% ifequal user.id data.author_id %} # allow user to do something {% endifequal %}{% endif %} The same problem arises in view code: if request.user.is_anonymous() or (request.user.id <> data.author_id): # deny access to template and give out error Suggestion: If the anonymous user had an ¨id¨ property, the additional checks would not be needed. The value for this ¨id¨ could be ¨None¨ as not be be mistaken for a real user. I believe that the User and Anonymoususer objects should behave as similar to each other as possible, and I believe this improves things a bit. (In [1221]) Fixed #783 -- Added AnonymousUser.id = None. Thanks, EABinGA
https://code.djangoproject.com/ticket/783
CC-MAIN-2016-50
refinedweb
213
62.88
hi. i was into raw sockets the last time so i wrote a simple program that would create a single packet and send it to the destination. with that code i want to establish a connection to my gateway on port 23. so i switched on tcpdump on the gateway and sent the packet. the was successfully sent but the gateway wasnt replying to that syn packet.with that code i want to establish a connection to my gateway on port 23. so i switched on tcpdump on the gateway and sent the packet. the was successfully sent but the gateway wasnt replying to that syn packet.Code: #include <netinet/in.h> #include <sys/socket.h> #include <netinet/ip.h> #include <netinet/tcp.h> int main () { int tcp_socket; struct sockaddr_in peer; struct send_tcp { struct iphdr ip; struct tcphdr tcp; } packet; packet.ip.version = 4; packet.ip.ihl = 5; packet.ip.tos = 0; packet.ip.tot_len = htons(40); packet.ip.id = 1; packet.ip.frag_off = 0; packet.ip.ttl = 255; packet.ip.protocol = IPPROTO_TCP; packet.ip.check = 14536; packet.ip.saddr = inet_addr("192.168.0.10"); packet.ip.daddr = inet_addr("192.168.0.1"); packet.tcp.source = htons(8000); packet.tcp.dest = htons(23); packet.tcp.seq = 1; packet.tcp.ack_seq = 2; packet.tcp.doff = 5; packet.tcp.res1 = 0; packet.tcp.fin = 0; packet.tcp.syn = 1; packet.tcp.rst = 0; packet.tcp.psh = 0; packet.tcp.ack = 0; packet.tcp.urg = 0; packet.tcp.res2 = 0; packet.tcp.window = htons(512); packet.tcp.check = 8889; packet.tcp.urg_ptr = 0; peer.sin_family = AF_INET; peer.sin_port = htons(25); peer.sin_addr.s_addr = inet_addr("192.168.0.1"); tcp_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); sendto(tcp_socket, &packet, sizeof(packet), 0, (struct sockaddr *)&peer, sizeof(peer)); close(tcp_socket); return 0; } why that? thanks ps. i have the port openend i want to connect to.
http://cboard.cprogramming.com/c-programming/33087-packets-dropped-kernel-printable-thread.html
CC-MAIN-2015-27
refinedweb
309
57.64
changes.mady.by.user Lusheng Ji Saved on Jun 25, 2020 Saved on Jul 01, 2020 RIC and SMO Installation completed. The SMO A1 (policy) flow is almost identical to what we have shown in the xApp (Traffic Steering) flow, with the difference that the policy operations (i.e. policy type creation, policy instance creation) are coming from the SMO instead of directly calling A1 mediator API. In SMO cluster, the Near RT RIC's coordinates (IP, port, etc) is specified in the recipe for the NonRTRIC. To check whether SMO has successfully established communication with Near RT RIC, Run the following on the SMO cluster: $ curl To create a new policy instance under policy type 20008 (Traffic Steering's threshold policy), Run: $ POLICY_TYPE_ID="20008"$ curl -v i-X PUT --header "Content-Type: application/json" \"{POLICY_TYPE_ID}" \--data "{\"threshold\" : 1}" O-DU HIGH - NearRTRIC E2 setup: odu-high.mp4 A1 flow: a1.mp4 O1 flow: o1.mp4 Kubectl commads: kubectl get pods -n nampespace - gets a list of Pods running kubectl get logs -n namespace name_of_running_pod Complete these tasks to get started Powered by a free Atlassian Confluence Open Source Project License granted to The Linux Foundation. Evaluate Confluence today.
https://wiki.o-ran-sc.org/pages/diffpagesbyversion.action?pageId=20875214&selectedPageVersions=13&selectedPageVersions=14
CC-MAIN-2021-21
refinedweb
199
50.77
ijson 2.2 Iterative JSON parser with a standard Python iterator interface: wrapper around YAJL version 2.x - yajl: wrapper around YAJL version 1.x - python: pure Python parser (good to use under PyPy) You can import a specific backend and use it in the same way as the top level library: import ijson.backends.yajl2 as ijson for item in ijson.items(...): # ... Importing the top level library as import ijson uses the pure Python backend. Acknowledgements. - Downloads (All Versions): - 127 downloads in the last day - 869 downloads in the last week - 4046 downloads in the last month - Author: Ivan Sagalaev - License: BSD - Categories - Package Index Owner: isagalaev - DOAP record: ijson-2.2.xml
https://pypi.python.org/pypi/ijson/
CC-MAIN-2015-22
refinedweb
114
53.71
@artsy/express-reloadable When developing a Node app it's common to rely on tools like node-dev or nodemon to make the development process more rapid by automatically restarting the server instance on file-change. What express-reloadable does is listen for source-code changes within a subset of your app and, scanning Node's internal module cache, clears the require call if found. This tricks Node into thinking the module has not yet been loaded, effectively hot-swapping out your code without a full restart. Additionally, when the watchModules option is passed, express-reloadable will listen for changes to NPM module code and reload on change. Useful when working with yarn link across packages / repos. Crazy-fast development speed! Disclaimer: While this works for most of our use-cases, this is an example of " require hacking"and hasn't been tested in all environments. Your mileage may vary. How it works: express-reloadableis called with a path to an app, which it then mounts - When source-code within that folder / app changes an internal lookup is made to Node, scanning its requirecache for the changed file - If found, it is cleared internally via delete require.cache[id] - When a new request is made express-reloadableexecutes a callback that re-requires the code and changes are instantly available. Installation: yarn add @artsy/express-reloadable Example: The below example assumes that the folders /api and /client exist, and that each contain an index file that exports a mountable express.js route. import express from 'express' import { createReloadable, isDevelopment } from '@artsy/express-reloadable' const app = express() if (isDevelopment) { // Pass in `app` and current `require` context const mountAndReload = createReloadable(app, require) // Pass in the path to an express sub-app and everything is taken care of mountAndReload(path.resolve(__dirname, './client')) // Full example: app.use('/api', mountAndReload(path.resolve(__dirname, './api')), { // If you need to mount an app at a particular root (`/api`), pass in // `mountPoint` as an option. mountPoint: '/api', // Or if you're using `yarn link` (or npm) to symlink external dependencies // during dev, pass in an array of modules to watch. Changes made internally // will be instantly available in the app. Additionally, using something like // `glob`, other modules outside of express route path can be passed. watchModules: [ '@artsy/reaction', '@artsy/artsy-xapp' ] })) // If prod, mount apps like normal } else { app.use('/api', require('./api') app.use(require('./client') } app.listen(3000, () => { console.log(`Listening on port 3000`) }) Troubleshooting: Help! I've mounted my app using reloadable but I'm not seeing any changes? For the utility to work you need to a) ensure that NODE_ENV=development (for safety) and b) the path to your app is absolute: // Incorrect app.use(reloadAndMount('./path/to/app')) // Correct app.use(reloadAndMount(path.resolve(__dirname, 'path/to/app'))) Thanks: This package was heavily inspired by @glenjamin's ultimate-hot-loading-example.
https://www.npmtrends.com/@artsy/express-reloadable
CC-MAIN-2022-21
refinedweb
478
53.41
Praveen Adivi 7 Dec 2010, 8:04 AM Hi All, I am a newbie to extjs and I had a question regarding ext.ns's behavior. I have a js file where in I define a name space useing Ext.ns("Ext.ux.test"); and this js file is then added to the jsp and when I include another jsp into the current jsp using jsp:include I get a javascript error saying, "Ext.ux.test is undefined". So, I was wondering if any body could kindly tell me how to make sure that the namespace Ext.ux.test is not lost. Thank you in advance.
https://www.sencha.com/forum/archive/index.php/t-117952.html
CC-MAIN-2016-36
refinedweb
106
74.79
No new comments. Go to all comments >> No new messages. Go to all messages >> No new notifications. Go to all notifications >> * * Login using TECHNOLOGIES Request a new Category | View All ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER Jobs CODE IDEAS No tag found Content Filter Articles Tutorials Videos Blogs Resources News Forums Interviews Complexity Level Beginner Intermediate Advanced Refine by Author [Clear] Mike Gold(8) Mahesh Chand(7) Amir Ali(5) Charles Petzold(4) Scott Lysle(3) Diptimaya Patra(3) John O Donnell(3) Gaurav Gupta(2) nildo (2) Tom Curry(2) Rick Meyer(2) Gaurav Chauhan(2) pinto.philip (2) Tony Tromp(2) Suman Goswami(1) Manish Tewatia(1) Hemant Srivastava(1) Manisha Mehta(1) Varesh Tuli(1) Shekhar Chauhan(1) Ghanashyam Nayak(1) Akshay Teotia(1) Benjamin Kemner(1) Mostafa Kaisoun(1) Amit Choudhary(1) Nipun Tomar(1) Raj Kumar(1) mohabbat (1) Thinathayalan Ganesan(1) Gaurav Pilay(1) Ehanth Lingam(1) Orlando Paganini(1) A Jean Michel Cobb(1) Wiktor Zvchla(1) shru27 (1) Perry Lee(1) sameh ahmed(1) Scott Penner(1) Raimund Neumuller(1) Alberto Ferrazzoli(1) Scott MacDiarmid(1) Jigar Desai(1) andyhmcheung (1) Daniel Stefanescu(1) Anders Carlsen(1) K Niranjan Kumar(1) Resources No resource found Easily Implementing CAPTCHAs in C# May 02, 2015. This article shows how to implement CAPTCHAs without a CAPTCHAs library and bitmap image generator code. Retrieve Image From Drawable Folder and Store in Sqlite Database in Android Dec 16, 2013. This article explains how to retrieve an image from a Drawable folder and store it in a SqliteDatabase in Android. How to Store a Person's Data With Image in SQLite Database Dec 13, 2013. This article explains how to store a person's data with an image in a SQLite Database. BItMap in Andoid Nov 20, 2013. This article explains BitMaps in Android. Android Studio is used to create the sample.. How to Capture and Crop Image in Android Jul 03, 2013. In this article you will learn how to capture and crop an image on a button click and show it in an ImageView in Android. How to Set Image in a Image View on Click in Android Studio Jun 13, 2013. In this article you will learn how to set image in a Image View by click on the image.. Color Detecting in an Image in C# Nov 25, 2012. This article shows how to detect a specific color in an image in C#. A sample code is also attached along with this article for your reference. Rendering Image Using Pixel Buffer in Windows Store Apps Nov 22, 2012. In this article I will how you how to load an image using Pixel Buffer or PBuffer by using WritableBitmap in Windows Store Apps using XAML. Drawing Rubber-Band Lines and Shapes in VB.NET Nov 10, 2012. I would like to show how we can draw rubber-band lines and shapes in GDI+ with just a few lines of code.. Working with PNGs using GDI+ Nov 10, 2012. PNG overcomes the color depth hurdle by providing up to 48Bpp (bits per pixel). Just as importantly, the PNG format is patent-free and available for use by anyone. Auto Redraw in VB.NET Nov 08, 2012. This is a problem if you wish to display text and graphics directly on a form. This brief project should help to provide you with AutoRedraw capability. Convert a DataGridView to a Bitmap in VB.NET Nov 08, 2012. This article describes an easy approach to converting a DataGridView control into a Bitmap. Nov 02, 2012. In this article we are going to learn how to load an image into a Bitmap Image with a file stream in Window Store Apps. Adding a Bitmap Checkpoint While Editing the Test in QTP in Testing Sep 13, 2012. In this article I discuss how to insert a Bitmap Checkpoint while editing the Test in QTP. To Create a Bitmap Checkpoint While Recording in QTP in Testing Sep 03, 2012. In this article we discuss about how to create a bitmap checkpoint while recording in QTP. Checking Bitmaps in QTP in Testing Aug 29, 2012. In this article we discuss the functionality of a Bitmap Checkpoint Type of Checkpoints in Testing Jul 24, 2012. In this article we discuss the various types of Checkpoints Load XML File Data in DataGridView & Print DataGridView Data Feb 09, 2012. Using this article you can understand how to load the XML file's record into the DataGridView & then you can print that DataGridView. Working with Canvas Tag in HTML 5 Dec 31, 2011. The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. How to Create a Picture of a WPF Control Jul 15, 2011. WPF has some simple methods to render a control in a picture format like jpeg, png, bitmap etc. In this article we will see how to do that.. Working with Elements and Properties in Windows Phone 7 Dec 01, 2010. This article explores text and bitmaps in more depth, and also describes other common elements and some important properties you can apply to all these elements, including transforms.. Using Bitmap and Texture in Silverlight and XNA application for Windows Phone 7 Nov 20, 2010. Bitmap is an object which is appear in both Silverlight and XNA applications but in XNA, a bitmap has a data type of Texture2D and hence is often referred to as a texture. Bitmaps are used to symbolize your application on the phone. Lunar calendar in C# Aug 18, 2010. In this article I will show how to create a lunar calendar in C#. Bitmap Effects In WPF - Part I Apr 08, 2010. In this article we will see what the Bitmap Effects available in WPF are, and how it can improve the controls look better. Bitmap Effects In WPF - Part II Apr 08, 2010. In previous article we saw how we can add effects; we experienced Blur and Outer Glow Bitmap effects. In this article we will see rest of the 3 Bitmap Effects.. Working with Bitmaps in GDI+ Feb 17, 2010. In this article I will explain about working with Bitmaps in GDI+. Windows Icon in WPF Jan 14, 2010. An Icon is a bitmap image (.ico file) that is displayed in the top left corner of a Window. This article discusses how to create and use Icons in WPF applications.. GDI+ Application Nov 01, 2009. In this article we move to the more practical aspects of writing graphics applications using GDI+ in the .NET Framework. Include Files as Resources in Silverlight 2.0 Mar 13, 2009. This article describes how to load an embedded bitmap programmatically. Bitmap Effects using WPF Aug 19, 2008. This article shows how to give Bitmap Effect in WPF. Sample Application: Falling Apples Game Jan 08, 2008. This article is a sample application using structures, bitmaps and other concepts. Hopefully you find it an enjoyable example. Generating ASCII Art from an Image using C# Mar 05, 2007. Have you ever tried converting a standard JPEG/Bitmap image into a fascinating ASCII art ? In this article I'll show you exactly how to do it. Convert a DataGridView to a Bitmap Jan 19, 2007. This article describes an easy approach to converting a DataGridView control into a Bitmap. Image Conversion Utility in C# Sep 14, 2006. This article describes a very easy approach to building an image conversion utility that will permit the user to open a supported image type and convert it to another supported image type. Capturing Desktop and saving image in a Word Document Jun 14, 2006. This code will allow you to capture your desktop and save the image into a word document.... Pocket Trilma.NET Oct 04, 2004. Pocket Trilma.NET is a Pocket PC version of project Trilma.NET.. Screen Capture and Save as an Image Dec 30, 2003. The following example source code shows how to capture the screen and save it to an image... ChessyOnline 1.0: An Online and Network Chess Game Dec 31, 2002. The attached project is a chess game that can be played by two users online as well as on the network. Auto Redraw in VB.NET Dec 13, 2002. This is a problem if you wish to display text and graphics directly on a form. Working with Portable Network Graphics(PNG) Format : Part I Dec 13, 2002. First off, why use PNG instead of GIF? Probably the most important reason is that GIF supports a maximum of 256 colors. Working With DirectDraw and Bitmap Images Sep 05, 2002. This month in the C-sharp DirectX column, we will be adding bitmap image support to our game engine.. Creating Graphics with XML Apr 09, 2002. This article shows how to create images on the fly and uses XML to specify the properties of the images. An Imporved LED Counter Apr 01, 2002. This in an improved version of Keeping Score with LED Counter article originally written by John O'Donnell. Memory Game Mar 19, 2002. This is a memory game where you can use your favorite pictures (.bmp, jpg, gif). Drawing rubber-band lines and shapes Mar 12, 2002. I would like to show how we can draw rubber-band lines and shapes in GDI+ with just a few lines of code. A Wheel Control in C# Feb 15, 2002. This article describes a simple Windows control written in C# that simulates a wheel knob like that on your walkman used to change volume. Drag and Drop for Board Games Jan 22, 2002. This application shows how the drag and drop features in C# could be used to create a simple board game or whatever. Creating Exploded Pie Chart Having Click Through Functionality in C# Dec 26, 2001. In this article I would like to show you code that would create exploded pie chart and implementing click through functionality to that chart.. Mark Six on the Fly Dec 04, 2001. In this sample, I demonstrate how a WebForm can be called directly as an Image.. Hangman: Using GDI+ in ASP.NET Applications Oct 11, 2001. This example shows how you can combine GDI+ commands on a web form. Screen Capturing a Form in .NET - Using GDI and GDI+ Sep 15, 2001. This article shows way to do form capture in GDI is to get the device context to the screen and bit blast it to a Bitmap in memory. A variety of Chart Engines Sep 07, 2001. The original code came from Scott Guthrie’s chart engine example. The differences from original code.. Scaling an Image Jul 13, 2001. This code will show You on way to scale an image with .Net Beta. Mar 13, 2001. In .NET framework, the Icon class represents a Windows icon, which is a small bitmap image used to represent an object. The icon class is defined in System.Drawing namespace. Working with GDI+ Brushes Jan 30, 2001. This tutorial explains how to work with texture, solid, gradient, and hatch brushes. Graphics Animation Sample May 16, 2000. After finishing a text program (lottery) its time for some fun. Everytime a have to work with a new language.I write a small program to bounce some balls in a box. About BitMap Bitmap is short for BMP is an image file format that can be used to create and store computer graphics. A Bitmap file displays a small dots in a pattern that, when viewed from afar, creates an overall image and that Bitmap image is a grid made of rows and columns where a specific cell is given a value that fills it in or leaves it blank thus creating an image out of the data. A bitmap or raster graphic is a digital image composed of a matrix of dots. When we try to viewed at 100%, each dot corresponds to an individual pixel on a display. In a standard Bitmap image each dot can be assigned a different color. Together these dots can be used to represent any type of rectangular picture. There are several different bitmap file formats. The standard uncompressed bitmap format is also known as the Bitmap..
http://www.c-sharpcorner.com/tags/BitMap
CC-MAIN-2016-18
refinedweb
2,039
66.23
Sometimes you just need to play an MP3 file. Whether it's a sound track does need a few additional items for you to get started, shown below. However, you may already have a few of these items, so feel free to modify your cart as necessary. If you’re unfamiliar with switches, jumper pads, or I2C be sure to checkout some of these foundational tutorials. The Qwiic Keypad utilizes the Qwiic connect system. We recommend familiarizing yourself with the Logic Levels and I2C tutorials (above) before using it. Click on the banner above to learn more about our Qwiic products.. All I/O pins are 5V tolerant but the board must but powered at 3.3V. All I/O pins are designed to function at 3.3V. The board consumes 35mA at 3.3V in standby and can consume over 400mA when driving at 8 Ohm speaker at max volume.. There are several I/O pins broken out on the board, which are described in the table below.. The SparkFun Qwiic MP3 Trigger Arduino library demonstrates how to control all the features of the Qwiic MP3 Trigger. We recommend downloading the SparkFun library through the Arduino library manager by searching 'SparkFun MP3 Trigger'. Alternatively you can grab the zip here from the GitHub repository: Once you have the library installed checkout the various examples. mp3.playFile(3);will play F003.mp3. The SparkFun Qwiic MP3 Trigger library takes care of all these commands for you. However, if you want to implement your own interface, the following commands are available (see list below). The Qwiic MP3 Trigger uses standard I2C communication to receive commands and send responses. By default, the unshifted I2C address of the Qwiic MP3 Trigger is 0x37. The write byte is 0x6E and the read byte is 0x6F. Here is an example I2C transaction showing how to set the volume level to 10: Here is an example I2C transaction showing how to read the device ID (0x39): The following commands are available: 0x00- Stops any currently playing track 0x01 [TRACKNUMBER]- Play a given track number. For example 0x01 0x0A will play the 10th MP3 file in the root directory. 0x02 [FILENUMBER]- Play a file # from the root directory. For example 0x02 0x03 will play F003.mp3. 0x03- Pause if playing, or starting playing if paused 0x04- Play the next file (next track) located in the root directory 0x05- Play the previous file (previous track) located in the root directory 0x06 [EQ_SETTING]- Set the equalization level to one of 6 settings: 0 = Normal, 1 = Pop, 2 = Rock, 3 = Jazz, 4 = Classical, 5 = Bass. Setting is stored to NVM and is loaded at each power-on. 0x07 [VOLUME_LEVEL]- Set volume level to one of 32 settings: 0 = Off, 31 = Max volume. Setting is stored to NVM and is loaded at each power-on. 0x08- Returns one byte representing the number of MP3s found on the microSD card. 255 max. Note: Song count is established at power-on. After loading files on the SD card via USB be sure to power-cycle the board to update this value. 0x09- Returns the first 8 characters of the file currently being played. Once the command is issued the MP3 Trigger must be given 50ms to acquire the song name before it can be queried with an I2C read. 0x0A- Returns a byte indicating MP3 player status. 0 = OK, 1 = Fail, 2 = No such file, 5 = SD Error. 0x0B- Returns a byte indicating card status. 0 = OK, 5 = SD Error. Once the command is issued the MP3 Trigger must be given 50ms to acquire the card status before it can be queried with an I2C read. 0x0C- Returns two bytes indicating Major and Minor firmware version. 0x0D- Clears the interrupt bit. 0x0E- Returns byte that represents the volume level. 0x0F- Returns byte that represents the EQ setting. 0x10- Returns 0x39. Useful for testing if a device at a given I2C address is indeed an MP3 Trigger. 0xC7 [NEW_ADDRESS]- Sets the I2C address of Qwiic MP3 Trigger. For example 0x6E 0xC7 0x21will change the MP3 Trigger at I2C address 0x37 to address 0x21. In this example 0x6Eis device address 0x37with write bit set to 1. Valid addresses are 0x08 to 0x77 inclusive. Setting is stored to NVM and is loaded at each power-on. The ATtiny84A receives commands over I2C. It then records the I2C commands into a command que. The que is sent FIFO over serial to the WT2003S at 9600bps. The WT2003S then requires an undetermined amount of time to respond. This means that commands are not instantaneously executed by the Qwiic MP3 Trigger and some commands may require a certain amount of time to before the Qwiic MP3 Trigger has loaded a valid response. For example, GET_SONG_NAME can be issued by the master microcontroller to the Qwiic MP3 Trigger. The QMP3 then transmits a serial command to the WT2003S. After a certain amount of time (unfortunately there are no max times defined by the WT2003S datasheet) the WT2003S will respond via serial. This can take 15 to 40ms. At that time, the song name will be loaded onto the Qwiic MP3 Trigger and can be read over I2C by the master microcontroller. In order to avoid clock stretching by the Qwiic MP3 Trigger and tying up the I2C bus, the Qwiic MP3 Trigger will release the bus after every command is received. Therefore, it is up to the user to wait the minimum 50ms between the WRITE GET_SONG_NAME and the READ I2C commands. The MP3 decoder IC on the Qwiic MP3 Trigger is the WT2003S. It requires approximately 1500ms after power on to mount the SD card. Normally, the Qwiic MP3 Trigger is powered while the user writes and re-writes sketches so the user does not notice this boot time. The boot time only comes into effect when user initially powers their project. The main controller (such as an Uno) needs to wait up to 2 seconds before giving up communicating with the Qwiic MP3 Trigger. The SparkFun Qwiic MP3 Trigger library takes care of the 2 second wait but if you’re writing your own implementation then consider the following example code: language:c if (isConnected() == false) { delay(2000); //Device may take up to 1500ms to mount the SD card //Try again if (isConnected() == false) return (false); //No device detected } return (true); //We're all setup! Up to 255 songs can be loaded onto Qwiic MP3 Trigger and triggered through the command interface. The Qwiic MP3 Trigger can be used both as a standalone board or with the Qwiic connect system. In this case, we will be using the RedBoard Qwiic as the microcontroller in the Qwiic system. For both options, make sure to load an MP3 file labeled T001.mp3 onto the MicroSD card. T002.mp3to associate it with Trigger Pin 2. By default the firmware installed on the ATtiny84 allows you to play tracks using the triggers. For more details, see the Triggers section of the Hardware Overview. Simply plug in the SD card, power the Qwiic MP3 Trigger, and short the Trigger Pin 1 to GND. Everytime you short both pins, T001.mp3 will play. Plug in the SD card into the MP3 Trigger. Then, connect the Qwiic MP3 Trigger to the RedBoard Qwiic using a Qwiic cable. Upload Example1-PlaySong.ino using the Arduino IDE to the RedBoard Qwiic. Once uploaded, the RedBoard will check for the Qwiic MP3 Trigger, set the volume to 10 and then play T001.mp3. Pressing the RESET button on the RedBoard will run the sketch again. Have fun with your new tunes maker! For more on the Qwiic MP3 Trigger, check out the links below: Need some inspiration? Check out some of these related tutorials: Or check out these blog posts: learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado
https://learn.sparkfun.com/tutorials/qwiic-mp3-trigger-hookup-guide/all?print=1
CC-MAIN-2019-43
refinedweb
1,314
73.78
I’ve been using the moment.js library within my two Ionic 2 projects and it has worked ok without problems. I’ve now upgraded my projects (from alpha40 to alpha46) and I now get an error when I try to use the library. In my package.json I have moment specified as a dependency: "moment": "^2.10.6" This seems to bring the package in ok (its listed under node-modules in my project). In my code I import it like this at the top: import * as moment from 'moment'; but when I try to use it i.e this.currentDate = new Date(); this.currentDateMoment = new moment(this.currentDate); I get an error of: TypeError: Object is not a constructor (evaluating ‘new moment(this.currentDate)’) Like I said, this all worked fine in alpha40. Anyone have any ideas what I need to change to get this to work again? Is is something to do with new Ionic 2 project structure or something (i.e my code being in the app folder instead of the www folder ?) I have a funny feeling the Conference app used to use the moment.js library was well but it looks like it doesn’t any more.
https://forum.ionicframework.com/t/error-using-moment-js-with-alpha46-ionic-2/40496
CC-MAIN-2022-21
refinedweb
203
76.62
25 September 2013 19:45 [Source: ICIS news] HOUSTON (ICIS)--US polystyrene (PS) contract prices on average rose in September from the previous month by 3 cent/lb ($66/tonne, €49/tonne) for the general purpose polystyrene (GPPS) and at least 1 cent/lb for the high-impact polystyrene (HIPS) due to gains in feedstock benzene and styrene costs and as inventories are tight amid supply disruption, market sources said. It is the first PS contract price increase since May. The September increase moves PS prices out of the lowest levels of the year, where they had been for two months for the July and August contracts. PS contract prices had last moved in late July when they fell by about 2 cents/lb from June for the July contract settlement. On 13 September, US August styrene contracts settled at an increase of 1 cent/lb on average from the previous month in its second consecutive monthly increase. On 30 August, the September benzene contract settled at $4.40/gal, up by 23 cent/gal, or 5.5%, from the previous month in what was also a second consecutive monthly increase. The September increase comes after producers started nominating price increases for monthly contracts as recently as in late August with Styrolution and Americas Styrenics seeking 3 cent/lb more for both PS grades and Total Petrochemicals announcing a 3 cent/lb increase on the GPPS but just 1 cent/lb on HIPS. As of Wednesday, producers and buyers have largely confirmed the 3 cent/lb increase on GPPS was implemented. As for the HIPS, some buyers confirmed it just went up 1 cent/lb. At least one of the producers who had been seeking a 3 cent/lb HIPS increase was not able to implement that increase to all of his market, sources said. “Eighty percent of the HIPS market is up 3 cent/lb and 20% just 1 cent/lb,” one source close to a producer who had sought 3 cent/lb for HIPS in September said. HIPS buyers contacted have reported seeing 1 cent/lb increase in September. Sources have said that HIPS pricing should not be as firms as the GPPS because of weakness in butadiene prices. Contract butadiene prices plunged on average by 30% from July to August. Butadiene is used to make polystyrene more flexible and resistance to impact, the product known as HIPS. The increase also comes at a time when there have been recent PS supply disruptions. Last week, Americas Styrenics called force majeure for PS production from its ?xml:namespace> In addition, Americas Styrenics is also expected to do a planned shutdown of on of three lines at its Due to the supply disruptions and low inventories, all the main North American PS producers, which include Americas Styrenics, Resirene in Some sources have said a relatively short-lived outage in After the increase US September PS contract prices as assessed by ICIS were at 100-102 for bulk GPPS
http://www.icis.com/Articles/2013/09/25/9709618/us-ps-sept-contract-prices-increase-on-feedstocks-tight-supply.html
CC-MAIN-2014-10
refinedweb
498
55.98
include a text file into a webpage Discussion in 'HTML' started by Hervé, Sep 29, 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 Include html text in a webpageGregor Traven, Oct 20, 2004, in forum: HTML - Replies: - 11 - Views: - 11,228 - Jeffrey Silverman - Oct 21, 2004 #include "file" -vs- #include <file>Victor Bazarov, Mar 5, 2005, in forum: C++ - Replies: - 4 - Views: - 657 - Exits Funnel - Mar 6, 2005 include file in include filePTM, Nov 12, 2007, in forum: HTML - Replies: - 1 - Views: - 394 - Andy Dingley - Nov 12, 2007 ASP Include file error <!-- #include file="" -->naveeddil, Jan 4, 2008, in forum: .NET - Replies: - 0 - Views: - 704 - naveeddil - Jan 4, 2008 /* #include <someyhing.h> */ => include it or do not include it?That is the question ....Andreas Bogenberger, Feb 21, 2008, in forum: C Programming - Replies: - 3 - Views: - 1,135 - Andreas Bogenberger - Feb 22, 2008
http://www.thecodingforums.com/threads/include-a-text-file-into-a-webpage.155075/
CC-MAIN-2015-32
refinedweb
181
79.19
Hi everyone! We have been looking at Prisma and Postgres databases in the past couple of articles. I will create a Next.js app that can post data to a Postgres database in this article. What we'll be building: - User signs in with Spotify - User loads their playlists from Spotify - User can sync one of the playlists to our Postgres database It will look like this: Setting up the starting point permalink I'm going to use the Spotify login example we made yesterday as the starting point for today's article. Download it from GitHub if you want to follow along. The first thing we need to do is add the Prisma dependencies to our application. npm i -D prisma npm i @prisma/client Then we need to initialize the Prisma client. npx prisma init This will generate the Prisma folder and add a database URL to our .env file. Open up the .env file and paste your Postgres database URL. Set up the database permalink The next thing we need to do is define a schema for our playlist. Open the prisma/schema.prisma file and add the following schema at the bottom. model Playlist { id Int @default(autoincrement()) @id title String image String? uri String @unique addedBy String } From here, we need to build our database. npx prisma db push As well as generate the local schema: npx prisma generate Creating an API endpoint to post our entity permalink We already have a playlists endpoint so let's leverage that one but modify it to accept POST requests. Open the pages/api/playlists.js file and start by importing the Prisma requirements. import {PrismaClient} from '@prisma/client'; const prisma = new PrismaClient(); Now let's modify the handler to do something on GET. const handler = async (req, res) => { const { token: {accessToken, email}, } = await getSession({req}); if (req.method === 'POST') { // Do post stuff } else if (req.method === 'GET') { const response = await getUsersPlaylists(accessToken); const {items} = await response.json(); return res.status(200).json({items}); } res.end(); }; As for the POST section, we want to extract the correct data from our post query and create a new object to send to our database. if (req.method === 'POST') { const {body} = req; const { name, images: {0: {url} = {}}, uri, } = JSON.parse(body); const playlistItem = { title: name, image: url, uri: uri, addedBy: email, }; } Then all we need to do is call our Prisma client and use the create function to insert our item. const playlist = await prisma.playlist.create({ data: playlistItem, }); return res.status(200).json(playlist); And that's it, if we now perform a POST request to this API endpoint, our playlist will be added. Creating the frontend action permalink Let's open up our index.js page for the front-end part. Inside the map function, add a button with a click action like so: { list.map((item) => ( <div key={item.id}> <h1>{item.name}</h1> <img src={item.images[0]?.url} <br /> <button onClick={() => saveToDatabase(item)}>Save in database</button> </div> )); } Now let's go ahead and make this saveToDatabase function. const saveToDatabase = async (item) => { const res = await fetch('api/playlists', { method: 'POST', body: JSON.stringify(item), }); const data = await res.json(); }; We are just passing the API request but not doing anything with the return data yet. This is perfect as once we click the button, it will call this function and post it to our API. Which in return adds a new entry in our database. You can also find the complete code on GitHub. Thank you for reading, and let's connect! permalink Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
https://daily-dev-tips.com/posts/nextjs-posting-data-to-postgres-through-prisma/
CC-MAIN-2022-21
refinedweb
617
75.5
Is there any JS smart json schema validator, like Joi maybe, but with dynamic custom errors? I want to easily validate user's input. When I ask the first name of the user (for example), it can take tons of lines of code in order to really make it good validated. I want something that I can use in front end and either in back end - without changing the validation structure. I need the ability to throw custom detailed errors, something like this: let schema = Joi.object.keys({ first_name: Joi.string("Required to be a string") .noNumbers("Should not contain numbers") .minlenth(2, "At least 2 chars") .maxlength(10, "Maximum 10 chars") .required("Required field"), last_name: Joi.string("Required to be a string") .noNumbers("Should not contain numbers") .minlenth(2, "At least 2 chars") .maxlength(10, "Maximum 10 chars") .required("Required field"), }); Unfortunately the above does not work - since Joi does not work like this. Maybe is there a good JSON schema validator to easily and efficiently validate the user's input without wasting time - and yet keep it clear for the user? 1 answer - answered 2018-10-17 08:32 Grégory NEUT You can use JOI. In the following example I'm overriding the errors directly : return Joi.object() .keys({ str: Joi.string() .min(2) .max(10) .required() .error(errors => errors.map((err) => { const customMessage = ({ 'string.min': 'override min', 'string.max': 'override max', })[err.type]; if (customMessage) err.message = customMessage; return err; })), }); I recommand you to use a function, considering the errors messages are going to be the same for all request : function customErrors(errors) { return errors.map((err) => { const customMessage = ({ 'string.min': 'override min', 'string.max': 'override max', })[err.type]; if (customMessage) err.message = customMessage; return err; }); } return Joi.object() .keys({ str: Joi.string() .min(2) .max(10) .required() .error(customErrors), }); EDIT : // This const customMessage = ({ 'string.min': 'override min', 'string.max': 'override max', })[err.type]; if (customMessage) err.message = customMessage; // Equals this let customMessage = false; if (err.type === 'string.min') customMessage = 'override min'; if (err.type === 'string.max') customMessage = 'override max'; if (customMessage) err.message = customMessage; // Equals this if (err.type === 'string.min') err.message = 'override min'; if (err.type === 'string.max') err.message = 'override max';. - Validate a field in an object is not null for a PUT request - SPRING I have a PUT request to update an object. I want to validate if a field in this object is not null. If it's null, then throw an exception. Controller @PutMapping public Institution updateUser(@Valid @RequestBody final User user, final UriComponentsBuilder uriComponentsBuilder) { if (StringUtils.isEmpty(userId)) { throw new ValidationException(); } return service.updateUser(user); } DTO public class User { @NotNull /* I am trying this but it's still allowing empty userId */ private String userId; private String name; private int age; } @Valid & @NotNull are not helping here or may be I am not using them correctly? I am trying to remove the StringUtils.isEmpty(userId)check from controller and looking for another solution using annotation. Any help please? I am using Spring-boot 2.1.0 & Java 11, if this helps. - Angular 6- Do my validations pose a security risk? I am building an application with Angular 6 and want to know if I should avoid certain front-end validations. The validations in question include receiving a list of users from our API/server, each with a key/value pair of "enabled": "true/false". If the value is true, we will display the user's information. If the value is false, we will raise an error saying the user is unauthorized. Is this something I should code into my Angular component? Or should this happen in the server before it even gets to the application? I thought that a user would be able to edit the source code via the browser developer tools and easily edit this check, to view information they shouldn't see. Is that true? Thank you! I can't seem to find direct information on this. Any information/resources would be much appreciated. - validate the IP address from the given list in Python I do see answers on the stackoverflow for validating the IPs from given string. I am trying to do the same. However, I have a LIST of IPs. I am stuck with the following code. Please help. I appreciate your time! def validateIP(self, IP): def is_IPv4(): i = 0 while i < len(IP): ls = IP[i].split('.') if len(ls)== 4 and all( g.isdigit() and (0 >= int(g) < 255) for g in ls): return True i += 1 return False def is_IPv6(): i = 0 while i < len(IP): ls = IP[i].split('.') if len(ls) == 8 and all(0 > len(g)< 4 and all( c in '0123456789abcdefABCDE' for c in g) for g in ls): return True i += 1 return False for item in IP: if '.' in item and is_IPv4(): return 'IPv4' if ':' in item and is_IPv6(): return 'IPv6' return 'Neither' print(validateIP('n', ['100.243.537.591', 'HBA.KJFH.LSHF', '172.16.254.1', '2001:0db8:85a3:0:0:8A2E:0370:7334', '256.256.256.256'])) - Reindexing Solr Data with different field type I am facing an issue while reindexing Solr data. I have indexed some documents specifying a wrong field type on the managed-schema file. Now, instead of the wrong field definition, I would like to use: <field name="documentDate" type="date" indexed="true" stored="true"/> To do this I have: - deleted all the previous wrong indexed documents; - updated the managed-schema - reloaded the core After these steps I tried to reindex documents, but this fails; looking at logs: org.apache.solr.common.SolrException: Exception writing document id 2ecde3eb2b5964b2c44362f752f7b90d to the index; possible analysis error: cannot change DocValues type from NUMERIC to SORTED_SET for field "documentDate". How is this possible? I have removed all the documents storing the field documentDate.. How can I solve this issue? - mySQL Join Multiple Tables (4) & Pivot edit 2 based on feedback: SQLFiddle This represents my schema (slightly reduced) with some sample data. The query gives me the output I want. When real data gets inserted and there are ~50,000 'Orbits' this causes ~18,000,000 of entries in tblmetricpoint and the query starts to take hundreds of seconds (Which seems like it is too long) I left the orginal post information below: I have the following query: Select concat(DeviceType, ' ', DeviceSerialNumber ) As DeviceName, LapCount, Round(LapTime, 3) AS LapTime , MAX(CASE WHEN MetricChannel = 'EnergyIncrementingCounter' AND MetricType = 6 AND SegmentNumber = 0 THEN MetricValue END) AS EnergyIncrementingCounter_Diff , MAX(CASE WHEN MetricChannel = 'EnergyIncrementingCounter' AND MetricType = 3 AND SegmentNumber = 0 THEN MetricValue END) AS EnergyIncrementingCounter_Max , MAX(CASE WHEN MetricChannel = 'ConditionOfTheTrack' AND MetricType = 1 AND SegmentNumber = 0 THEN MetricValue END) AS ConditionOfTheTrack_Ave , MAX(CASE WHEN MetricChannel = 'b_InPitLaneCrossed' AND MetricType = 3 AND SegmentNumber = 0 THEN MetricValue END) AS PitIn , MAX(CASE WHEN MetricChannel = 'b_OutPitLaneCrossed' AND MetricType = 3 AND SegmentNumber = 0 THEN MetricValue END) AS PitOut , MAX(Case WHEN MetricChannel = 'MotorEfficiency' AND MetricType = 1 AND SegmentNumber = 13 THEN MetricValue END) AS MotorEfficiency_p1_AVE , MAX(Case WHEN MetricChannel = 'MotorEfficiency2' AND MetricType = 1 AND SegmentNumber = 13 THEN MetricValue END) AS MotorEfficiency2_p1_AVE , MAX(Case WHEN MetricChannel = 'MotorEfficiency' AND MetricType = 1 AND SegmentNumber = 17 THEN MetricValue END) AS MotorEfficiency_p2_AVE , MAX(Case WHEN MetricChannel = 'MotorEfficiency2' AND MetricType = 1 AND SegmentNumber = 17 THEN MetricValue END) AS MotorEfficiency2_p2_AVE From tblLaps left join tblSectorsInLap on fk_LapPoint = id_tblLaps left join tblTrackSectorDefinition ON fk_SegmentEntry = tblSegmentDataID left join tblSectorMetrics on id_tblSectorsInLap = fk_segmentpoint WHERE tblLaps.eventid = 22 GROUP BY id_tblLaps HAVING min(EnergyIncrementingCounter_Diff) >= 0 AND LapTime > 30 This works reasonably well for eventid = 20 (which has a small amount of records in tblSectorMetrics). However, if I have a large amount of records, say 80,000,000 (in tblSectorMetrics). The query takes 11 seconds for the duration and 75 seconds for the Fetch (MySQL Workbench) when the limit is 2,000 records. If I don't limit the number of results I get ~70,000 records and it takes almost an hour, I then export the result set to a CSV which is ~10 MB. My Question is: Is there a better way I can structure my SQL query so that it doesn't take so long? My Other Question: Is there a better way to get the results (stored proc/view, etc)? My Third Question: Is there anything about the schema that I should look into changing? I don't have a strong background in SQL and I built the above query from several posts on this site, so I'm not sure if I missed something fundamental which would help me Table Explanations: tblLaps: 'id_tblLaps', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment' 'DeviceType', 'varchar(10)', 'NO', '', NULL, '' 'DeviceSerialNumber', 'varchar(10)', 'NO', '', NULL, '' 'LapCount', 'int(11)', 'NO', '', NULL, '' 'LapTime', 'double', 'NO', '', NULL, '' 'Driver', 'varchar(45)', 'YES', '', NULL, '' 'eventid', 'int(11)', 'NO', 'MUL', NULL, '' tblSectorsInLap: 'id_tblSectorsInLap', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment' 'fk_SegmentEntry', 'int(11)', 'NO', 'MUL', NULL, '' 'TimeSegmentStarted', 'datetime', 'YES', '', NULL, '' 'TrackCondition', 'int(11)', 'YES', '', NULL, '' 'fk_LapPoint', 'int(11)', 'NO', 'MUL', NULL, '' tblTrackSectorDefinition: 'id_tblTrackSectorDefinition', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment' 'EventID', 'int(11)', 'NO', 'MUL', NULL, '' 'StartDistance', 'double', 'NO', '', '0', '' 'EndDistance', 'double', 'NO', '', '0', '' 'SegmentName', 'varchar(45)', 'YES', '', 'Segment Name Goes Here', '' 'SegmentNumber', 'int(4)', 'YES', '', NULL, '' tblSectorMetrics: 'MetricType', 'int(11)', 'NO', 'MUL', NULL, '' 'MetricValue', 'double', 'YES', '', NULL, '' 'tblInstanceID', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment' 'MetricChannel', 'mediumtext', 'NO', '', NULL, '' 'fk_SegmentPoint', 'int(11)', 'NO', 'MUL', NULL, '' - Cannot parse AVRO schema in Golang I am having trouble parsing my AVRO json schema. I try to use the avro.ParseSchema function from this library:. However, i get the following error message: Unknown type name: array I've been trying to fix this for a long time but i cannot seem to make it right. I have the following strucs implemented: import ( "bytes" "log" avro "gopkg.in/avro.v0" ) type Matrix struct { UID int `avro:"uid"` Data [][]float64 `avro:"data"` } type MatrixContainer struct { MatricesArray []*Matrix `avro:"matrices_array"` } //Somewhere in here it goes wrong schema, err := avro.ParseSchema(`{ "type": "record", "name": "MatrixContainer", "fields": [ { "name": "matrices_array", "type": "array", "items": { "type": "record", "name": "Matrix", "fields": [ {"name": "uid","type":"int"}, {"name": "data","type":"array","items": {"type":"array","items":"double"} } ] } } ] }`) Any help would be greatly appreciated. - Joi throw error when a key value of object matches with other Validate a schema with objects, where one my key should not exactly match the key-values of other object. eg: const innerObject = Joi.object({ a: Joi.number().required(), b: Joi.number().required(), }); const outerSchema = Joi.object({ key1: innerObject.required(), key2: innerObject.required(), }); In the above outer schema, key1 one should not match exactly with inner object values of key2. - JOI - Validating complex object I tried, and tried but can't figure it :( This is the object I need to validate: let body = { greeting: { stringValue: 'Hello !', stringListValues: [], binaryListValues: [], dataType: 'String' }, newsletterId: { stringValue: '123456789', stringListValues: [], binaryListValues: [], dataType: 'String' } }; I need to validate that there is a greeting, and that is has key stringValue and that is not empty. Other values I don't care. Also, for the second object newsletterId, and that also has key stringValue and that is not empty. Other values I don't care. I have come up with checking only root object, with this schema: const schema = { greeting: Joi.required(), newsletterId: Joi.required() }; I read many examples, but I was unable to find none that has this type of structure. - Consistent error validation responses in Express http api, using mongoose and Joi I am pretty new to Node backend development, since I am coming from frontend. I am developing an http api using Express, Mongo, Mongoose and Joi for input validation. I am using both Mongoose and Joi schema validation, the latter just in particular cases, such as post/put/patch routes. Using an "unique" rule in Mongoose schema for email field I've stumbled upon the following issue: Mongoose error responses are quite a lot different from Joi ones. As you can imagine, consistent responses should be preferred to avoid complicated data parsing on the frontend to show errors in the UI. This is an example of Mongoose error response for unique email: { "errors": { "email": { "message": "Error, expected 'email' to be unique. Value: 'lorem.ipsum@yahoo.com'", "name": "ValidatorError", "properties": { "message": "Error, expected 'email' to be unique. Value: 'lorem.ipsum@yahoo.com'", "type": "unique", "path": "email", "value": "lorem.ipsum@yahoo.com" }, "kind": "unique", "path": "email", "value": "lorem.ipsum@yahoo.com" } }, "_message": "Author validation failed", "message": "Author validation failed: email: Error, expected 'email' to be unique. Value: 'lorem.ipsum@yahoo.com'", "name": "ValidationError" } while this is an example of Joi error response for wrong password: { "isJoi": true, "name": "ValidationError", "details": [ { "message": "\"password\" with value \"3\" fails to match the required pattern: /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,32}$/", "path": [ "password" ], "type": "string.regex.base", "context": { "pattern": {}, "value": "3", "key": "password", "label": "password" } } ], "_object": { "username": "thequickbrownfox", "first_name": "The Quick", "last_name": "Brown Fox", "email": "thequickbrownfox@hotmail.com", "password": "3" } } Please note that I am also using Mongoose Unique Validator to get Mongoose unique error messages instead of the default E11000 Mongo error which is quite speechless. Is there any way to get similar error responses in suchlike use cases? Thanks.
http://quabr.com/52849837/is-there-any-js-smart-json-schema-validator-like-joi-maybe-but-with-dynamic-cu
CC-MAIN-2019-09
refinedweb
2,176
56.15
For a better animation of the solution from NDSolve What is really curved, spacetime, or simply the coordinate lines? share|improve this answer edited Mar 8 '15 at 22:53 answered May 28 '13 at 17:49 Pierre-Luc Pineault 6,28862137 add a comment| up vote 0 down vote simple (i == null) ? num1 = 10; int? Jul 23, 2011 07:37 PM|pbromberg|LINK int? AND User = ? more hot questions question feed default about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback Technology Life / Arts Culture / Recreation Boggle board game solver in Python Why do I never get a mention at work? What is the total sum of the cardinalities of all subsets of a set? An explicit conversion exists (are you missing a cast?)" Reply pbromberg Contributor 2843 Points 526 Posts Re: "Cannot implicitly convert type 'int?' to 'int'. public int GetMaxsequence(int assessmentid) { return (from q in entities1.Questions join qa in entities1.Questions_Assessments on q.QuestionID equals qa.QuestionID where qa.AssessmentID??0 == assessmentid select q.SequenceOrder).Max(); } v2 = v1 ?? 0; share|improve this answer edited Sep 21 '12 at 3:51 answered May 13 '11 at 17:04 Arturo Martinez 2,4741131 add a comment| up vote 16 down vote Is it acceptable to ask an unknown professor outside my dept for help in a related field during his office hours? Hope it helps! Solutions? Default(int) is not the same size as an int. RaspberryPi serial port What is the simplest way to put some text at the beginning of a line and to put some text at the center of the same line? Cannot Convert Int To Int Array C# I have a user-created object whose fields get stored into a SQL Server database. Jul 26, 2011 10:27 PM|Decker Dong - MSFT|LINK Hello OP:) Show us your definination of your AssignmentId in your created model class, Plz. C# C# Programming Guide Nullable Types Nullable Types Using Nullable Types Using Nullable Types Using Nullable Types Using Nullable Types Boxing Nullable Types How to: Identify a Nullable Type How to: An explicit conversion exists (are you missing a cast?)" on my OrdersPerHour at the return line. Convert Nullable Type To Non-nullable C# An explicit conversion exists (are you missi... For example: C# Copy int? Ask a question Quick access Forums home Browse forums users FAQ Search related threads Remove From My Forums Answered by: Best way to convert a nullable type into its non-nullable equivalent? nullable type can contain three different values: true, false and null. C# Copy int? How To Convert Int To Int Array In C# Anyone know what it is? Convert String To Nullable Int All-Star 94110 Points 18123 Posts Re: "Cannot implicitly convert type 'int?' to 'int'. Eduard .: I love it when a plan comes together :. this contact form Jul 23, 2011 07:41 PM|johnjohn123123|LINK thanks for ur reply, but why "my method signatureshould allow a nullable type" Reply Nasser Malik Star 13030 Points 2654 Posts Re: "Cannot implicitly convert type It is set to true when the variable contains a non-null value.ValueValue is of the same type as the underlying type. v2= v1.GetValueOrDefault(); share|improve this answer answered Mar 4 at 18:15 thestar 1,1521218 add a comment| up vote 9 down vote GetValueOrDefault() retrieves the value of the object. Cannot Implicitly Convert Type Int To Int C# Phil Marked as answer by Faize Tuesday, November 23, 2010 7:49 PM Friday, November 19, 2010 6:20 PM 0 Sign in to vote I would just let the default value. As your AssessmentID is nullable type and you are comparing it with not null variable. d1 = 3.14; bool? Why cast an A-lister for Groot? Does every interesting photograph have a story to tell? Cannot Implicitly Convert Type 'int' To 'int ' Array BR Reply Decker Dong... Because calling .Value on a nullable type that's null will throw a 'Nullable object must have a value' exception, so you need to guard against that anyway. i = 10; double? If it is null, it returns the default value of int , which is 0. I have a user-created object whose fields get stored into a SQL Server database. C# Convert Int Array To Nullable Int Array Member 474 Points 2431 Posts Re: "Cannot implicitly convert type 'int?' to 'int'. Console.WriteLine("num1 == num2 returns true when the value of each is null"); } /* Output: * num1 >= num2 returned false (but num1 < num2 also is false) * num1 < Were the Smurfs the first to smurf their smurfs? An explicit conversion exists (are you missi... Check This Out Jul 23, 2011 09:46 PM|Prashant Kumar|LINK int? Considering it that you have the err msg——Cannot implicitly convert type 'int?' to If you assign this to another variable of type int (either explicitly or implicitly), the compiler will generate the error that you are getting. If you're assigning a nullable type to a non-nullable type, you should be sure that the value isn't actually null. default(int); Any Nullable int m2 = (int)n; // Compiles, but will create an exception if n is null. What now? My manager said I spend too much time on Stack Exchange. Jul 27, 2011 05:20 PM|johnjohn123123|LINK it worked fine , but if i query the date and there are no questions that mathes the search critiria , then an exception will be Jul 28, 2011 01:12 PM|Cathy Mi - MSFT|LINK Hi, Then use my first suggestion instead of the second one. Member 474 Points 2431 Posts Re: "Cannot implicitly convert type 'int?' to 'int'. asked 5 years ago viewed 155662 times active 7 months ago Linked -2 ASP.NET MVC Create method null int -3 In .NET how do I convert a nullable int to a
http://hiflytech.com/int-to/cannot-convert-nullable-int-to-int.html
CC-MAIN-2018-09
refinedweb
982
63.59
Details - Type: Bug - Status: Closed - Priority: Not Evaluated - Resolution: Cannot Reproduce - Affects Version/s: 5.15.2 - Fix Version/s: None - Component/s: Build tools: moc - Labels:None - Platform/s: Description This was raised as and closed as duplicate of issue supposedly solved. It was not solved and still exists as of Qt 5.15.2. This happnes for TBB library versions 2020 and higher (up to current 2021). It happens when Intel Thread Building Blocks (TBB) library is used within ang QT C++ source file processed by moc. So reproduction steps - add #include <tbb/tbb.h> into any C++ QT source file (i.e. the one processed by moc). The reason for this is because TBB defines tbb::detail::dl:event structure with methods named emit() and this is what causing the issue.
https://bugreports.qt.io/browse/QTBUG-89081?gerritIssueType=IssueOnly
CC-MAIN-2021-43
refinedweb
134
66.54
Vol. 4- Issue 50 The Lynn Theatre Cannon The Gonzales Reporting regional news with Honesty, Integrity and Fairness Lavaca Co. ploded about 7 p.m. Wednesday in Petersville off state Highway 111. (The well) has been safely secured, and the fire is out, K. Leonard, a spokeswoman with Enron Oil and Gas (EOG) Resources Inc., **75 Cents** Sept. 6-12 The Butler - PG-13 Fri.: 7:15; Sat.: 4:15, 7:15; Sun.: 4:15, 7:15; Mon., Wed., Thurs. 7:15 Sc. 1: CLOSED TUESDAYS YOAKUM Workers have now capped the oil well which blew out Aug. 28, causing an explosion and fire which raged for several days. The Nabors Industries oil rig ex- which operated the rig, said Tuesday in a news release via e-mail. The explosion will be investigated by the Texas Railroad Commission and the federal Department of Labors Occupational Safety and Health Administration. The OSHA investigation could take up to six months. Shortly after the explosion, EOG released a statement about the incident and reported that all workers were uninjured and accounted for. EOGs first priority in responding to this incident is the safety of personnel working on site, the responders who are providing asFIRE, Page A5 Kick Ass 2 - R Fri.: 7:00, 9:30; Sat.: 4:00, 7:00, 9:30; Sun.: 4:00, 7:00; Mon., Wed., Thurs. 7:00 Tickets: Adults $7.00 Children (12 & under) $5.00 4:00 Matinee $5.00 everyone Sc. 2: Experts Our annual fall feature, the Beat the Experts football contest, continues in this weeks edition. See Page B10 to enter! Beat The Area residents were quick to respond with pictures and information following the explosion of the Nabors Industries/EOG rig in far southwest Lavaca County Aug. 28. At left, resident Cheryl Michalec furnished a shot of the fire about an hour after it happened. Tray Rankin (center) said he could see this from my back porch. The fire continued to burn through the weekend, as the photo at right from The Cannons Dave Mundy attests. Earl Parker experienced The regional explorathe horrors of Omaha tion for natural resources Beach and survived to continues to reap financial see ultimate victory. See benefits locally. Page A3. Dynamic Industries, Inc. announced the acquisition of property in town on Thursday. The company is part of Dynamic Energy Services International LLC, a leading fabrication and service provider to the global oil, gas and energy industries. Gonzales Dynamic Industries bought the three remaining lots in the Gonzales Industrial Park, about eight acres in total, and will soon start construction on a new campus. The property will be developed in two phases. Phase One is construction of a 12,000 square-foot facility on one and a half stabilized acres that will house a state of the art electrical DYNAMIC, Page A5 Dynamic Industries, a global player in the energy industry, will be building a new campus on Commerce Court in Gonzales Industrial Park. Pictured with the newly-erected sign announcing their coming is Vicky Helm, Dynamics business developer in shale plays. (Photo by Cedric Iglehart) Theres a lot of activity in downtown Gonzales these days new businesses are sprouting. See Page A12. Community...................... A2 Livestock Markets.......... A7 Oil & Gas........................... A8 Classifieds.......................... B6 Comics............................. B14 For the Record.............. A9 Faith.................................... A11 In Our View........................A4 Family............................... A10 Region.............................. A3 Puzzle Page.................... B13 Go Apaches! .................. C1 Sports.................................. B1 Obituaries....................... A5 Education....................... A10 St. Patrick Catholic Church in Waelder staged Fiesta Guacamole XXXVI over the Labor Day weekend and the highlight was the annual parade. Despite 100-degree heat, scores of onlookers lined the street in front of Waelder City Park to take in the pageantry. (Photos by Cedric Iglehart) Become a subscriber today! Annual subscriptions are just $25 per year. Call 830-672-7100. Weather Watch THU FRI SAT SUN MON TUE WED 830-672-8585 Page A2 Community Calendar The Cannon the office at least two days prior to the event so accommodations can be arranged. For more information or to pre-register for the event contact the Guadalupe County Extension office at 210 E. Live Oak in Seguin, 830-303-3889. The Moulton High School Reunion for all classes will be held on October 19, 2013 at the KC Hall in Moulton. Registration and visiting will begin at 2 p.m. Dinner will begin at 5:30 p.m. followed by a short meeting. A dance will follow from 7 p.m. until 11 p.m. with music by the Red Ravens. A fee of $12.50 per person includes a catered meal and dance. The classes of 1961, 1962 and 1963 will be honored as they have or are celebrating their 50th anniversary since the last reunion. Graduating classes through the class of 1976 will receive written invitations in midAugust--but the reunion is for anyone and everyone who ever attended Moulton High School. Those who need to provide a new address or those not identified to receive a written invitation or need more infotmation should contact Dennis Ellinghausen (361-596-7721) or e-mail ellinghausen@att.net or Tony Janak Gardening Classes There will be a Walk Class/Leslie Sansone DVD offered at First United Methodist Church at 2 p.m. Monday through Thursday, conducted by Wesley Nurse Shirley Goss, RN. The class is free to the public There will be a Flex & Tone Exercise Class offered at First United Methodist Church at 11 a.m. Tuesdays and Thursdays. The class is conducted by Wesley Nurse Shirley Goss, RN and is free to the public. New this semester at Christian Womens Job Corps will be Freedom classes: Mondays 8:3010:30 beginning Monday, September 9, led by Julie Winton. Also scheduled will be a Womens Bible study, From Dream to Destiny by Robert Morris, Tuesday mornings 10 - 11:30, Tuesday afternoon 1:30-3 p.m. led by Sherry Poe and Irene Rinehart For details, call Sherry Poe at 830-857-4960 or come by 721 St. Louis - The Bethany House. The Briefcase this month will feature Gwen Hodges presenting the program, Then Sings My Soul...Stories Behind Some of Our Most Beloved Hymns, from 12:05-12:55 p.m. at the Fellowship Hall at First Baptist Church-Gonzales. There will be a salad luncheon of chicken and ham salad, pimento cheese, crackers and drinks. Childcare is available on request, contact the church at 672-9595. Walk class Flex-Tone class The Thomas Shelton Chapter of the Daughters of the American Revolution will hold a Constitution Week Luncheon on Saturday, September 21. The luncheon will begin on noon and be held in the Fellowship Hall of the First Methodist Church. The Small Business Development Center has announced the following upcoming event: Empower Your Marketing, Sept. 11, 10 a.m. - noon, 1614 N. Texana St., Hallettsville, TX 77964-4580 This free seminar may be cancelled if minimum number of registrants is not met. Satisfactory meeting room temperatures are difficult to maintain. Always bring a sweater or jacket to ensure comfort. The Texas AgriLife Extension Service will host a Fall Weed and Brush Workshop on Friday September 13 at the Luling Foundation Farm located at 523 South Mulberry Street in Luling from 9 a.m. until noon. Registration will begin at 8:30 a.m. Three TDA CEUs will be offered to pesticide applicators. Topics to be covered at the program will include Brush Management, Broad Leaf Weed Management, Planning for next year, and Plant Identification. Participants will also get to view broad leaf herbicide trials that are established at the farm. Please pre-register with the Guadalupe County Extension Office by Wednesday September 11th at 830-303-3889 to ensure an accurate count of handouts. Registration is $10. Individuals with disabilities should contact Moulton Reunion SBDC seminar CWJC classes Vietnam Veterans AgriLife Workshop The Briefcase DAR Luncheon Fresh Flowers Plants Gift Items Wreaths Snack Baskets Burlap Designs Homecoming Mums Wedding Work Sympathy We want you and your family to stay healthy! Get your flu shot conveniently, without ever leaving your vehicle. Drive in, roll down your window, roll up your sleeve and drive out...its that easy! Date: Wednesday, September 18, 2013 Time: 7:00am-7:00pm Place: Gonzales Healthcare Systems Parking Lot Sarah DeWitt Drive Gonzales, TX Cost: $25.00 - cash/check/credit card accepted Medicare will be accepted with cards presented at time of service Must be 4 years old and older to receive drive-thru vaccination. Other restrictions may apply All participants will be registered to win a three month membership at James C. Price Wellness Center! For more information contact Mary Jane Williamson at 830.672.7581, ext. 216. (830) 519-4374 Registration to join the Independence Trails Girl Scouts for the 2013-2014 will be held September 5, from 5:30-7:30 p.m. at Lions Park in Gonzales. Registration fee is $15. Register and participate in various activities and see a little of what is in store for the girls this year. The Girl Scouts have a tradition of 100 years of helping girls ages 5-17 in grades K-12 realize their full potential and become self-confident, strong and compassionate. To learn more, visit.. A Hunters Safety & Education Course will be conducted on Saturday, September 14 at 3 p.m. at 5631 US 183 North in Gonzales. Participants will have to register online to complete the classroom portion of the training prior to the field training on September 14. You must have completed the online training and bring documentation of completion to the field training. For registration and other details, please contact Wayne Spahn at 830-672-3720 or Ray Raley, Jr. at 830-857-3853. 1. Any business can enter. 2. Fill out an entry form as attached. Or..... 3. Call Main Street at 672-2815 4. Fall Decorations can be anything you come up with. Use your imagination! 5. Judging will be held on October 2, 2013. First, Second, and Third place winners will be announced. 6. This event is sponsored by the Gonzales Main Street Have your display up by September 30, 2013 Name:____________________________________ Address:__________________________________ Contact Person:_____________________________ Phone #:___________________________________ Email Address:______________________________ Form Information call: 672-2815 Send Completed Form to: Gonzales Main Street P.O. Box 547 Gonzales, Texas 78629 Remember display deadline is September 30, 2013 Contest Rules Judging Information Rummage-Bake Sale Hunter safety The Cannon Page A3 Lockout Services includes Light, Medium and Heavy Duty Towing and Service Calls, Light, Medium and Heavy Duty Mechanic DOT & State Inspections From the horror of Omaha Beach to final victory: the Earl Parker story Earl Parker was born in Frankfort, KY., 89 years ago, the son of a retail dairyman. During high school (1942) he tried to join the Marines, but failed the vision test. Disappointed, he entered Eastern Kentucky University for a degree in physical education and then the Army called. Drafted in March 1943, he endured 13 weeks of basic training (infantry) in Georgia, and in November shipped out for England. There he became 1st Infantry Division, the Big Red Oneand trained to invade France during Operation Overlord. As a machine gun team member, he practiced intensely all over England until June 1944. The weather on June 5th Lew McCreary Lew McCreary is a resident of the Conroe area who also owns land in Lavaca and Gonzales counties. He is compiling the stories of our honored veterans from throughout the region, especially those of the World War II era. If youd like to see the story of your honored veteran featured, contact him at lrmmccreary@consolidated.net was bad, so they launched on the 6th when it was worse. PFC Earls vessel, an LCVP carrying 30 G.I.s, was deployed nine miles off Omaha Beach, then pressed on under power. The enemy was mightily prepared. Soon their coxswain (skipper) was hit by shrapnel, dropping the off ramp, still in deep water. All G.I.s carried heavy packs and sunk like stones. Earl finally disengaged all gear (except his side arm) and surfaced, then swam to an invasion obstacle topped with a land mine. It could blow any second so he left. Some statisticians had predicted 50-percent casualties on the landing and Earls best friend did not make it. Weapons lay everywhere ashore, so Earl snatched a carbine until finding a machine gun. They topped the first hill and captured a pillbox. Omaha Beach was so grim that General Eisenhower considered withdrawal, but did not. From the start, Earl was aware of the enemys ATASCOSA Chrysler, Dodge, Jeep, Yamaha 2014 Jeep Wrangler Allways superior fire power, nevertheless they must push on into the hedgerows of Normandy. Here the dug in Germans clearly had the advantage, and the Yanks paid dearly for every inch gained. The cost in lives was prohibitive, so something had to be done. Finally General Bradleys bold plan to carpet bomb an entire section of German line was executed. This incessant, powerful bombardment created the necessary break out through Hitlers western wall. Now the allies opportunity to fight in open country and overcome was possible. The long, dangerous offensive through France, Belgium and Germany was a constant series of foxholes, attacks, repelling counter attacks and more foxholes. The fearful German 88s (artillery) were a nightmare. Its concussion alone could toss a G.I. around, cover him with dirt and bloody his nose. C rations often ran short so occasional captured German stores sustained them. Much later, the Yanks got a three day rest. One of the most intense struggles was for Aachen. The battle for this first German city was horrificand both sides struggled desperately to prevail. In the Huertken Forrest, some shrapnel caught Earls left arm, hospitalizing him in Belgium. Soon thereafter he was flown to Wales for recuperation. When released he became clerk typist, serving in Versailles, Reims, and finally Frankfort (Gr.)...Eisenhowers SHAEF headquarters until May of 1945. In Reims, France, he observed the German high command goose step in, then surrender. Back in Kentucky, Earl reconnected with college for his masters and started his doctorate. After three years of teaching/coaching in Louisville, he bonded with The Tenneco Company, richly diversified in chemicals, pipelines, agriculture and energy. Although starting as skilled labor in pipelines, he rapidly took on significant new responsibility in upper management, and that brought him to Houston. Once he settled in comfortably, he and his wife Earl Parker Marilyn searched for country property, and purchased acreage near Shiner. They moved into these new digs during 1986 for good. An organization man, Earl joined civic organizations and busied himself with Brahma cattle and making hay. Asked why the G.I.s prevailed in Europe, Earl responded like this: It was allied air superiority starting at Normandy, interdiction of enemy fuel supplies and transportation, untrammeled U.S. manufacturing capabilityand finally the American spirit. The German army was so rigidly structured that if leadership was a casualty, sometimes the troops were immobilized. On the other hand, by Gods grace that generation of GIs was often motivated and innovative enough to gain the victory through their own ingenuity. Tea Party and Texas Nationalist members from throughout central Texas gathered in Marble Falls Monday for the Labor Day Freedom Fest. Keynote speaker Claver KamauImani of ragingelephants.org used Biblical references to justify Texas moving toward independence, while Gonzales Dave Mundy (below left) was among a number of state candidates out stumping for support. He is running for the State Board of Education, District 3, seat. The host of the event, Highland Lakes Tea Party president Diana Moses (below right) had a message for the Internal Revenue Service. Larry Harlan 110128 IH 37 Pleasanton, TX 78064 Sales Consultant Page A4 In Our View The Cannon Dave Mundy General Manager Its a geographical thing. The mountains of Central Texas remind them of the Sierra Madre. They think theyre still on the Left Coast. When God designed Texas, he made Austin for them, because He gave the rest of us nice, logical, relatively flat terrain. Obviously He knew we would need a place to store our crazies, so He created Austin. The area around and north of Austin is known as the Hill Country, but as far as Im concerned, it really should be called the Mid-Texas Mountain range. A time for love, a time for hate, a time for peace, I swear its not too late. The Byrds, Turn! Turn! Turn! Those arent hills. Hills, you see, are like highway overpasses. Here in Gonzales, for example, we have The Hill a nice, gentle slope. That stuff in and around Austin: thats mountains. I know, because Ive driven through the Rockies and the Appalachians, white-knuckled the whole time, and thats the same feeling I got driving along Highway 281 from Austin to Marble Falls and back Monday. I hate driving in mountains. When youre driving on hills, youre in no danger of falling off. When youre driving in the mountains, you never know when youre going to top the crest of a peak and see nothing but an oncoming guardrail and empty space in front of you before you plunge thousands of feet to a horrific death in the river far, far below. I am not, by nature, acrophobic. When I first joined the Marine Corps, they made me a telephone cable splicer, so I played volleyball on top of tall poles. I have no fear of flying, although Im probably on the no-fly list these days. (Admittedly, Im not real fond of helicopters, but I know most chopper pilots do not lay their birds on their sides while making a turn, giving the ground-pounders theyre carrying a wonderful view of Onslow Beach, N.C., through the open doorway of the CH-53. That was NOT funny, Sir.) On the other hand, I cannot admire photos of the Grand Canyon without getting vertigo, or step near the full-length windows of a tall office building because I just know someone is going to shove me through. That explains a lot about the transplanted San Franciscans currently inhabiting Austin: theyve spent their entire lives about to fall off the mountain and its driven them nuts. Those of us who live in the saner, flatter precincts of Texas, on the other hand, dont have to worry about falling off the highway and can thus turn our thoughts to deeper things, such as raising food and families in sane fashion, how to get that oil from underneath us to energize our economy, and how to convince the San Franciscans to stop trying to turn our state capital into another of their utopian communes. Admittedly, some sane people do choose to live in the mountains of Central Texas; after all, the event I attended Monday was hosted by the Highland Lakes Tea Party. How those folks manage to retain their sanity while not falling off the mountains, Ill never know. But the rest of us, Im sure, are content to let the Central Texas Mountain Range be the reservation where we keep our most crazed liberals. Only problem is, some of them have gotten off the reservation and escaped to San Antonio. It was in the springtime when an uncle took me away. From school. So I became a victim of abuse. By a government. Ours. What happened. Was this. It was the spring semester of 19 and 68. And I was enrolled at North Texas State University. For those unfamiliar with Texas geography, North Texas State is located in North Texas. Anyshucks, a few days before my 24th birthday, which falls on April 19, I received a greetings from my Uncle Sam. Informing me to report for a physical. Back then, when I was young, Id work a spell and then go to school for a semester or two. Prior to attempting to become learned at NTSU this depleted mind and I had received academic transcripts from Texas Tech, Sam Houston State, Temple Junior College, San Antonio College, along with having been previously enrolled at NTSU in the fall of 63. Well, in the spring of 68 I was majoring in architecture, with a minor in journalism, at the time and working part-time over in Dallas at the Goodyear retread plant. So my Pappy went to the draft board located in the county seat, Marlin, and told em that his only boy was studying at the time and could he be excused from the physical until late May when the semester was over. The plea fell on a deaf ear. The Selective Service System said a fella going on 24 years old shouldve finished his education by then. And that he no longer deserved a II-S (student) deferment. Scratch Pad Jim Cunningham is a former longtime Gonzales newsman and the former interim publisher of the Gonzales Cannon. He now lives in the Moulton area. On Thursday, August 29, fast food workers in many American cities launched a strike for higher wages. They are supported by the liberal Service Employees International Union (SEIU). In typical liberal fashion, the SEIU is deceiving employees with half truths while ignoring the realities of life and America. Most people feel everyone is equal and everyone should be paid equally. They are quick to accept the idea that all people should have a living wage and dignity at work. Those assumptions are great ideas. However, in real life we are not created equal except before the law. Some people are short, others tall. Some are heavy (can I say fat anymore?), some are thin. Some are old, and some are young. Some are educated and trained, others not. Some are motivated and other not so much. Also, our lives are influenced by the choices we make. Bad choices and deci- So I was ordered to report to Marlin on a day at the tail end of April to take a bus ride up to Dallas for the physical. Well, Denton, home of NTSU, as I noted is up in North Texas and just a beer and half drive from Dallas. So I reasoned I could just show up at the induction center and forego the trip to Marlin. Wrong. The draft board and I didnt coincide on the logistical reasoning. Now at NTSU the west coast and east coast ideology of protesting this (Vietnam) and that (conscription-draft) had yet to infiltrate the thinking of the clean-cut students. The radicalism and hippiedom would come later. As the 60s would blemish Americas image. And the turbulent 60s reached an unraveling in 1968. Event after event whorled out of control. North Korea seized the Pueblo, a U.S. Navy ship in January and held 83 on board as spies and in January-February the North Vietnamese launched a TET offensive, a crucial turning part in the Vietnam War. In March, American GIs massacred 347 civil- ians at My Lai in that strange little country called Vietnam. And Czechoslovakia was invaded by Russians in August. It was a year that became more and more volatile. Stateside, an angry and violent America endured. In a matter of months, two assassinations occured as Martin Luther King was slain in Memphis on April 4 and presidential candidate Robert F. Kennedy was shot in Los Angeles on June 5. He died the next day. President Lyndon Johnson announced in March he would not run for another term. So the stage was set for more unrest at the Democratic Convention in Chicago as antiwar protesters converged on the windy city to get the donkey-doers to soften their stance on Vietnam. The riots of 1968 took 40 lives and only a calculator could come up with a ballpark figure on the property damage that was done. Martial Law was declared in Chicago and Baltimore. The Democrats became known as a party of disorder as the GOPs Richard Nixon and his Silent Majority in favor of the Vietnam War saw Nixon, while winning only 43.4 percent of the popular vote, cruise to a landslide win with the electoral vote. And then there was this lean fella that had became too old in 1968 to be considered a cool Joe College. So I took a drive to Marlin and boarded a bus to retrace the route I had just travelled. Despite having endured a head injury and having lapsed into a coma from a car wreck in 59. And having suffered through a major leg operation due to a football mishap. And being afflicted with asthma. Despite all that, I was de- clared One-A. Fit for duty. Textbooks and lectures in buildings situated in a pastoral setting gave way to the lovely landscape of Fort Polk (Tigerland), La. in the heat of the summer. Where friendly drill sergeants cared about my well-being 24-7. Myself and the other recruits of Company D were coached in the fine art of latrine duty and KP and the joy of cleaning out a grease trap. We were instructed in the balance of the front-leanand-rest position, along with the maintenance of an M-14 rifle. Policing an area was of high priority along with field striping a cigarette butt. Bivouacs were camping trips and hikes to the shooting range and classes on how to treat a gaping belly wound occupied a portion of our time during the eight and a half weeks of training. Basically, basic was a time in our lives of learning how to die. Then it was off to Fort Monmouth, N.J. for Advanced Individual Training. My MOS was 84B20 Still Photography. And the winter of 68 was a simple time. Shooting on film was much more creative than popping off rounds at popup targets. However, in March of 1969, with 1968 only a fading shadow dancer, I landed in Vietnam. Where with a .44 sidearm and a .30 carbine and several Canon cameras Id be shooting em up for longer than I care to remember. But at the oddest of times I oft-times do. Remember down the road. The 60s arent over yet, not until the fat lady gets high. Ken Kesey George Rodriguez is a San Antonio resident. He is the former President of the San Antonio Tea Party, and is now Executive Director of the South Texas Political Alliance. sions lead in one direction, and good ones in another. Such is life. In America, people usually ended up in a given socio-economic status because of their choices in life, not because some Supreme Power dictated it. Tomorrow, the rich can become poor and the poor rich if they make the right choices. Third, Americas society and economy is not static and rigid where a person is 2013 The Cannon Page A5 Obituaries sistance and neighbors in the immediate area, Leonard said. The company is coordinating its response with local fire department and emergency response personnel. EOG has also notified appropriate regulatory agencies. In addition, Wild Well Control has been contracted to assist in the response effort. EOG is assembling well control experts and specialized equipment to safely control the well and extinguish the fire, Leonard said. The companys priorities remain constant: protect the safety of those responding to the incident, neighbors in the area and the environment. Leonard added that It is too early to determine the cause of the incident. Two readers from the area, Cerena MiDayna is one of several calico kittens available at a chalec and Tray Rankin, supplied pictures of discounted adoption rate at the Friends of Gonzales Animal Shelter (FOGAS) throughout the month of September. (Photo courtesy of FOGAS) Animal Shelter or check out mention the word calico. their website can always stop by Because the council cats.webs.com or- FOGAS, located at 505 St. By CEDRIC IGLEHART finder.com by entering the Francis Street in downtown newseditor@gonzalescannon.com chose the effective rate, no WAELDER The public hearing will be rezip code 78629, or call the Gonzales, and let one of the Waelder City Council quired for adoption. The shelter at 830-857-1616 and calico cuties pick you out. agreed on a new tax rate council set a date of Sept. for the city during its 17 for formal adoption of regular meeting Tuesday the rate during a special called meeting at 7 p.m. night. In another agenda item, The council, who proand her husband, Gilbert of worked for Dr. Willis and ceeded without the pres- the council authorized the Gonzales. T.D. Crews as a hospital and ence of Robert Tovar and city attorney to create a She is preceded in death clinic nurse. She also served Peggy Blackmon, unani- resolution for abandonmously approved a mo- ment of a 20-foot wide by her parents, Ruben and as school nurse for GISD. Mary Ramos, two uncles; Isabel was a longtime tion to accept the effective alley out of an 0.08-acre Tony Ramos and Joe Ra- member of St. James Catho- rate of $0.2226 per $100 of Block 45 for the purmos. lic Church where she as- valuation as recommend- pose of transferring the The family request me- sisted with many parish ed by the Gonzales Coun- propery to a new Family morials to: American Can- activities. She was an active ty Tax Assessor-Collector. Dollar. The store will be cer Society / 8115 Datapoint member of the Catholic That rate is lower than last located on Highway 90A, near the intersection of Dr./ San Antonio, Texas Daughters and Beta Sigma years rate of $0.2231. 78229. To join the family in celebrating Bernices life, please go to Phi Sorority. She was also an avid bowler. Isabel was preceded in death by her parents, husband, Sterling E. Kelley; daughter, Tracey Kelley; sisters, Mildred Moore and Maxine Albricht. She is survived by sons, Sterling Kelley, Jr and wife Patsy, David Bradfield Kelley and wife Kerry; daughter, Laurie Kelley Taylor and husband Steve; sisters, Verna Mae Lyon and Imogene Jeanie Stoeltje; and special friend, Walter Ulbrich. She is also survived by three grandchildren, Sterling Kelley III, Brandon Kelley, and Zach Taylor; and great grandchildren, Logan and Isabella Kelley. She is remembered by her family as a very wise, loving, and generous mother. The family is grateful to her caregivers at the The Heights Nursing & Rehab Center and The Romberg House, especially Aida Olalde. Visitation was held on Friday, August 30 at Seydler Hill Funeral Home with recitation of the Rosary following. The funeral mass was celebrated on Saturday, August 31 at St. James Catholic Church with interment in St. James Catholic Cemetery. In lieu of flowers, please consider making a donation to St. James Catholic Church or St. James Daughters Society. the scene to The Cannon from some distance away. The fire continued to burn through the weekend. Several readers contacted The Cannon with unofficial information theyd received from neighbors and witnesses indicating workers on the rig had become concerned after hearing an underground explosion prior to the eruption of fire on the surface. First responders, including fire departments from Yoakum and Shiner were still on the scene at dusk on Wednesday. In addition to the rig and equipment onscene, one trucking company which had vehicles at the site reported two of its 18-wheelers were also destroyed. Two houses located within a quarter-mile of the site were initially evacuated, but residents were able to return to their homes within hours. Avenue B. In other business, the council: Re-appointed Rocky Quintero Jr. and Mike Harris to the Golden Crescent Regional Planning Commission for the General Assembly and Board of Directors. Tabled action on building a fence around the Waelder City Kiddie Park. Accepted the resignation of Jessica Canales as Municipal Clerk and announced they would advertise the position and accept applications through Sept. 17. Bernarda Bernice Camarillo, 1969-2013 Bernarda Bernice Camarillo, 44, of Gonzales, Texas passed away Wednesday, August 21, 2013 at her residence in Gonzales, Texas. Funeral Services is under the direction of Buffington Funeral Home in Gonzales, Texas and will be held at 1:00 P.M. on Saturday, September 7, 2013 at St. James Catholic Church in Gonzales, Texas with Father Paul Raaz officiating. A Memorial Service will follow at Gonzales Municipal Park Cemetery. Bernice was born May 18, 1969 in Cuero, Texas. She was the daughter of Ruben and Mary Ramos. She married Benito Camarillo in Gonzales, Texas on December 24, 2009. Bernice enjoyed cooking, listening to music, and dancing. She enjoyed drinking her beer and had a good sense of humor. She was known as being a caretaker and taking in friends when they needed her. She is survived by her husband, Benito, a son; Brandon Ramos Gonzales, two daughters; Brianna Ramos, Brandie Ramos; two sisters; Irene Ramos of Gonzales, Texas, Alethia Casares CAMARILLO Isabel Kelley, 1924-2013 Isabel Marie Orts Kelley, beloved mother, died peacefully at Gonzales Memorial Hospital. Isabel was born to August & Annie (Oehler) Orts in Poth on Feb. 15, 1924, one of 5 girls. She attended Poth Schools, was senior class salutatorian, and a volleyball & tennis athlete. After graduation she attended Santa Rosa School of Nursing and became a Registered Nurse. She accepted a job at Crews Hospital in Gonzales. Shortly after coming to Gonzales she met and married Sterling E. Kelley and they had four children. Isabel was the Director of Nurses for many years at Crews Hospital. She KELLEY panel shop and administrative staff for the Technical Division. We plan on breaking ground in about a month and hope to complete construction by the beginning of next year, said construction manager Peter Reeves. We will also be putting in a street from the cul-de-sac in Commerce Court over to Harwood Road. Phase Two is going to encompass the property to the north on two and a half acres, where a 10,000 square-foot light fabrication facility will be erected for the companys Mechanical Division. Im not exactly sure when were going to start work on Phase Two, but it will probably overlap Phase One, Reeves said. The Gonzales location will join the companys location in Carrizo Springs in hopes of further enhancing Dynamic Industries as a premier player in the Eagle Ford Shale. The location of the city is considered ideal by the company because of its position in relation to the Eagle Ford Shale and the newly-active Eaglebine Shale. The Eagle- bine is the confluence of the Eagle Ford and the Woodbine Sandstone, which was famously drilled in the 1930s during the discovery of the giant East Texas Field. Activity in the Eaglebine is being concentrated primarily in Brazos, Grimes, Madison and Walker counties. Based on our research, Gonzales happens to be a the conjunction of the Eagle Ford shale to the south and the west, said Vicky Helm of Dynamics business development of shale plays. As the developing Eaglebine shale continues moving east and north, we found Gonzales to be the perfect location for us to service all of our clients within a two-hour window from here. We are so happy with the amount of support we have gotten from the City of Gonzales and the Gonzales Economic Development Corporation in helping us with the relocation and acquiring of the property, said Reeves. Its been like a breath of fresh air. Weve never received a welcoming like the one weve gotten from Gonzales. The move will lead to the creation of several new jobs in town. Over the course of a year, Dynamics Carrizo location grew from a team of five to over 150 and Helm said she expects the same pattern of growth in Gonzales. Dynamic Industries, Inc. offers a full range of services including site development, I&E, automation, control panels, fire & safety and H2S services. 2138 Water Street/Hwy. 183, Gonzales, Texas 78629 Phone 830.672.1888 ~ Fax 830.672.1884 Freedom classes: Mondays 8:30-10:30 beginning Monday, September 9, led by Julie Winton Women's Bible study, "From Dream to Destiny" by Robert Morris, Tuesday mornings 10:00 - 11:30, Tuesday afternoon 1:30-3:00 led by Sherry Poe and Irene Rinehart (Limited class space) Call Sherry Poe @830-857-4960 or come by 721 St. Louis The Bethany House Page A6 The Cannon 830-672-3057 or 830-857-4006 Plumbing Residential & Commercial A-8953 SEa monStErS 2-d (PG) mortal inStrumEntS (PG-13) tHE ButlEr (PG-13) 1:45, 4:30, 7:00, 9:25 7:00, 9:30 1:00, 3:10 AAcontracting@stx.rr.com wwalker@gvec.net Fri., Sept. 6 thru Thurs., Sept. 12 all Shows $5.00 Before 6:00 Adult $7.50 Child & Senior $5.50 Open Daily @ 12:45 ROCKING CHAIR STADIUM SEATING WHEELCHAIR ACCESSIBLE ALL DIGITAL SOUND HEARING IMPAIRED SOUND Root Plowing - Root Raking Discing and Tank Building. Call: 361-594-2493 Re-Roof Vinyl Siding Metal Buildings Remodeling Concrete Works Plumbing Trenching Backhoe Service Serving the area since 1948 B&J Liquor Wide Selection of Liquor, Wine, Liqueurs and Beer! Special Orders Welcome! Gift Baskets made to order! MiChaeL durrett (830)857-4442 FREE ESTIMATES Any type concrete work. Commercial & Residential We dont do cheap work; We do quality work (361)293-1941 Electric RE WINDING PAIRING BUILDING MOTOR Est. 1930 SPECIALISTS Construction Company Sub-Contractor Specializing in Site Work Foundation Pads-Road Work-Demolition Stock Tanks-Brush Clearing Sponsored by Page A7 September 5th Office 830-672-2845 Chamber Chatter Daisy Scheske Daisy Scheske is the Executive Director of the Gonzales Chamber of Commerce. Country Collectibles donated $800.00 to Gonzales Main Street to help make downtown Gonzales more brighter during Christmas time. I wanted to give my part in helping beautify and light up downtown Gonzales during Christmas, said Vivian Wallace, owner of Country Collectibles. Pictured accepting the check is Connie Dolezal, Main Street treasurer, Vivian Wallace, Marilyn Qualls, Barbara Friedrich, Main Street Director, members of Main Street - Sanya Harkey, Kacey Lindemann Butler, Melissa Taylor (little Wesley Casares), Del De Los Santos and Debbie Toliver. If any business or individual would like to donate to the Main Street Christmas Lighting to make Winterfest more beautiful please contact Barbara Friedrich, Main Street Director @ 830-672-2815. (Photo by Mark Lube) These cooking shows on TV are just totally amazing. Our average Texan in Gonzales County is not going to pull out Coriander Seed, Mustard Seed, Cumin Seed and Saffron out of their spice supply cabinet. Somehow I just dont see how a burger made out of lamb is going to cut it. At least that poor lady that looks like she just went through a wind tunnel from the looks of her hair does admit that she gets a little wild with her cooking and drinks as much of the wine as she puts in the food. I think her name is Ann Burrell. I think I can say these things because she is a public figure. Ol Rachel Ray says to use a cast iron pan. Now our grandmothers could have told everyone that. So feed your family this week because everyone will be hungry after school. Maybe some good Texas burgers would work best. PRAYER TIME: Joe Kotwig, Mr. Bill, Jesse Esparza; Bill and Marie Lott, Louise Jones, Sandy Ingram, Aunt Georgie Gandre; Danny and Joyce Schellenberg, Sarge Duncan, Rhonda Pruett, Terrence, Aunt Frances Gandre, Bubba and Sara Roecker, Glenn Mikesh, Lillie Lay, Maria Castillo, Phyllis and Alton Oncken, Selma Vickers, Landis, Keith Glass, Teresa Wilke, Linda Denker, Case Martin, Sandi Gandre, Aunt Betty Gandre, Margie Menking, Joy Carson, Richard Hidalgo Jr., Arthur Casares, Shirley Dozier, Marie Schauer, L.A. Lindemann, Jr.;Graham Kelley, Esther Lindemann, Anna Lindemann, Lanny Baker, Judy Wilson, Bob Young, Marguerite Williams, and our military and their families, Wade and Lola Wilson enjoyed a short visit from Pat and Jamie Jo Wilson after they went to see Katelyns volleyball game which was played in Seguin. They Sandi Gandre didnt say who won. Then Wade and Lola were enjoying some fajitas that Michael had made. They were out on the back porch talking to Joshua when they noticed that their good dog Pluto was staring at something very intensely right in front of their pump house. Wade took a hoe and went to see what it was and sure enough it was a big fat rattle snake stretched out. It was about five foot long and had seven rattlers. Joe Kotwig nearly stepped on one of those dear rattle snakes while putting out a bale of hay. His foot managed to stay up off the snake and the pitch fork went down on the snake. Then it landed upside down on the fence as per tradition to see if we could draw some rain down. It thundered. Barbara Wenske Pohmeyers husbands killed a 36 inch on their property. Watch out they are hunting a cool place too. Another thing that is hunting a dab of water is those fire ants. Some of them look like mutated fire ants but their sting is just as bad. Those little devils are persistent and they hurt. And they are very thirsty. They are all over you or the crackers or your child/pet before you know it, so watch out. And they dont care whether it is night or day. They are just like a drunk. They just keep bumbling and bumping around like lost sheep. I watched the same two ants have a head on collision with the same door facing three times in a row last night. It was good to see Ina Gay Orum and Janet Clark at the Monthalia United Methodist Church last Sunday. Then I heard that Pastor Paul was trying to get these kids to drink dirty water. I guess that you will just have to back track it to get the low down on this. Since I have been waking up feeling like a freight train ran over me backwards, I guess I will have to do the same. It has been so hot this last couple of days that even Pepe has been lethargic. Not one of the outside critters has been inclined to move. Even poor Nicki D, the sixteen year old cat, has just laid up there on his box and given out one big yowl. He didnt even move an inch. I am so amazed at Nicki. He was born with his hip bones outside of its sockets. I took him to Dr. McKee and he said it wouldnt do any good to operate on his hips. He said that I would just have to watch him and protect him the best I could. For a long time he had a big black cat who was his friend. Unfortunately about three years ago something killed my big black cat. Nicki and I hunted him for days, but we never found him. So now Nicki rarely leaves the yard. We baby old Nicki D with special favors and now Itsy Bitsy is his protector. Have a good week, and God Bless. can Bingo, annual Jamaica Auction, Ballet Folklorico, and one of my favorites, the Jamaica raffle! Since I can remember, my family has purchased a couple of raffle tickets every year. One year I actually won a microwave that I still use to this day! Another great event coming up in September is the First Shot Cook-off that will be held at J.B. Wells Park. I was able to attend last years event and I was thoroughly impressed as to how many participants were there. Growing up in Texas you are always surrounded by BBQ, especially in our neck of the woods! Last year I indulged in some of the best BBQ I had ever tasted! (Ive even been a judge at the Austin Rodeo Cook-Off) I look forward to attending this years competition and good luck to all the participants. Alongside the IBCA and CASI competitors there will be an antique tractor exhibit, arts & crafts vendors, and of course the Come & Pull it Tractor Pull! For more information or to register to show off your cooking skills, please visit them at. com The Gonzales Livestock Market Report for Saturday, August 31, 2013 had on hand: 833 cattle. Compared to our last sale: Calves and yearlings sold steady. Packer cows sold steady. Stocker-feeder steers: Medium and large frame No. 1: 150-300 lbs., $225$235; 300-400 lbs, $190-$230; 400-500 lbs, $170-$185; 500-600 lbs, $149-$165; 600-700 lbs., $138-$143; 700-800 lbs, $132-$135. Bull yearlings: 700-900 lbs, $91-$105. Stocker-feeder heifers: Medium and large frame No. 1: 150-300 lbs, $175-$210; 300-400 lbs, $165-$175; 400-500 lbs, $142-$160; 500-600 lbs., $135-$143; 600700 lbs., $127-$132. Packers cows: Good lean utility and commercial, $75-$80; Cutters, $79$87.50; Canners, $61-$68; Low yielding fat cows, $69-$76. Packer bulls: Yield grade 1 & 2, good heavy bulls; $97-$103; light weights and medium quality bulls, $85-$94. Stocker Cows: $950-$1,150. Pairs: $1,050-$1,550. Thank you for your business!! View our sale live at cattleusa.com! $150-$224 bra hfr; 450-500 lbs, $140$155; 500-550 lbs, $136-$150; 550-600 lbs, $132-$139; 600-700 lbs., $124-$132; over 700 lbs, $110-$125. Cuero Livestock Market Report on August 30, 2013, had 1,135 head. Had 189 cows and 14 bulls. The packer market was steady with past 3 weeks run- The Hallettsville Livestock Commission Co., Inc. had on hand on August 27, 2013, 2,095; week ago, 2,399; year ago, 1,880. More good rains in our area. Heavier weight classes of calves sold steady to $2 higher. Lighter weight classes sold weaker than last weeks very high market. Plainer an fleshier classes were a little weaker but overall demand very good. Packer cows and bulls sold $1 to $2 higher on approx. 330 hd. Total. Packer Cows: higher dressing utility & cutter cows, $75-$93; lower dressing utility & cutter cows, $63-$75; light weight canner cows, $52-$63. Packer Bulls: heavyweight bulls, $100$107; utility & cutter bulls, $94-$100; lightweight canner bulls, $85-$94. Stocker and Feeder Calves and Yearlings: Steer & Bull Calves: under 200; $210-$250; 200-300 lbs, $200-$255; 300400 lbs, $185-$240; 400-500 lbs, $168$200; 500-600 lbs, $140-$173; 600-700 lbs, $138-$154; 700-800 lbs, $131-$146. Heifer Calves: under 200 lbs, $190-$242; 200-300 lbs, $175-$218; 300-400 lbs, $161-$191; 400-500 lbs, $142-$176; 500600 lbs, $135-$154; 600-700 lbs, $128$140; 700-800 lbs, $118-$138. If we can help with marketing your livestock, please call 361-798-4336. Mill FREE Complete Auto & Truck Repair Specializing in Diesel, European & Asian Triple AAA Certified Shop $200 up to $1258 (830) 672-7967 *All loans are subject to our liberal credit policy and credit limitations, if any and require verifiable ability to repay Page A8 The Cannon (830) The Cannon Page A9leysersons murder. On October 11, 1878, before a crowd of thousands, Longley was executed in Giddings by Lee County sheriff James Madison Brown. Rumors persisted that Longleys hanging had been a hoax and that he had gone to South America, and a claim was made in 1988 that he had later reappeared and died in Louisiana. AUSTIN Commissioner of Education Michael Williams this week reminded school districts across the state of provisions in a new law relating to the adoption of major curriculum initiatives, including curriculum management systems such as the recently-renamed CSCOPE. Senate Bill 1474 (SB 1474) which was passed by the 83rd Texas Legislature, signed by the governor and became effective June 14 - initia- tive committees TEA regional administrators who developed CSCOPE, working as the Texas Curriculum Management Program Cooperative, announced to school districts on Aug. 26 the system was being re-named. In a letter to school districts, Dr. Jerry Maze, chair of the cooperative, said that as of Aug. 30 CSCOPE will be re-titled the TEKS Resource System. We believe this new name will better reflect our mission, our service, and will help all parties involved move forward in a positive way, Mazes letter notes. TEKS Resource System is just that, a resource. It will still have all of the components and options you have enjoyed in the past and any material that you have developed within the old site will automatically be transferred to the new site ... However, as we have stated previously there will be no sample lessons provided within the system. The CSCOPE electronic curriculum management system came under intense scrutiny in the last year, first from individual teachers and parents and then from Texas legislators during the last session, after several lesson plans were found which contained what many perceived as anti-American, anti-Christian and other messages. The system was also heavily criticized for requiring teachers to teach specific lessons in specific ways at specific times, which many veteran classroom teachers insisted limited their effectiveness in communicating with students. More than 70 percent of Texas school districts continue to use the system in one degree or another. Caldwell County Sheriff Daniel Law announced that on August 31, Hays County deputies arrested Erasto Escutia, 17, on multiple warrants issued out of the Caldwell County Sheriff s Office. On August 6, Escutia was reported to have displayed and fired a handgun during a disturbance in the 100 Block of Misty Lane, which is located in Caldwell County. Judge Todd Blomerth issued a warrant for his arrest Erasto Escutia On the Square 5th - DJ Rocketman (Karaoke) 7th - Neon Light Cowboys 12th - Dennis & DJ Richter September Schedule 14th - Bushy Creek Boys 19th - DJ Rocketman (Karaoke) 20th - TEXXAS 21st - Good Old Boys 27th - Keen Country Lunch served Monday-Friday, 11am-2pm Dinner - 6pm-9:30pm - Saturday Dinner only 6pm-9:30pm Howards Breakfast Lunch Page A10 The Cannon 3.6L, V-6 Michael Scott Zella received his Masters Degree in Criminal Justice Leadership and Management in ceremonies held at Sam Houston State University August 3, 2013. Scott is currently the Southern District Commander in the law enforcement division of the Texas Department of Criminal Justice, Office of Inspector General. Scotts career in law enforcement began in May of 1991 after completing his Associates Degree in criminal justice at Kilgore Junior College. He then enrolled at Sam Houston State and began his Bachelor of Science degree in criminal justice while at the same time being employed by the Walker County Sheriff s department as a jailer. Scott received his Bachelor of Science degree in August of 1993 where upon he accepted a position of deputy sheriff in Walker County. He completed the Montgomery County Police Academy in Conroe , Texas and went on to serve as a deputy sheriff from 19942001 attaining the rank of Sergeant and receiving the Officer of the Year Award 830-303-4546 and three daughters, Kaci, Jaci, and Graci reside in Huntsville, Texas today. Scott is the son of Gary Zella and Teddy Jo Newberry Scheske. Grandparents were J. Carlyle and Ruthe Newberry and Adolph and Laura Lee Pakebusch Zella. Reagan Lynn Daniel is proud to announce the birth of her baby brother, Easton Layne Daniel, who was born on Friday, June 14, 2013 at 12:44 p.m. at the Central Texas Medical Center in San Marcos. Easton tipped the scale at 10 pounds, 4 ounces and was 19.5 inches long at birth. Also welcoming Easton into this world are proud parents, John and Valorie Daniel; and grandparents Dale and Sherri Schellenberg, and Tom and Mary Daniel. Great grandparents include Betty Cuvelier, Dannie and Joyce Schellenberg, Donald and Bertha Cuvelier, Beatrice Mikesh and the late Ervin Mikesh, and the late Bill and Bettye Daniel of Denton. (Courtesy photo): Fast Relief capsules and cream (All natural with no side effects.) Plexus 96 Protein shake (A yummy tasting non gritty drink that is full of vitamins and 15g of protein. Great for breakfast or a meal on the go) Contact your Plexus Ambassador for details on how to get started for only $34.95 Contact me about new multi vitamins available Shelly Stamport - 830-857-0209 Soncrest Eggs 925 Saint Andrew Gonzales Faith The Cannon Page A11ahai Faith Bahai HOUSE FOUNDATIONS STAINED CONCRETE DRIVEWAYS SIDEWALKS DIRT WORK ALL YOUR CONCRETE NEEDS Travis Treasner Ilene B. Gohmert Certified Public Accountant First Baptist Church 422 St. Paul, Gonzales First Baptist Church 403 N Texas Nixon First Baptist Church Hwy 108 N Smiley Construction Company Office 830-437-2873 Bubba Ehrig 830-832-5094 830-540-4285 phone 830-672-2867 (830) 672-6556 STEVE EHRIG 830-263-1233 830-672-2551 Melanie Petru-Manager melaniepetru@gmail.com txarr.com/license #030010 Call Debbie or Dot at 672-7100 today to reserve your sponsorship on the Worship Page for ONLY $10 per issue. Page A12 The Cannon The surging economy in Gonzales is setting the stage for some major expansion and renovation of the downtown area. Last week, the GISD Board of Trustees voted to proceed with buying the old H-E-B building on St. Joseph St. to renovate as a campus for the districts early-childhood programs, and several businesses are opening up downtown locations or renovating their facades. BZs Country Petals (left) at 616 St. Lawrence was scheduled to open this week at 626 St. Lawrence. Hours will be 8 a.m.-5:30 pm. Monday-Friday and 8 a.m.-noon on Saturday. (Photos by Mark Lube) The old warehouse at 418 St. Andrew St. is being restored and will soon have its new tenant Brothers Grajales Gourmet Coffee. Owner Carlos A. Hernandez Grajales said the facility will be the home for two gourmet brands: Brothers Grajales Coffee and Come and Take It Coffee. Grajales expects the new warehouse operation will be ready for business by the first weekend in October. (Photos by Dave Mundy) While several downtown-area buildings are seeing new tenants and new businesses, other property owners are making improvements to make their facilities more inviting to prospective tenants. Cary Blake, owner of the J.P. Randle Building at 509 St. Joseph Street is currently making renovations to the building. I am removing personal belongings, items that are not useful, cleaning up and removing the old awning, she said. (Photos by Mark Lube) Loans Up to $1,300.00 Serving Texas for over 40 Years! Sports Bastrop at Gonzales Friday, 7:30 p.m. Apache Stadium Johnson last year and this year we get the opportunity to see what kind of football player he is, Lock said about Ramirez. He ran the ball with authority and made a lot of shifty moves. He really worked hard in the offseason on increasing his speed and hes done it. Hes worked his way to where he is now. Hes also an outstanding student and a very intelligent young man. Were very fortunate that hes an Apache because he makes a lot of plays for us. Unfortunately Gonzales was bitten by the injury bug last week when standout senior lineman Tyler Filla went down with a knee injury. Lock said he will The Cannon Things couldnt have gone much better for Gonzales last Friday. The Apaches rolled into Victoria and rolled out of town with a convincing 40-point win over the East Titans. Head coach Ricky Lock saw his offense bully their way to 606 rushing yards including six scoring runs of 15 yards or more. Happy with the win but not content with the execution, Lock said his charges still have a ways to go. Weve still got a lot of work to do, he said. Weve got to clean some things up and get in better condition. We missed a lot of blocks on the perimeter and defensively we missed a lot of tackles, two of which went for long touchdowns. I do think however that we did get better as a team. It was a learning experience for the young men who hadnt played at that level before and it was a positive experience because of the way the game turned out. What the game turned out to be was a coming out party for Alyas Ramirez, who rushed for a gamehigh 256 yards on 19 carries and four touchdowns. The sophomore stud was also an important part of the Apache defense that (for the most part)stymied the Titans all night with the exception. He backed up Cecil be evaluated by doctors in San Antonio this week and is definitely out for Fridays contest. Were hoping we can get Tyler back at some point, said Lock. Whenever theres an injury, you expect the worse and hope for the best. Sophomore Clayton Wilkerson will likely be replacing Filla in the lineup, which means he would be making his first ever varsity start. Bastrop will come to town Friday night still reeling from their seasonopening 35-6 loss to Cedar Park Vista Ridge. The Bears had five turnovers in the game and twice failed to score from inside the 10yard line. The game was a lot closer than the score indicates, said Lock. They played pretty well on defense, they just had some bad luck happen to them. Defense seems to be the strong point for the Bears this year where are led by quick DL Masta Hicks, LB Luis Carmona and DB Romello Wilson, who had an interception last week. Hicks is very, very athletic and Carmona is very active, Lock said. Wilson really stands out when you watch their secondary on film. Lock said in order to avoid the track meet last weeks first half turned into, the Apaches are going to have to be more sound on APACHES, Page B2 Area Previews The Gonzales Junior White Apaches, led from left by Cade Davis (25), Lane Mills (64), Jaydyn Lookabill (5) and Colby Richter (90), tore through their sign and stormed the field at the beginning of their seasonopening game at Yorktown. For a roundup of last weekends CYFL kickoff, see page B5. (Photo by Cedric Iglehart) Its a new year in the Shiner-Hallettsville rivalry. The teams meet at 7:30 p.m. Friday at Brahmas Memorial Stadium. Both opened with explosive wins last week The Comanches ran all over Industrial in a 34-0 win and Hallettsville took care of business against the Ganado Indians, winning 43-6. Both squads had good years in 2012, but it is now 2013. Hallettsville is ranked and they are predicted to be good like last year, Shiner head coach Steven Cerny said. But it is a new year. Shiner is a tough team, Hallettsville head coach Tommy Psencik said. They have solid quarterback, running backs and an experienced offensive line. Hallettsville runs a balanced spread attack and Shiner has to be ready for anything If we shut down the run, they will go to the pass, Cerny said. We need to mix things up defensively. We cannot let them have the big play. Hallettsville will need to earn every point. It will have to be a bend-butdont-break thing. Hallettsville has several playmakers including Trenton McGee, Dalton Herrington, Jimario Grounds, Tim Sheppard, Kaylon Massey, Kaden Hardt, Brent Motal and Nate Kowalik. Shiners offense had a good performance against Industrial. We need to control their PREVIEWS, Page B2 GONZALES Any win for a team is going to help its confidence the slightest bit for the next match. The Gonzales Lady Apaches swept the Austin Eastside Memorial Lady Panthers, 25-8, 25-3 and 25-5, Tuesday evening at the GHS Special Events Center. Lady Apache head coach Sarah Moreno was pleased with everything the Lady Apaches did. Its a win in the book, she said. It built our confidence. The girls did great things by sticking to our system. The defense did great getting to the places they needed to be and being very disciplined. Moreno said Gretchen Singleton had five kills to lead the Lady Apaches (612) with Molly Barnick and Alex Finch chipping in four kills each. In sets two and three, Danielle Flowers was a force to be reckoned with from the serving spot in the back. Danielle got lots and lots of aces, Moreno said. She just does not miss them. I called for different ones and she made every single one of them. In the first set, the Lady Panthers managed to grab the early hand, taking a 3-2 lead and getting an ace from Anna Habimana. A kill from Barnick tied the game at 3-3 and Gonzales then scored nine straight points, getting a block from Kendall Fougerat and an ace from Madison Musick. Eastside Memorial was able to close down to 13-5 and Gonzales went to vic- tory with 12-3 run, getting an ace from Cassidy La Fleur and a kill from Finch. Gonzales got a 5-2 lead in the second game, getting a couple of aces from Musick. Later, ahead 7-3, the Lady Apaches ripped off 18 straight points with around half a dozen or so aces from Flowers and kills from both Fougerat and Singleton. In the third set, the serving of Flowers powered the Lady Apaches to a 6-1 advantage. Gonzales later went up 15-3 on plays from Singleton and Fougerat as well as kills from Danyelle Glass and Bailey Connell. The Lady Apaches then ended the match with a 10-0 run. The Gonzales junior varsity and freshman teams played each other with the JV winning, 25-11 and 25Brianna Miller prepares to hit the ball while teammates Madison Musick (9) and 7. Alex Finch (3) look on during Gonzales match against Eastside Memorial Tuesday night. (Photo by Mark Lube) Page B2 Y 7 0 14 0-21 Scoring Summary C-Tyson Simcik 4 run (Derrick District 26-3A Standings Hayes kick) District Overall Y-TreVontae Hights 15 run Giddings 0-0 1-0 (Reagan Jacobs kick) Gonzales 0-0 1-0 Y-Hights 8 run (kick failed) La Grange 0-0 1-0 Y-Jared Garza 43 pass from Cuero 0-0 0-1 Chase Hermes (Hights run) Smithville 0-0 0-1 C-Detriyon Carter 54 run (run Yoakum 0-0 0-1 failed) Last game results Gonzales C-Simcik 1 run (run failed) 60, Victoria East 20; Columbus C-Simcik 1 run (run failed 25,Yoakum 21; Wharton 23, Team Stats Col Yoa Cuero 22; La Grange 49, Marble First Downs 19 13 Falls 23; Giddings 21, Liberty Rushes-yds 56-301 32-160 Hill 20 Passing yds 49 148 Fridays game schedules Bastrop Passes 3-8-1 4-12-2 at Gonzales, 7:30 p.m.; Wimberley Penalties-yds 8-40 5-58 at Giddings, 7:30 p.m.; La Grange Fumbles-lost 3-3 6-6 at Columbus, 7:30 p.m.; Smithville Punts-avg. 6-30.1 3-37.3 at Marble Falls, 7:30 p.m.; Victoria Individual stats West at Cuero, 7:30 p.m.; Yoakum Rushing Columbus: Detriyon at Sinton, 7:30 p.m. Carter 16-151, Royce Caldwell 12Game Summaries 54, Tyson Simcik 22-53. Yoakum: Gonzales 60, Victoria East 20 Trevontae Hights 13-93, Terrance Score by Quarters Hall 6-39, Gilbert Dominguez G 19 21 20 060 2-22. V 6 13 0 020 Passing Columbus: Simcik Scoring Summary 3-8-49-1. Yoakum: Chase Hermes G - Alyas Ramirez 61 run (pass 2-9-103-2, Hights 2-3-45. failed), 1st, 9:46 Receiving Columbus: Logan G - Darrance James 15 run (con- Denley 1-43. Yoakum: Hall 2-81, version failed), 1st, 4:39 Garza 1-43, Miguel Resendiz 1-24. G - D.J. Gonzales 77 run (Jose District 15-2ADI Standings Contreras kick), 1st, 1:26 District Overall V - Cameron Williams 77 kick Luling 0-0 1-0 return (conversion failed), 1st, 1:09 Marion 0-0 1-0 G - Ramirez 39 run (Contreras George West 0-0 0-1 kick), 2nd, 9:47 Jourdanton 0-0 0-1 V - Jonathan Ortega 75 run SA Brooks 0-0 0-1 (Kelsey Ferry kick), 2nd, 9:21 SA Cole 0-0 0-1 G - Ramirez 5 run (Contreras Last game results Luling 47, kick), 2nd, 5:51 Universal City Randolph 23; V - Ortega 64 run (Ferry kick), Bandera 42, George West 12; Falls 2nd, 4:32 City 34, Jourdanton 28; Stockton G - Brant Philippus 10 run 27, San Antonio Cole 7; Marion (Contreras kick), 2nd, 0:06 29, Poth 28; San Antonio St. G - Ramirez 2 run (pass failed), Anthony 47, San Antonio Brooks 3rd, 7:35 Academy 6 G - Jaime Tellez 15 run (ContreFridays game schedules Altair ras kick), 3rd, 3:58 Rice Consolidated at Luling, 7:30 G - Aaron Hunt 48 run (Contrep.m.; Karnes City at Marion, ras kick), 3rd, 1:58 7:30 p.m.; Ingleside at George Team Stats G V West, 7:30 p.m.; Jourdanton at First downs 14 7 Stockdale, 7:30 p.m.; Universal Rushes-yds 58-606 17-187 City Randolph at San Antonio Passing yds 15 67 Cole, 7:30 p.m.; San Antonio Passing 1-2-0 5-18-0 Brooks Academy at San Antonio Punts-yards 1-26 3-148 Cornerstone, 7:30 p.m. Fumbles-lost 2-0 2-1 Game Summaries Penalties-yds 5-40 1-5 Lulilng 47, Universal City Individual stats Randolph 23 RUSHING Gonzales: Alyas Score by Quarters Ramirez 19-256, Brant Philippus L 19 12 0 16-47 13-66, Aaron Hunt 8-87, GrayUCR 2 8 0 13-23 son Meredith 7-23, D.J. Gonzales Scoring Summary 6-118, Jamie Tellez 3-15, Darrance L-Taylen Moore 88 pass from James 2-41. Victoria East: Jonathan Trayden Staton (Kaylen Coe kick) Ortega 10-166, Laken Williams L-Moore 26 pass from Staton 4-(-4), Bryce Martinez 2-21, Trey (kick failed) Martinez 1-4. L-Brendon Cubit 17 run (twoPASSING Gonzales: Philippoint conversion failed) pus 1-2-15. Victoria East: Ortega UCR-Justin Alexander defen5-18-67. sive two-point conversion RECEIVING Gonzales: L-Shaft Cubit 16 run (run failed) James 1-15. Victoria East: Williams UCR-Christian Hosley 8 run 2-12, Dillon Lippe 1-20, Josh Bare(Bryan London run) field 1-20, Trent Whitley 1-15. L-Shaft Cubit 3 run (pass failed) Columbus 25, Yoakum 21 L-Brendon Cubit 10 run (Josh Score by Quarters Alvarez pass from Staton) C 7 0 6 12-25 UCR-Miguel Rivera 33 run (run Football Scoreboard The Cannon failed) L-Brendon Cubit 8 run (Moore run) UCR-Hosley 4 run (Zach Trujillo kick) Team Stats L UCR First Downs 20 17 Rushes-yds 27-187 52-237 Passing yds 274 75 Passes 11-21 6-14 Penalties-yds 8-57 4-25 Fumbles-lost 0-0 1-0 Punts-avg. 3-29 4-24 Individual stats Rushing Luling: Brendon Cubit 11-107, Trayden Staton 7-36, Shaft Cubit 6-24, Taylen Moore 3-20. UCR: Bryan London 24-110, Christian Hosley 20-75, Miguel Rivera 3-41, Justin Alexander 3-7, Colin Toth 2-4. Passing Luling: Staton 11-21274-0. UCR: Toth 6-14-75-0 Receiving Luling Moore 3-114, Josh Alvarez 3-66, Brendon Cubit 2-22, Desmond Cubit 1-49, Shaft Cubit 1-14, Keeton Coe 1-9. UCR: Hosley 3-27. Passing Hallettsville: Kowalik 12-16-242-0. Ganado: Salazar 5-14-45-0. Receiving Hallettsville: Herrington 5-82, Trenton McGee 3-98, Massey 1-14, Jimario Grounds 2-32, Sheppard 1-16, Massey 1-14. Ganado: Smith 4-38, Morales 1-7. District Overall Edna 0-0 1-0 Hallettsville 0-0 1-0 Hempstead 0-0 1-0 Altair Rice 0-0 0-1 Industrial 0-0 0-1 Palacios 0-0 0-1 Last game results Hallettsville 43, Ganado 6; Hempstead 34, Brookshire Royal 22; Edna 27, Needville 14; Houston St. Thomas 46, Altair Rice 30 Consolidated; Shiner 34, Vanderbilt Industrial 0; Boling 35, Palacios 12 Fridays game schedules Shiner at Hallettsville, 7:30 p.m.; Altair Rice at Luling, 7:30 p.m.; Stafford at Hempstead, 7:30 p.m.; Refugio at Edna, 7:30 p.m.; Ganado at Vanderbilt Industrial, 7:30p.m.; Palacios at El Maton Tidehaven, 7:30 p.m. Game Summaries Hallettsville 43, Ganado 6 Score by Quarters H 8 7 28 0-43 G 0 0 0 6-6 Scoring Summary H-Trenton McGee 76 pass from Nate Kowalik (Tim Sheppard run) H-Kaden Hardt 3 run (Kowalik kick) H-Dalton Herrington 89 kickoff return (Kowalik kick) H-Herrington 65 pass from Kowalik (Kowalik kick) H-Herrington 24 run (Kowalik kick) HSheppard 15 run (Kowalik kick) G-Kameron Smith 7 pass from Ray Salazar (run failed) Individual stats Rushing Hallettsville: Brent Motal 10-92, Kaden Hardt 9-82, Tim Sheppard 5-32, Dalton Herrington 2-24, Kaylon Massey 2-3,Drew Haas 1-0, Nate Kowalik 1-(-3). Ganado: Billy Jones 12-25, Benny Garcia 1-25, Ray Salazar 1318, Jonathan Martinez 1-6, Bobby Garcia 4-5, Cody Morales 2-4, Kameron Smith 1-4. District Overall Karnes City 0-0 1-0 Nixon-Smiley 0-0 1-0 Stockdale 0-0 1-0 Bloomington 0-0 0-1 Cotulla 0-0 0-1 Natalia 0-0 0-1 Poth 0-0 0-1 Last game results Nixon-Smiley 28, Flatonia 14; Karnes City 27, Kenedy 21; Woodsboro 41, Bloomington 31; Stockdale 27, San Antonio Cole 7; Carrizo Springs 35, Cotulla 6; Ingram Moore 40, Natalia 2; Marion 29, Poth 28 Fridays game schedules Three Rivers at Nixon-Smiley, 7:30 p.m.; Karnes City at Marion, 7:30 p.m.; Bloomington at Agua Dulce, 7:30 p.m.; Jourdanton at Stockdale, 7:30 p.m.; Cotulla at Crystal City, 7:30p.m.; Lytle at Natalia, 7:30 p.m.; Poth at Falls City, 7:30 p.m. Game Summaries Nixon-Smiley 28, Flatonia 14 Score by Quarters Flat 6 0 8 0--14 N-S 0 7 14 7--28 Scoring Summary FLAT--Mitchel Mica 1 run (pass failed) N-S--Nick Pena 1 run (Eduardo Tovar kick) FLAT--Gus Venegas 18 pass from Will Bruns (Mica run) N-S--Tom Palacio 1 run (Tovar kick) N-S--Jared Van Auken 34 run (Tovar kick) N-S--Samuel Moore 18 interception return (Tovar kick) Team Stats FLAT N-S First Downs 6 11 Rushes-Yds 30-(-26) 45-199 Passing Yds 90 26 Passes 6-12-2 2-3-0 Penalties-Yds 7-60 9-59 Fumbles-Lost 5-2 4-1 Punts-Avg 2-35.5 5-18.7 Individual Statistics RUSHING: Flatonia, Marcus Mica 3-10, Aaron Manzano 3-14, Gus Venegas 3-(-11), Will Bruns 18-(-45), Mitchell Mica 3-6. NixonSmiley, Kevin Martinez 2-2, Jared Van Auken 18-107, Tristen Newman 7-43, Nick Pena 5-(-2), Justin Ramos 2-4, Tom Palacio 10-43, Samuel Moore 1-2. PASSING: Flatonia, Will Bruns 6-12-2-90. Nixon-Smiley, Nick Pena 1-2-0-22, Samuel Moore 1-10-4. RECEIVING: Flatonia, Gus Venegas 5-84, Marcus Mica 1-6. Nixon-Smiley, Samuel Moore 1-22, Tristen Newman 1-4. District Shiner 0-0 Three Rivers 0-0 Yorktown 0-0 Ganado 0-0 0-1 Kenedy 0-0 0-1 Last game results Shiner 34, Vanderbilt Industrial 0; Three Rivers 30, Skidmore-Tynan 0; Yorktown 28, Hallettsville Sacred Heart 22; Karnes City 27, Kenedy 21; Hallettsville 43, Ganado 6 Fridays game schedules Shiner at Hallettsville, 7:30 p.m.; Three Rivers at Nixon-Smiley, 7:30 p.m.; Yorktown at Goliad 7:30 p.m.; Pettus at Kenedy, 7:30 p.m.; Ganado at Vanderbilt Industrial, 7:30p.m. Game Summaries Shiner 34, Vanderbilt Industrial 0 Score by Quarters I 0 0 0 0-0 S 7 7 13 7-34 Scoring Summary S-Tyler Patek 67 run (Rigo Baray kick) S-Marcus Coleman 76 run (Baray kick) S-Jacob Stafford 37 run (Baray kick) S-Patek 17 run (kick blocked) S-Coleman 4 run (Hunter Mraz kick) Team stats I S First Downs 10 18 Rushes-yards 31-56 47-364 Passing yards 109 0 Passes 11-19-1 0-2-0 Penalties-yards 5-45 2-10 Fumbles-lost 2-2 1-1 Punts-average 4-27 1-49 Individual stats Rushing Industrial: Evan Gregg 5-25, Trenton Thedford 8-24, , Trevor Russman 3-6 Jay Rubio 15-1. Shiner: Marcus Coleman 12-140, Jacob Stafford 13-132, Tyler Patek 14-101, Chad Neubauer 4-9, Joey Overton 1-5, Blake Michalec 1-1, team 2-(-24). Passing Industrial: Rubio 1119-1-109. Shiner: Stafford 0-1-0-0, Patek 0-1-0-0. Receiving Industrial: Cade Peterek 3-36, Gregg 3-35, Thedford 2-20, Rhett Musser 2-13, Tyler Conard 1-5. District Overall Thrall 0-0 1-0 Weimar 0-0 0-0 Flatonia 0-0 0-1 Holland 0-0 0-1 Thorndale 0-0 0-1 Last game results NixonSmiley 28, Flatonia 14; Thrall 18, Bruceville-Eddy 14; Jarrell 34, Holland 18; Chilton 41, Thorndale 14 Fridays game schedules Hallettsville Sacred Heart at Flatonia, 7:30 p.m.; Boling at Weimar, 7:30 p.m.; Holland at Granger, 7:30 p.m.; Thorndale at Somerville, 7:30 p.m. Saturdays game schedules Florence vs. Thrall at Waxahachie, 4 p.m. District Brazos Chr. 0-0 John Paul II 0-0 St. Joseph 0-0 Sacred Heart 0-0 St. Gerard 0-0 Overall 1-0 1-0 1-0 0-1 0-1 St. Paul 0-0 0-1 Last game results Yorktown 28, Hallettsville Sacred Heart 22; Pettus 26, Shiner St. Paul 14; Bryan Brazos Christian 28, Cypress Christian 22; Bryan St. Joseph 53, Central Texas Christian 8; Schertz John Paul II 48, Texas School for the Deaf 48-0; St. Marys Hall 21, St. Gerard 16 Thursdays game schedule St. Gerard at San Antonio Hawkins, 7:30 p.m. Fridays game schedules Sugarland Fort Bend Christian at Shiner St. Paul, 7:30 p.m.; Hallettsville Sacred Heart at Flatonia, 7:30 p.m.; Snook at Bryan Brazos Christian, 7:30 p.m.; Temple Holy Trinity at Bryan St. Joseph, 7:30 p.m.; Austin Eastside Memorial at Schertz John Paul II, 7:30 p.m. Game Summaries Pettus 26, St. Paul 14 Score by Quarters SP 6 8 0 0-14 P 13 6 0 7-26 Scoring Summary P-Anthony Mendoza 25 run (Matt Gonzales kick) SP-Colton Machart 84 pass from Austin Barton (run failed) P-Mendoza 51 pass from Gonzales (run failed) SP-T.J. Bell 40 run (Marco Ynclan run) P-John Constante 31 run (kick failed) P-Gonzales 1 run (kick failed) Team Stats SSP P First Downs 15 9 Rushes-yds 37-246 30-95 Passing yds 153 105 Passes 9-22 4-6 Penalties-yds 6-35 1-10 Fumbles-lost 2-2 0-0 Punts-avg. 2-32.5 5-41.6 Individual stats Rushing St. Paul: T.J. Bell 22-145, Ryan Gieger 4-50, Austin Barton 6-24, Marco Ynclan 2-17, Jed Janecek 3-10. Pettus: John Constante 14-80, Anthony Mendoza 2-28, Josh Herrera 7-(-3), Matt Gonzales 7-(-10). Passing St. Paul: Barton 9-22153-0. Pettus: Gonzales 4-6-105-0 Receiving St. Paul: Colton Machart 2-93, Ynclan 3-33, Geiger 2-21, Nathan Pilat 1-6. Pettus: Mendoza 3-69, C.J. Crux 1-36. Yorktown 28, Sacred Heart 22 Score by Quarters Y 8 14 0 6-28 HSH 14 8 0 0-22 Scoring Summary HSH-Jonathan Vanek 79 kickoff return (two-point conversion failed) Y-Logan Romans 3 run (Steven Perez run) HSH-Dylan Jahn 27 run (Trent Janak pass from Scott Stoner) Y-Jonathan Weischwell 5 run (Roman run) HSH-Kyle Pettus 2 run (Jahn pass from Stoner) Y-Caleb Schendel 42 run (twopoint conversion failed) Y- Steven Perez 1 run APACHES: Looking for PREVIEWS: Sacred Heart, more offensive execution Flatonia renew their rivalry and consistency on defense Continued from page B1 Continued from page B1 defense. Weve got to make sure that we are in the right places, he said. They have more team speed than we do. Weve got a couple of guys that can run, theyve got a bunch of guys that can run. Assistant coach Todd Patmon was promoted last May after former head coach Gerald Perry was reassigned after five seasons. Perry last guided the Bears to the playoffs in 2010. Under Patmon, Bastrop has abandoned the triple option look from a year ago for a traditional one back set based on zone reads and spreading out the defense to create natural running lanes. The Bears are big up front on the offensive line where Jordan Davis (6-3, 300) and Jarvis Brawley (6-1, 255) are returning starters. RB Carrington Waites (1151) was the teams leading rusher last week, but the Bears will also try innovative ways to get the ball into the hands of dangerous receiver Izaiyah Washington. The key to holding down Bastrops offense is not al- lowing new QB Cameron Barron to settle into a groove. Last week, he completed 9 of his 18 passes for 79 yards and also had a two-yard touchdown run. Last year they had a very fast kid at quarterback but this kid has a better motor and runs the ball more effectively, said Lock. Hes also pretty decent at throwing the ball. The game will kickoff at 7:30 p.m. in Apache Stadium. defensive line with our offensive line and run the veer effectively, Cerny said. Shiner will count on Jacob Stafford, Marcus Coleman and Tyler Patek to produce a lot of rushing yards. Against Shiners veer, our defensive players will need to do their specific job and not someone elses, Psencik said. We will have to fly to the football. On offense, we will need to keep possession of the ball by being very balanced. Last years game was an offensive show by Hallettsville as they won 49-28. It was Shiners only regularseason loss. Its a big game and there will be a big crowd, Psencik said. Sacred Heart at Flatonia Flatonia host Hallettsville Sacred Heart in a typical Bulldogs-Indians rivalry game for Flatonias home opener at 7:30 p.m. Friday at Bulldog Field. This will be a tight and tough game, Flatonia head coach Chris Freytag said. Sacred Heart is big, physical and they are strong. I think it will be a typical Flatonia-Sacred Heart game, Indians head coach Pat Henke said. Freytag said the Bulldogs must do better in all phases of the game against the Indians. Our offensive line did not block well and we have made a couple of adjustments, he said. We need to control the football which is something we struggled to do against Nixon (last week). Henke is expecting a tough battle from the Dogs. Flatonia is physical up front, they have size and have some good skilled players, he said. It will be a challenge for our defense. We gave up lots of yards against Yorktown last week. Sacred Heart will just need to their offensive line to play well to get the offense going. We must protect the PREVIEWS, Page B12 FINANCING AS LOW AS 2.99% APR** on select vehicles Offers good on new and unregistered units purchased between 7/30/13-9/30/13. *On select models. See your dealer for details. **Rates as low as 3.99% for 36 months. Offers only available at participating Polaris dealers. Approval, and any rates and terms provided, are based on credit worthiness. Other financing offers are available. Applies to the purchase of all new ATV, RANGER, and RZR models made on the Polaris Installment Program from 7/30/13-9/30/13. Fixed APR of 3.99%, 6.9 9%, or 9.99% will be assigned based on credit approval criteria.. 2013 Polaris Industries Inc. By CEDRIC IGLEHART The Cannon Page B3 newseditor@gonzalescannon.com night. In addition to the work put in by the all-star front five of Zach Perez-Clack, J.T. Miller, Damien Airhart, Jordan Johnson and Tyler Filla, the Apaches also received great blocking on the edge from Joe Ryan Carrizales and out of the backfield from Jose Contreras, Trent Schauer, Travis Schauer, and Dylan Cantu. Gonzales (1-0) scored early in its first possession. After a short gain by Ramirez brought up a fourth and one from the Apache 39, he darted through a hole made by Johnson and J.T. Miller and raced 61 yards for the score. The two-point conversion failed and Gonzales led 6-0 with 9:46 left. (From left) Jordan Johnson, Wade Miller and J.T. Miller converge on Titan quarOn the Titans first play, terback Jonathan Ortega. (Photo by Cedric Iglehart) Ortega was met in the After a short gain on backfield by Tellez and his pass incomplete due to from 15 yards out. The Derek Hunt for a three- tight coverage by James on Apaches were called for a first down by Meredith, yard loss. Ortega dropped Trent Whitley. Derek Hunt penalty on the two-point D.J. Gonzales broke up the to pass on the next play, but returned the ensuing punt conversion attempt so the left sideline, escaped out of a tackle at the 15 and he was flushed from the 22 yards to set the Apaches score stood at 12-0. Another quick three and dragged a hapless defender pocket by Perez-Clack and up in Victoria East territory at the 46. out followed for the Titans, into the end zone to cap a sacked by Johnson. Seven plays in, the highlighted by a tackle 77-yard jaunt. Following an illegal proHowever,Victoria East cedure penalty, the Titans Apaches used some razzle- for loss on Ortega by J.T. had a third and 24 from dazzle when James took a Miller. A touchback on the struck back with a little their own 24. Ortega faced pitch on an end around and punt gave Gonzales the ball trickeration of their own GONZALES, Page B4 another heavy rush and danced into the end zone at their own 25. Mustangs overcome own Defensive play provides mistakes, beat Flatonia early spark for Comanches By MARK LUBE sportseditor@gonzalescannon.com Flatonia running back Aaron Manzano is brought down by Nixon-Smileys Michael Scarbrough during the Mustangs win last Friday. (Photo by Dave Mundy) SHINER When a turnover and bad snap on a punt put Shiner in danger of conceding some early and easy scores, the defense stepped up and bailed the team out. The Comanches (1-0) ran through, around and over the Industrial Cobras, and the defense forced a couple of turnovers as Shiner got 2013 started the right way with a 34-0 win Friday night at Comanche Stadium. Those are things we kind of expected to happen in early season ball games, Shiner head coach Steven Cerny said. We had some players out there (in a varsity game) for the first time. We settled down and the big thing is our defense really stepped up and got the ball back to us. The Comanches fumbled away the football on the second play of the games opening drive. Industrial running back Trenton Thedford picked up 13 yards to the Comanche 24. A few plays later, Shiner recovered a fumble at their 22. On a thirdand-6 play, quarterback Tyler Patek gained 7 yards on a keeper to the 33 and then simply pushed forward on a surge and raced through the defense for a 67-yard touchdown score, giving Shiner a 7-0 lead. Industrial went on a time-consuming drive of 75 yards in nearly seven minutes that turned out to be fruitless. A 19-yard run in the latter stages by fullback Evan Gregg set up Industrial at the 5. Gregg took a toss down to the 3. Thedford took a handoff and got to the 1. Quarterback Jay Rubio was stopped for no gain and Industrial went for on fourth down and did not make it as the Shiner defense stuck together and stuffed him. Shiner drove to just a little past their 36 and stalled despite two offside calls on the Cobras. A bad snap on the punt led to the Cobras get another great scoring chance as they had the ball at the Shiner 11. Two plays went nowhere and on the third one, Rubio was picked off by Ernie Egan. I thought our defense stepping up was the turning point in the game, Cerny said. That bad snap could have been a disaster and given Industrial some momentum but once again defense stepped up. Shiner capped the quick, two-play 75-yard drive as Marcus Coleman took a toss, went outside and was off to the races for a 76yard run to give the Comanches a 14-0 lead with 5:54 to play in the second quarter. Cerny said the offense executed very well overall. We faced a lot of third and long, and all of sudden, we got the big play SHINER, Page B4 By DAVE MUNDY manager@gonzalescannon.com NIXON The mommies in the Nixon stands were starting to gather up small children and shield their eyes so they didnt have to see the bad things happening when the Mustangs ducked into the phone booth and pulled off their Clark Kent glasses. Admittedly, they didnt step out wearing big S on their chests, nor were they able to leap tall buildings at a single bound. But they did a fair job of stopping a fast-moving train. Man, how weird was that? exclaimed NixonSmiley coach Carlton McKinney after his squad dodged a couple of firsthalf bullets, then scored twice in a 20-second span of the third period en route to a 28-14 come-from-behind victory over the Flatonia Bulldogs in Fridays football season opener. Down 6-0 after Flatonia had scored on a 1-yard run by Mitchel Mica on the games opening drive, the Mustang defense frustrated the Bulldogs in the red zone twice in the second period, leading to a 7-6 halftime lead which changed the complexion of the game. After a three-and-out deep in their own territory early in the second, NixonSmiley lined up to punt. Tristan Newmans kick, however, was shanked and thrown right back by a stiff southerly breeze, giving the Bulldogs possession of the ball at the Nixon-Smiley 16-yard line. The punt officially measured negativethree yards. A well-read stop of a Guz Venegas sweep by Mikel Scarborough dropped the Bulldogs back eight yards, and two plays later, Flatonia quarterback Will Bruns was hammered by NixonSmileys Riley Samford as he delivered a pass and the Mustangs Garrett Earlywine snatched the ball to kill the threat. The Nixon-Smiley offense, however, turned the ball back over two plays lat- er, with the Bulldogs Brandon Perez coming up with the recovery at the Mustang 14. A pair of behind-theline stops by Justin Ramos and an illegal-shift penalty later, the Bulldogs lined up for a 39-yard field goal attempt by Jose Manzano only to see Newman sweep in and smother the kick. We had some kids step up and play tonight, McKinney said. They responded when we needed them. The offense made some mistakes, but they responded. The Mustangs followed the blocked kick with a 71yard, 10-play drive capped by a 1-yard sneak from Nick Pea. Eduardo Tovers PAT kick made it a 7-0 game at halftime. The punting nightmare visited Nixon-Smiley to open the second half, however, and the Bulldogs didnt waste the chance a second time. Penalties for an illegal chop block and a personal foul dropped the Mustangs from their own MUSTANGS, Page B4 Honorable Mentions Nate Kowalik, Hallettsville. Was an efficient 12-for-16 passing for 242 yards and two touchdowns. Marcus Coleman, Shiner. Ran for 140 yards and two touchdowns on 12 carries in the Comanches win over Industrial. Trayden Staton, Luling. Threw for 274 yards and two touchdowns on 11-for-21 passing. Tyler Patek, Shiner. Ran for 101 yards and two touchdowns. TreVontae Hights, Yoakum. Ran for 93 yards and two touchdowns in the Bulldogs 25-21 loss to Columbus. Eddie Manzano, Flatonia. Had 16 tackles, including eight solo, in the Bulldogs loss to Nixon-Smiley. T.J. Bell, Shiner St. Paul. Led the Cardinals with 145 yards rushing and a touchdown during their loss to Pettus. Jacob Stafford, Shiner. Had 13 rushes for 132 yards and a score. D.J. Gonzales, Gonzales. Ran for 118 yards and a touchdown on just six carries. Jared Van Auken, NixonSmiley. Rushed for 107 yards and a touchdown in the Mustangs win over Flatonia. Aaron Hunt, Gonzales. The freshman ran eight times for 87 yards and a touchdown in his varsity debut. Jose Contreras, Gonzales. Went a perfect six for six in extra point kick attempts. Page B4 The Cannon Mark Lube The Cannon 14-1 14-1 Shiner Flatonia Nixon-Smiley Cuero Luling Hallettsville TCU Ole Miss Texas A&M Oklahoma Arizona Ohio State Oregon Chiefs Texans Cedric Iglehart Matt Camarillo Gonzales PD 9-6 9-6 Adan Davilla Walmart 9-6 9-6 D&G Automotive Glenn Glass 11-4 11-4 Dane Needham GVTC 7-8 7-8 Shiner Flatonia Yorktown Cuero Luling Hallettsville TCU Texas Texas A&M Oklahoma Arizona Ohio State Oregon Chiefs Texans Caraway Ford 8-7 8-7 Shiner Flatonia Nixon-Smiley Cuero Luling Hallettsville TCU Texas Alabama Oklahoma Arizona Ohio State Oregon Cowboys Texans Bret Hill Christina Jahns Gonz. Livestock Gerard Nuez Sonic 6-9 6-9 Andrew Rodriguez Sleep Inn 8-7 8-7 9-6 9-6 Shiner Flatonia Nixon-Smiley Cuero Blanco Hallettsville Texas Tech Texas Texas A&M Oklahoma UTSA Ohio State Tennessee Cowboys Texans Schulenburg Somerville Yorktown Cuero Luling Hallettsville Texas Tech Texas Texas A&M Oklahoma Arizona Ohio State Oregon Cowboys Texans Shiner Somerville Yorktown Cuero Luling Hallettsville Texas Tech Texas Texas A&M Oklahoma Arizona Ohio State Oregon Cowboys Texans Shiner Flatonia Yorktown Beeville Blanco Hallettsville Texas Tech Texas Texas A&M Oklahoma UTSA California Oregon Cowboys Texans Schulenburg Somerville Yorktown Cuero Luling Hallettsville Texas Tech Texas Texas A&M Oklahoma Arizona Ohio State Oregon Cowboys Texans Shiner Flatonia Nixon-Smiley Cuero Luling Hallettsville TCU Texas Alabama Oklahoma Arizona Ohio State Oregon Cowboys Texans Football Roundup MUSTANGS: Late pick-six Cardinals cant get past Pettus secures season opener Continued from page B3 25 to their own 4, and when another Newman punt came riding the breeze back toward the Mustang goal line, N-S drew a penalty for trying to bat the ball -- setting the Bulldogs up at the Nixon-Smiley 4-yard line. A holding call set Flatonia back, but Bruns responded with a perfect lob into the corner of the end zone to Venegas for an 18-yard pass. A two-point conversion run by Mica put Flatonia on top 14-7. The ball started bouncing the other way midway through the third quarter, however. On the first play following a Mustang punt, Ramos pounced on a Flatonia fumble to set the Ponies up at the Bulldogs 30-yard line. A pass interference call halved the distance, and five plays later Tom Palacio punched it into the end zone to tie the game with 2:01 remaining in the third period. Tovars ensuing kickoff into the wind wasnt intended to be an onside kick, but the ball traveled only 15 yards before bouncing to the ground, where it was alertly picked up by the Mustangs Jordan Martinez and returned to the Bulldogs 45. Two plays later, Jared Van Auken burst up the middle and reached the secondary untouched, racing 34 yards to score and put NixonSmiley back on top. Neither team was able to sustain a drive after that, and after being pinned deep in their own territory late in the contest the Bulldogs risked a fourth-and-15 call from their own 3-yard line. Bruns pass again got held up in the wind and NixonSmileys Samuel Moore turned it into an 18-yard pick-six to seal the deal for the Mustangs. We played terrible, Flatonia head coach Chris Freytag said. Not to take anything away from Nixon, but we deserved better coaching than this. We tried out the no-huddle offense, it worked great in practice but tonight ... there were just too many mistakes. Weve got a lot of improving to do, he said. For McKinney and his Mustangs, the win was a huge morale boost after the frustrations of the last couple of seasons. The big part is the success we had tonight, the enthusiasm that will generate, he said. We made a lot of mistakes. We have to turn that into teaching, and let the kids know that if we clean up those mistakes we can get a lot better. PETTUS The St. Paul Cardinals had nearly 400 yards of offense but could not get past the Pettus Eagles on Friday. Pettus scored first, getting an Anthony Mendoza run in the opening quarter. St. Paul came right back with an 84-yard pass from Austin Barton to Colton Machart. The two-point conversion run failed and left St. Paul down 7-6. Mendoza then caught a 51-yard pass from Matt Gonzales and a 13-6 lead at the end of the quarter. Late in the second, T.J. Bell had a big 40-yard scoring run to put St. Paul ahead 14-13 but Pettus got a score with less than a minute to go with a 31-yard run by John Constante. Gonzales scored on a 1-yard run in the fourth to seal the game for Pettus. Simcik had given the Cardinals a 7-0 lead in the first quarter with a fouryard run. The Bulldogs tied the game with a TreVontae Hights 15-yard run. In the third box, Hights scored on an eight-yard run and later on, Jared Garza caught a 43-yard pass from Chase Hermes. Hights got the two-point run to give Yoakum a 21-7 lead. Detriyon Carter brought Columbus to within 2113 on his 54-yard scoring scamper. Eagles a 31-10 halftime lead. Each team scored two touchdowns in the fourth quarter. Luling got a 10yard and eight-yard scoring runs by Brendon Cubit, Randolph got a 33-yard run by Miguel Rivera and a four-yard scamper by Hosley. Columbus Yoakum 21 25, COLUMBUS The Columbus Cardinals rallied from a 21-13 deficit in the fourth quarter to defeat Yoakum, 25-21. Quarterback Tyson Simcik had a pair of 1-yard touchdown runs in the fourth quarter, with the game-winner coming with 4:47 left to play. UNIVERSAL CITY The Luling Eagles hit the ground running to start the 2013 season with a 4723 win over Universal City Randolph. Luling got two Trayden Staton-to-Taylen Moore touchdown passes of 88 and 26 yards in the first quarter and Brendon Cubit scored on a 17-yard run, also in the first frame. Randolph returned the missed two-point play to trail 19-2 after one quarter. In the second box, Shaft Cubit scored on a 16-yard run for a 25-2 Luling lead. The Ro-Hawks got a touchdown from Christian Hosley on an eight-yard run. Shaft Cubit had a shorter three-yard run to give the GANADO The Hallettsville Brahmas put on offensive show to open the season with a 43-6 win over Ganado on Friday. The Brahmas opened the scoring in the first quarter as Trenton McGee hauled in a 76-yard touchdown pass from Nate Kowalik and Tim Sheppard ran for the two-point conversion. Hallettsville added a second touchdown in the second box as Kaden Hardt scored on a three-yard run for a 15-0 Brahmas lead. The Brahmas put the ball in the end zone four times in the third quarter Dalton Herrington ran a kickoff back 89 yards, caught a 65-yard pass and scored on a 24-yard run. Sheppard capped the Hallettsville scoring with a 15-yard run. The Indians got on the board in the fourth quarter ROUNDUP, Page B5 Shiner running back Jacob Stafford breaks free from the grasp of Industrials Dustin Hempel during last Fridays win over the Cobras. (Photo by Mark Lube) Continued from page B3 to give us a third down, he said. Industrial punted on their next drive and Shiner had 3:21 and 78 yards to score. They got down to the 18 of Industrial, helped by a 14-yard run by Coleman, a facemask call on the same play and a 22yard run by Jacob Stafford. With just a few seconds left, Shiner missed a 35-yard field goal by Rigo Baray to end the half. To open the third box, the Shiner defense held Gregg to a 3-yard run and then sacked Rubio twice. The Cobras had a 17-yard punt into the wind to give Shiner the ball at the 37. Stafford took a handoff, seemed to disappear into a pile, stumbled, kept his balance and finished off a 37yard touchdown run to give Shiner a 21-0 lead with 9:31 to go in the third. The teams exchanged a series of punts until the Comanches had a short field to run after a 22-yard punt by Industrial. At the Cobra 30, Stafford had a run of 5 yards and then an 8-yard rush to the 17. Patek repeated his feat from earlier and scored on a 17-yard sneak. Industrial blocked the point after for a 27-0 Shiner advantage. The Cobras had their next drive start at their 27. Rubio had a couple of good passes 13 yards to Gregg to the 42, 9 yards to Cade Peterek and a pass to Gregg for 15, eventually bringing the Cobras to the Shiner 30. Tyler Conrad hauled in a fourth-down catch for 5 yards but was 4 yards shy of the marker. The Comanches then put the icing on the cake with a 14-play, 75-yard drive in just under six minutes, capping the drive with a 4-yard run by Coleman and a 34-0 advantage. when Cameron Williams took the ball on a reverse during the ensuing kick return and ran 77 yards to whittle the Gonzales lead down to 19-6. Early in the second quarter, Philippus pushed the Apaches out to the near midfield on a dive. On the next play, Ramirez came through a gaping hole in the middle and broke up the left sideline for a 39yard touchdown. Undaunted, the Titans got another quick strike after returning the ball out to their 25. Ortega dropped to pass, made a man miss in the backfield, reversed his direction and raced 75 yards for a score. James looked as if he was going to score when he returned the ensuing kickoff from the Apache 19, but the speedy lost the handle on the football and it rolled out of bounds at the Gonzales 45. Seven plays later, Ramirez powered in from five yards out to cap the drive. On the next possession, the elusive Ortega showed that he still had more to pull from his bag of his tricks. Facing third and nine, he rolled to his left, went back to his right and was in the end zone 64 yards later. Kelsey Ferrys extra point kick would be the last points of the game for Victoria East with 4:32 left to play in the first half. Gonzales would run out most of the clock by using a 10-play, 64-yard drive that culminated in Philippus touchdown run. The second half was all Apaches, all the time. Ramirez ended their first possession with a two-yard plunge and later in the quarter, Tellez broke off a strong run for a 15-yard score. On the Titans next possession, Airhart put a bonejarring hit on Ortega, who lost the ball and it was recovered by J.T. Miller at the Gonzales 43. Aaron Hunt gained nine yards on first down and then did something special on the next carry. He managed to squirt through a small crease and blazed his way into the end zone as the entire Apache sideline erupted in amazement. Contreras converted his sixth extra point kick in as many tries to end the games scoring with 1:58 left in the third quarter. The only sour note of the night for Gonzales came when Filla failed to rise to his feet after a play early in the fourth quarter. The senior standout had to be helped to his feet and taken off the field via golf cart. No immediate word was given regarding the nature of his injury. The Cannon Page B5 CYFL Roundup Marques Washington and Dylan Rodriguez find a cool spot while anxiously waiting to face Goliad. The Senior Apache Black won the game 18-0. (Courtesy photo) Cade Davis runs past the Yorktown defense during this touchdown last Saturday. (Photo by Cedric Iglehart) Blue turned back Gonzales Black, 27-0; Goliad took care of Hallettsville, 34-6; and Cuero lost to Yoakum Silver, 7-6. Chrisean White looks for a seam in Gonzales Sophomore Blacks game against Cuero on Saturday. (Photo by Mark Lube) Mason Navejar (34) makes a defensive play Saturday morning at the Gonzales High School practice field during Gonzales Sophomore Black 13-0 win over Cuero. (Photo by Mark Lube) The team (above) of Tom Sudderth, Rutt, Glenna Kessler, David Hernandez and Bill Kessler came in first place at the Wednesday Night Scramble held August 28 at Independence Park Golf Course in Gonzales. The members of the second place team (below) were Jay Windham, Mark Turney, Dustin Ford and Ron Pekar. Not pictured are Jeremy and Jonathon Parsons. (Courtesy photos) Avram Almaguer (46) and Alejandro Reyna (all white) combine to make this stop on a Yorktown ball carrier. (Photo by Cedric Iglehart) with a seven-yard pass from Ray Salazar to Kameron Smith. Kowalik completed 11of-15 for 232 yards and two touchdowns with Herrington hauling five catches for 104 yards. Brent Motal led Hallettsville on the ground with 93 yards on 11 carries. HALLETTSVILLE The Sacred Heart Indians and Yorktown fought to a 22-22 tie until the fourth quarter when Yorktowns Steven Perez scored on a one-yard run right at the end of the game for the difference. Sacred Hearts Jonathan Vanek returned the opening kickoff 79 yards for a touchdown and Yorktown later came back with a Logan Roman three-yard run and Perezs two-point run for an 8-6 lead. The Indians retook the lead before the end of the frame as Dylan Jahn scored from 27 yards out and Trent Janak hauled in two-point pass from Scott Stoner. Next score for Yorktown was a Jonathan Weischwell five-yard run with Roman getting the two-point conversion. Sacred Heart went ahead 22-16 on the two-yard plunge from Kyle Pettus and Jahn caught a twopoint pass from Stoner. The Wildcats knotted the game before halftime on the 42-yard run by Caleb Schendel, but the twopoint conversion failed. WHARTON Down 23-9 to start the fourth quarter, the Cuero Gobblers scored two touchdowns but missed an extra point, allowing Wharton to escape with a 23-22 win. The Gobblers got a 14yard run from DAnthony Hopkins, who finished as the games leading rusher with 142 yards on 20 carries. Tristan Barefield caught a four-yard touchdown pass but the gametying extra point was no good. The Tigers opened the scoring in the first box with a 27-yard field goal and got two touchdowns directly from turnovers. Taylor Skinner returned an interception 42 yards for a touchdown and Wharton later recovered a fumble in the end zone. Cuero later got a safety in the first quarter. The Gobblers cut Whartons lead to 16-9 in the second frame on the 13-yard run by Zach Hopkins. The Tigers went ahead by two scores in the third quarter with a 15-yard run by Toney Rogers. Gonzales cross country runners (from left) Max Moreno, Valeria Aguayo, and Ashton Williams show off the medals they earned at the Lockhart Meet last weekend. (Courtesy photo) From coaches reports cause she has put in a ton of Doyle said. It was a relaywork this summer and de- style meet and I mixed up The Gonzales cross served to run well, Doyle our kids randomly. I becountry teams ran in the said. lieve early in the year our Lockhart meet on Saturday. For the boys, Ashton kids need to learn to run This was our first cross Williams came in at No. 11 with different teammates country meet outside of and Max Moreno was at and it has always paid off the relay meet we hosted, No. 14. late in the season. Gonzales head coach Cully Gonzales is back in acBoth the Gonzales girls Doyle said. This meet was tion on Sept. 13 when they and boys team will not have important so the runners travel to Pflugerville. a full squad of runners uncould find out where they The Gonzales girls and til about the third or fourth are and we could determine boys cross country teams meet of the season. where we need to go by started off the 2013 season We are still getting in Oct. 23 when our district with the Gonzales Relays shape for some runners meet is. held in Independence Park andgetting in better racing Valeria Aguayo had a top on Aug. 24. shape for the ones that have 20 finish, placing No. 17. I was impressed with the been out most all summer, I was proud of her be- meet and how the kidsran, Doyle said. Page B6 The Cannon EFFECTIVE NOW: ALL FREE ADS WILL RUN FOR 4 WEEKS AND THEN BE CANCELLED. IF YOU WANT THEM TO RUN ANY MORE AFTER THAT THERE WILL BE A TWO WEEK WAITING PERIOD TO GET BACK IN. EFFECTIVE NOW ALL SERVICE ADS WILL START BEING CHARGED FOR. FOR 25 WORDS OR LESS IT WILL BE $5.00 A WEEK; ANYTHING OVER 25 WORDS IT WILL BE AN ADDITIONAL .25 CENTS PER WORD. HELP WANTED CDL employees. Requirements: 2 years experience tanker and must be willing to get HazMat endorsement ASAP. Call 830-672-8000. -------------------------AVON Representatives Wanted! Great earning opportunities! Buy or Sell! Call 830-672-2271, Independent Sales Rep. NOTICES Horsemanship Clinics. September 12, October 5, November 2-3, November 16-17. Held in Gonzales. For information go to www. knptraining.com. 361-648-1055. (1114-13) ------------------------7327. GARAGE SALES. LEGAL NOTICES LEGAL NOTICES LEGAL NOTICES LEGAL NOTICES LEGAL NOTICES Gonzales County Commissioners Court Amended Proposed Salary Increases for Elected Officials For Fiscal Year 2013-2014 Pursuant to the Texas Local Government Code, Section 152.013, notice is hereby given that the Gonzales County Commissioners Court will meet at the Courthouse on Monday, the 16th of September, at 9:00 a.m. The Commissioners Court shall consider a proposal to raise the annual salaries of the Gonzales County elected officials, to become effective on October 1, 2013, as follows: Salary Longevity HELP WANTED Now Hiring. Qualified CDL drivers. Calll 830-875-5011 for information. Luling Oil & Gas, LLC. Oilfield Services, 1237 Hoover Ln., Luling, Texas 78648. -------------------------Part-time Director of Music Ministries Needed - First United Methodist Church in Gonzales, TX. Competitive and generous salary. Primary responsibility is overseeing music for two Sunday morning services as well as developing and promoting the overall music ministry for the church. Inquiries may contact Rev. Andy Smith at (830) 6728521 or revasmith@ gvec.net.(9-26-13) -------------------------CNH Paving is seeking professional & reliable class A CDL Drivers. Hauling belly dumps and home every night. Located in the Waelder area. For more info, call: 830540-3377. -------------------------Mechanic Needed. Must have own tools, experience necessary with car diagnostic vehicles. Come by West Motors, 1701 Sarah DeWitt Dr. for application & bring resume. -------------------------CDL DRIVERS WANTED J.M. Oilfield Service, a family oriented company is seeking professional & reliable Class A Edwin Parker VS Tony Perez 45.312 acre tract of land, more or less, out of the EZELIEL W. CULLEN LEAGUE, ABSTRACT NO. 148, Gonzales County Texas as described by metes 7/29/2013 and bounds in exhibit a attached hereto and made part of hereof LESS AND 8/19/2013 EXCEPT THAT CERTAIN 4.13 ACRES OF DESCRIBED IN EXHIBIT B vol 1103 page 067-068 The Minimum Bid Is All Costs Of Suit And Sale. Published In The SALE TO BE HELD 1 day of October, 2013 Between the hours of 10:00 AM and 4:00 PM Gonzales County Courthouse Southeast Steps Terms: Cash, Cashiers Check, Money order Additional Terms: ADJUDGED MARKET VALUE $207,930 John Moreno, Constable Gonzales County Pct. 4 P.O. Box 366 Smiley, Texas 78159 (830) 582-1292 By: Deputy The Cannon Page b7 CLASSIFIEDS MISC. FOR SALE 5.0 Chest type freezer, 2 TVs, 1 19, 1 - 25, 3 infant car seats. Excellent Condition. Call 830- FIREWOOD MESQUITE BBQ WOOD FOR SALE in Gonzales County. All sizes and shapes, ready to use. (830) 672-6265. -------------------------Firewood: Pickup load is $60.00. If you haul. Delivered is $85. Call: 830-5404430. FURNITURE mattresses. Good condition, washer/ dryer, never been used, Whirlpool, High table, ceramic, w/4 chairs. Loveseat, cloth, 3 tvs, 19, 25 and 32, color, white microwave cart with 2 drawers on bottom, recliner, cloth new conventional toaster, broiler, white day bed w/trundle bed, both mattresses, white childs desk, chair, leather with foot rest. 830-2038977, text or call. -------------------------3 latex mattress topper. Queen size. Like new, paid . AUTOS CTS Cadillac, 4-door, V-6. Brand new tires and chrome wheels. $8,800 firm. Call 830672-1106, leave message if no answer. ------------------------30540. -------------------------For Sale: 2001 Chevrolet Silverado 1500 - $7,500. 2nd owner pickup with low miles, cold A/C, spray-in bed liner, grill guard, towing package and more! Call Lauren at (361) 648-5049 for more info. HELP WANTED HELP WANTED HELP WANTED You need a high school diploma or GED and the ability to: Learn operation of plant processing equipment Work 12-hour shifts, night shift Learn to drive a forklift Demonstrate communication skills, initiative and judgment in problem-solving Work safely, following rules and procedures Lift up to 55 lbs on a frequent basis FARM EQUIPMENT Single round bale trailer, hand crank. $200. 437-2046. -------------------------Round bale carrier for 3 pt. hitch. $150. Call 437-2046. -------------------------D4H Dozer. Serial Number S/N2AC591, 6 way blade. EROPS with AC. Forrestry package on cab, engine enclosures. Rear Winch. $40,000 Firm. 830540-4301. -------------------------2009 Kuhn Knight model 1130 manure spreader for sale. Used for only 3 cleanouts. Very good condition. $12,000. 857-5446. -------------------------For Sale: Farmall 504. $3,000. Work, 361-596-4911; Home, 361-5967. LEGAL NOTICES LEGAL NOTICES LEGAL NOTICES LEGAL NOTICES AUTOS Suzuki Japanese mini truck. 35,450 miles, spray lined bed, lifted, 4x4. Needs some attention to fuel intake, but should be easy fix. Great for ranch or hunting. $2,000. 361-771-5483. -------------------------1982 Continental Lincoln Mark VI. Buckskin top, gold bottom, $2,995. Only serious buyers call Pat Kelly Logan, 830-672-2542. -------------------------For Sale: 5 16 steel jeep rims, one with brand new Goodyear Wrangler tire, P220R70/16. Will sell whole set for $100 . Or if you just want the tire off the rim, tire will be $25. Call 830-203-9408. -------------------------98 GMC 3/4 ton, 4x4, auto., pickup truck, with extended cab. 830-8574242. -------------------------2004 Nissan Altima, 3.5, 6 cyl, AC, Auto trans., power, cruise, gray metallic w/gray interior. One owner. $6,500. 830540-3382. --------------------------------------- FURNITURE For Sale. Antique beds. Come out of old Alcalde Hotel. Pretty good shape for age. Still looks good. $100 a piece. 512-292-0070. -------------------------Piano small upright. Excellent condition. $500. Shiner, 361594-2318. -------------------------Southwestern Kingsize bed w/complete boxsprings & ADVERTISEMENT FOR BIDS CITY OF GONZALES GONZALES, TEXAS STREET REPAIRS TO ST. VINCENT, ST. PAUL, ST. ANDREW AND CHURCH STREETS Separate sealed bids addressed to the City of Gonzales (OWNER) clearly labeled STREET REPAIRS TO ST. VINCENT, ST. PAUL, ST. ANDREW AND CHURCH STREETS, ATTN: CITY SECRETARY will be received at Gonzales City Hall, 820 St. Joseph Street, Gonzales, Texas 78629, until 2:00 oclock p.m. on Thursday, September 19, 2013, and then publicly opened and read aloud immediately. This project includes the installation of approximately 43,400 square yards of single course surface treatment over reclaimed street repair areas, and 93,000 square yards of single course surface treatment for entire widths and lengths of streets. Alternate bids for 93,000 square yards of 1-1/2 inch HMAC overlay are also being considered. The project will most likely be completed in four different phases, one phase per street, over a twelve month period. 200, Gonzales, Texas 78629, (830) 672-1205. Plans, Specifications, and Contract Documents may be examined and purchased for a non-refundable fee of $40.00 at this location. Each bid shall be accompanied by a cashiers check or certified check upon a national or state bank in an amount not less than five percent (5%) of the total actual bid price payable without recourse to the City of Gonzales, or a bid bond in the same amount from a reliable surety company as a guarantee that the bidder will enter into a contract and execute required performance and payment bonds. The contract shall be awarded to the lowest responsible bidder; however, the right is reserved, as the interests of the OWNER may require, to reject any and all bids, and to waive any informality or minor defects in bids received. Bids may be held by the 200, Gonzales, Texas 78629, (830) 672-1205, by 5:00 oclock p.m., Monday, September 16th. HELP WANTED Duzy Oliver is looking for employees who would like to work on the Coffee Roasting process. We need your help from Monday to Friday, 8:30 a.m. to 3:30 p.m. If you are interested, please contact: Duzy Oliver LLC, 361-9608308, duzy_oliver@hotmail.com or Help Wanted MOBILE HOMES Belmont RV Park. We have FEMA trailers for sale. From $2,500 & up or rent to own. Please call 830-4243600. -------------------------We Buy or Trade for Used Homes. Fayette Country Homes, Schulenburg, 800369-6888. Open Sundays 1-6. (RBI 32896). -------------------------Used, Repos, Tradeins - If it needed something replaced or painted we did it. Save Thusands. Visit our Web Site. Tierraverdehomes. com. Fayette Country Homes, 800-3696888. Open till 6pm - 7 days a week. Sunday 1-6. (RBI 32896). -------------------------New! 28x56 Loaded, Thermo windows, Total R-60 insulation. 3 bedroom, 2 bath. Delivered, set, A/C. If ordered by Nov. 30th, $49,900.00. Fayette Country Homes, 830369-6888. Open till 6pm - 7 days a week. Sunday 1-6. (RBI 32896) HELP WANTED Is seeking an experienced accounting person for the Position of: Assistant Treasurer/Accounts Payable Clerk (Salary Range is from $14.57 to $16.57 per hour) Assistant Treasurer/Accounts Payable person needed. This is a full-time position. Applicant must be able to handle a heavy workload, be able to work under pressure, handle deadlines, pay strict attention to detail, and have strong accounting skills. Applicant is required to be a very organized and detailed oriented person. Position requires strong bookkeeping skills including the ability to reconcile complex Vendor statements, Bank reconciliations and General Ledger. Must be bondable as according to Local Government Code Section 83.002. Essential skills: ten-key by touch, computer aptitude, general office skills, well organized, and phone etiquette.General office duties to include: answering phones, data entry, filing, copying, and other duties assigned. Applications may be obtained at the Gonzales County Treasurers Office, located at 414 N. St. Joseph, Suite 202, or the Human Resources Department located at 414 N. Saint Joseph, Suite 104, Gonzales between the hours of 8am and 4pm or on the web at. Only completed applications will be considered. Applications received by September 23, 2013. A drug and alcohol screen test will be required. Gonzales County does not discriminate on the basis of race, color, national origin, sex, religion, age and handicap status in employment or the provision of services. EOE. Page B8 CLASSIFIEDS HOMES FOR RENT $1,200 Security Deposit. Contact Monica with RE/MAX Professional Realty,s bedroom-820-5461. -------------------------Charming 1/1 home on 2 wooded acs, w/lrg. deck in country, 77 North, paved road. $775/ mo. No pets/smokers. 512-415-6483. -------------------------For Rent: 2BR/2BA/2CG home on 183 N. $1,250/ mo., plus deposit. Call 830-857-4458 for information. -------------------------Motel Suites. 2 bedrooms, full kitchen, The Cannon HOME SERVICES me to. Can stay Friday night, Saturday night but must be home by Sunday at 3:00. Call 830-5193044. -------------------------Sitting at night taking care of elderly in their home. References, transportation. Call 361-2128731. -------------------------Need personal service? Will clean oilfield campers, homes and apartments. Also offer laundry work, ironing and running your personal errands. If you need a pair of jeans or shirt ironed for the night out or last minute event and didnt make it to the cleaners in time, give me a call (830) 203-0716. References. Available. -------------------------House cleaning services available. Reasonable rates. Servicing Gonzales and surrounding areas. References available. Call Barbara at 979-7778710 or email barbarajp30@hotmail. com. -------------------------In Home Appliance Repair. Washer, Dryers, all major appliances, 30 years experience. Haul Scrap Metal & appliances. Call Larry at 361-596-4391. ------------------------. -------------------------I am looking for a private setting job around Gonzales, Cost or on 1116 (Pilgrim Road). I have 20 years experience. Please call Emily, 830-4372727; Cell, 820-2632768. -------------------------Will do house cleaning Monday thru Friday. Call 830203-0735. -------------------------Sewing & Alterations. Jo West. 830-203-5160. Call between 9 a.m. & 9 p.m. CHILD CARE more information, 263-2789. -------------------------Will do child care in my home. Includes meals. Any age (Infants onup). Have one opening available in August. Call 830-519-3044. ------------------------. RV SITES RENT Six RV Hookups for long term lease at Harwood. Intersection of Hwy. 90 and TX 304. Contact: 281-788-7500. Thanks for Your Support! HELP WANTED HELP WANTED Competitive Pay...$9.50-$12.00/hr. (with weekly perfect attendance) Human Resources 603 W. Central, Hwy. 87, Nixon, Texas 830-582-1619 for more information. ~ Se Habla Espanol FOR LEASE) Benefits include: WANT TO RENT Looking for a 2 or 3BR nice house in Nixon and Leesville area. Call 830-8571658. -------------------------Looking for a nice house in or near Gonzales. 940-2844255. NOW HIRING HELP WANTED 830-672-7573 HOME SERVICES Looking for sitting job for a sweet lady in her home. Includes cooking and will drive for her if she needs CHILD CARE Teenager looking to babysit part-time, infants & small children. Will take care of at your home or my home. Call for HELP WANTED HELP WANTED HELP WANTED HELP WANTED HELP WANTED Hatchery: Successful candidate must be experienced as diesel mechanic or truck maintenance and willing to work on a variety of projects involving general facility maintenance. We offer a competitive wage based on talent and experience along with 401K, Vacation, Medical, Dental, Vision and Life Insurance. Kitchen Pride Mushroom Farms, Inc Apply at Mechanic/Maintenance Position Human Resources 603 W. Central, Hwy. 87, Nixon, Texas 830-582-1619 for more information. ~ Se Habla Espanol The Cannon Page b9 CLASSIFIEDS RV SITES RENT 2 RV spaces in town. $295/mo., 1 Mobile home space for rent, $175/mo. Call Finch Park, 6722955. -------------------------RV Sites Available. Nixon, TX. Clean, quiet, fair prices. 830-857-6921. LIVESTOCK Fancy Feathers Bantams. Feather Duster Roos. Colors, pairs, $20. Will deliver to Gonzales. 512-272-5147. ------------------------) -------------------------For Sale: Registered Polled Hereford Bulls. 8-22 mths old. Heifers also, 8 months to 2 years. 830-540-4430. -------------------------WANT TO BUY: Any or Unwanted Horses. Call Leejay at 830-857-3866. ------------------------- LIVESTOCK 672-6265, 830-8574251. REAL ESTATE ances, remodeled, new master bath. 830-857-6488. -------------------------House for Sale/To Be Moved: 3BR/1Ba frame house, pier & beam foundation, central A/H. Buyer responsible for moving house from property, $6,000. 830-857-4172. WANTED Im looking for a 1959 GISD yearbook. Call Jimmy at 361-571-6888. REAL ESTATE REAL ESTATE REAL ESTATE REAL ESTATE House for Sale. Beautiful Historic home for sale. 713 St. John. Give me a call if interested. 713-425-9345. -------------------------Wonderful Spanish style house on 20.59 acres with 2 ponds, 7 horse stalls, 2 storage barns and other outbuildings. Can be viewed at www. littlefieldproperties. com id #79040. Call Tanya (broker) at 361-865-2563. ------------------------. -------------------------Older couple downsizing 15 acres (10 acres fenced), house, 3/1 1/2, Barn, ponds, trees. Wharton County. $137,000. 979-5333262. -------------------------4BR/2BA, 1900 Sq. ft. 210 Tanglewood Trail. New appli-! Its Easy! Choose from a Cooking Show, Catalog Show, Facebook Show or if you need an item, here is my site, https:// w w w.pamperedchef.biz/zavadil. Dee Zavadil, 830857-1495. -------------------------Lucky Shots by Dee. Need Family Portraits, Family Reunions, Birthdays, School Pictures, Weddings, Etc. 830857-1495 -------------------------Plumbing Repairs. All Types of Plumbing. Master Plumber. Reasonable Rates. Please Call 713203-2814 or 281415-6108. License #M18337 -------------------------No Limit Accessories David Matias, Owner 830-263-1633 1026 St. Paul St., Gonzales Window Tinting, Commercial. Call for appointment. 18 AC - 5224 Sandy Fork Rd, Harwood - 3BD/2BA home perfect for the country getaway! 2 car detached garage, 30x40 run-in shed. Large tank, fully fenced. Mature trees. $244,500. cleared and wooded. 14 AC - 1491 Highsmith Rd, Luling - Partially 830-875-5866 3BD/2BA home with stained concrete and additional living/bonus room. Detached storage Residential building. 347 CR 388, Gonzales County - NEW LISTING - Great location of Hwy. 97 between Gonzales and Waelder! Located on 7 acres, this property features a 4BD/2BA home with large kitchen open to living and dining. Large workshop on slap features 2 rollup doors and restroom. Offered at $179,500. 4728 CR 283, Harwood - NEW LISTING - Custom 3BD/2BA home on approx. 22.9 wooded acres great for recreation and hunting! Split floorplan with spacious great room. Upgrades! Tile, Custom kitchen, Granite counters. Detached shed, partially fenced. REDUCED $315,000. 215 S Oak - Large, 3 BD/2.5 BA home located on half of a city block for 0.7 acre! Large den and formal dining areas feature 2 wood burning fireplaces. Upstairs features private entrance for income producing space if desired. Open lot to enjoy garden, pool, or build income producing structure. REDUCED $209,500. 960 S. Pecan - Modern, custom 4BD/3BA secluded home on 1 acre home on 1 acre backs to wet weather creek. Open floor plan, security and surround wired. REDUCED $336,500. $338,000. $340,000. FORECLOSURE - The Settlement at Patriot Ranch - 2BD/2BA Main Home on 3 AC - 473 Crockett Lane - views offered with this 2BD/2BA main home and detached efficiency guesthouse. 2 car carport. REDUCED $226,000. $239,000. Settlement at Patriot Ranch - 3-27 acre site built home sites. Beautiful countryside and wildlife views. Electricity available. Paved roads, well/septic required. 79.5 AC CR 281, Harwood - Partially wooded and cleared land with partial fencing. Co-op water and electricity available. 1 tank and hand dug well. Country Road frontage on 2 sides. $360,000. RV Park - 10.5 AC - Great location just off IH-10, mature trees and nice tank. Site has been engineered for 54 unit RV Park. 43 AC - 2198 Sandy Branch Rd., Harwood - Secluded with partial high fence, large tank, rustic cabin. Beautiful views. REDUCED $266,600. 111 Acres, Creek Rd - Dripping Springs - Scenic property offers partially cleared and wooded land located on high bluff with Onion Creek frontage. Minerals convey. $1,900,000. LAND 70 Acres - For Sale by owner. FM 443. Outside of Hochheim/Dryer area. 210-867-8851. -------------------------17+ acres of cleared land with good fence. Perfect for homesite. 830-8574242. -------------------------Lots for Lease. Conveniently located behind WHS (Waelder High School). For information call 512299-1627. ------------------------. MOTORCYCLES Gruene Harley-Davidson is currently buying pre-owned Harleys. Looking to sell youR Harley? Call Jon Camareno at 830-624-2473. RECREATION 2006 Land Prides 4x4 Recreational Vehicle For Sale. Approx. 200 hours. Honda Motor. Independent Suspension. Windshield and Roof. 4x4. Asking - $4,950.00 in very good condition. Call 830-8574670. Land PETS FREE: 1/2 Bassett, 1/2 Catahoula puppies. 8 weeks old, vet checked. 830857-4868. -------------------------Chihuahuas for sale. 1 male, 3 female. 830-491-1856 or 830-263-2094. -------------------------ANUE Pet Grooming. 7 days a week. Hand/Scissor Cut. Small, $20 & $30; Medium, $35 & $40; Medium/Large, $45. Ask for Susan. 361-258-1505. HUNTING LEASES 5 experienced hunters looking for at least 800+ acres for hunting in Westhoff area. Bill Cain, 281-684-0165. REAL ESTATE REAL ESTATE vTHOMPSONVILLE 5641 Hwy. 90, 2 bedroom, 3 bath, interior recently painted, tile floors, SOLD loam, stock tank. Great for horses. Metal barn appx. 30x. HOMES LIVESTOCK Free Donkeys. 361772-7655 after 6 p.m. -------------------------2006 Blue Roan handcock mare. 14 hands. Stocky built. Has worked cows, arena roping. Pastured for 1 year. Needs to go to work. $1,200. 361771-5483. -------------------------For Sale: Black & Red Brangus Bulls. 2 & 3 yrs. old. Good selection. No papers. 830-437-5772. (9-19-13) -------------------------Rabbits for Sale. With cages, with feeders & waterers. all for $300. 361741-2604. -------------------------Brangus Bulls for Sale. 1-2 yr. old, 3-18 mos., 3-7 mos. Leesville. 281-3829820. -------------------------Angus Bull for sale. Registered JBarB. 3 1/2 yr.old herd bull. $2,975. 361-7986250. -------------------------Bulls for Sale. Black Angus and Black Limousin. Breeding ages. Gentle. Delivery available. 979263-5829. ------------------------. -------------------------- Brick ACREAGE RV-SITES Refurbished 28ft BPull TTs $6,850. New Upholstery & Bedding. Like New Many with New Appliances Financing 979-743-1514 or 800-369-6888 APTS. FOR RENT. EFFICIENCY APARTMENTS FOR THE ELDERLY 62 OR OLDER AVAILABLE IMMEDIATELY * Rent based on income * Garden Style Apartments * Private Entrances * Individual Flower Bed Available * Carpeted & Air Conditioned * Water, Sewer & Trash Paid * Miniblinds, Ceiling Fan, Range, Refrigerator furnished * Maintenance/Management/Service Coordinator on site 3.7 ACS. 4BR, 3BA, 2LV.................. $150,000 New on Mkt, neat 3 bd. ..........$89,000 3BR, 1 Bath................ $65,000 306 McClure Rivercrest Super home, 4 bds......... 1618 St. Peter Home and extra lot.... $70,000 ............................................$165,000 473 Crocketthome Lane-Settlement - 3....... bd., Rivercrest 3,600 +sq. ft., beautiful property.................................. $258,000 ............................ $255,000.$197,000 1.66Water acs., St riverfront, nice M/H.......... 1602 .-commercial/rental.... $150,000 SALE PENDING ............................................ $115,000 2342 FM 108, 3 bd.,2 story home..... $145,000 Land 792 90-B - Lakefront.............................. $89,000 51 acs., royalties, private, utilities, .... 312 Cr. Rd. 471, Lakefront + ,3 bd., ........................................... $5,500/ac 1.5 acre lot............................................ $150,000 90 A East, 35 Land acs., + home.............. ............................................ $395,000 11.2 acs., Hwy 90. Gast RdCT .......$5,300/Ac. NTRA CO CT NTRA CO CR 228 - 15 acs., M/H, trees................ $87,500 Shirley Breitschopf 153 acs., FM 2091.........................$795,000 830-857-4142 homesite.................$4,990/Ac. 61 acs., perfect Lynnette Cooper 3.94 acs., Settlement....................... $65,000 lynnette@gonzalesproperties.com 10 acs., Settlement.........................$79,000 Carol Hardcastle 2-4 acs., Sarah DeWitt ............$25,000/Ac. 1 ac. Seydler830-857-3517 St...............................$25,000 8.7 You acs.,can cityreach limitsour ....................... .$120,000 staff by calling: 58 Phone: acs., trees, potential, edge of town ............. 830-672-2522 ...................................................$12,000/Ac. COMMERCIAL Call 672-7100 to place your free classified ads! REAL ESTATE REAL ESTATE 70 Acres. Yorktown/Goliad. Great building sites. Live oaks, brush, hay field. Water wells. Some minerals. $5,500/acres. ~~~~~~~~~~~~~~~~~~ 106 Acres. Rockport. Minutes to water, fine dining. Good oaks, coastal bermuda. Nice home plus modular home. Some minerals. $1,400,000. ~~~~~~~~~~~~~~~~~~/implements. Mostly Mesquite. $250,000. ~~~~~~~~~~~~~~~~~~ 68 Acres. South Cuero. Oaks, brush, hay field. Pens, well. Crossfenced. $5,300/ac. ~~~~~~~~~~~~~~~~~~. Lot - Live Oak..................................$8,000 401 St. George-approx. 3400 sq. ft................. .......................................................$170,000 Shirley Breitschopf 20.29 ACRES, Rocksprings. behind locked SAFE TUBS TexSCAN Week of gate. Electricity, gently rolling with live oaks, SAFE STEP WALK-IN TUB Alert for seniors, shirley@gonzalesproperties.com September 1, 2013 exotics. $2,937 down, $535/month, (9.9%, bathroom falls can be fatal. Approved by 20 years) or TX Vet nancing. 1-800-876DRIVERS Lynnette Cooper Arthritis Foundation. Therapeutic jets with 9720.. ATTENTION DEDICATED and regional less than 4 inch step-in. Wide door, anti-slip lynnette@gonzalesproperties.com drivers. Averitt offers excellent benets and oors, American made, installation included. $106 MONTH BUYS land for RV, MH or cabin. Gated entry, $690 down, hometime. CDL-A required 1-888-362-8608. Call 1-888-960-2587 for $750 Off. Carol Hardcastle - 830-857-3517 ($6900/10.91%/7yr) 90-days same as cash, Recent grads with a CDL-A, paid training. TECHNICAL TRAINING Guaranteed nancing, 1-936-377-3235 Jymmy Davis - 512-921-8877 Apply online K. at AverittCareers.com, EOE AIRLINE CAREERS begin here. Become approved training.Financial aid if qualified. monthly. 291.25 acres, $85,918, $4300 per mile! New eet Volvo tractors! 1-year Housing available, job placement assistance. down, $781.90 monthly. 210-734-4009. OTR Experience required. Tanker training Call Aviation Institute of Maintenance. Dallas:1-. available. Call Today: 1-877-882-6537; www. 800-475-4102 or Houston: 1-800-743-1392 OakleyTransport.com STEEL BUILDINGS DRIVERS - TANGO TRANSPORT now hiring company drivers and owner operators. Excellent home-time. 401k. Family medical/dental. Paid vacations. Apply online at or phone 1-877-826-4605 Commercial WEST TEXAS, south of Sanderson, 177.89 DRIVERS - HIRING EXPERIENCED /INEXOur friendly staff can be reached by: an Aviation Maintenance Technician. FAA acres, $47,140, $2370 down, $431.48 PERIENCED Tanker drivers! Earn up to 51 HELP WANTED 830-672-8668 All real estate advertising in this newspaper is subject to the Fair Housing Act which makes it illegal to advertise any preference, limitation or discrimination based on race, color, religion, sex, handicap, familial status or national origin, or an intention279275. STEEL BUILDINGS Blow out! Best savings on remaining clearance buildings. Garages, shelters, homes, 20x22, 25x30, 30x40, 35x56 and 40x70. Make offer and low payments. Call Ashley at 1-800-991-9251. REAL ESTATE PA I D C D L Tr a i n i n g ! N o e x p e r i e n c e needed. Stevens Transport will sponsor the cost of your CDL training. Earn up to $40K first year and $70K third year. Excellent benefits, 1-888-726-4130, www. ACREAGE REPO with septic tank, pool, becomeadriver.com. EOE pier, ramp. Owner finance. Granbury PARTNERS IN EXCELLENCE OTR driv- 1-210-422-3013 ers APU equipped, pre-pass, EZ-pass, AFFORDABLE RESORT LIVING on Lake passenger policy. 2012 and newer equipFork. RV and manufactured housing OK! Guarment. 100% NO touch. Butler Transport anteed nancing with 10% down. Lots starting 1-800-528-7825 as low as $6900. Call Josh, 1-903-878-7265 ABSOLUTELY THE BEST VIEW Lake Medina/Bandera, 1/4 acre tract, central W/S/E, RV, M/H or house OK only $830 down, $235 month (12.91%/10yr), Guaranteed nancing, more information call 1-830-460-8354 Run Your Ad In TexSCAN! Statewide Ad .................. $550 North Region Only ...... $250 South Region Only ..... $250 West Region Only ....... $250 96 Newspapers, 211,716 Circulation 100 Newspapers, 391,741 Circulation 94 Newspapers, 301,619 Circulation 290 Newspapers, 905,076 Classied Ad Network. Page B10 The Cannon Sale Every Saturday at 10 a.m. Working hard to insure quality service for all our customers. Loans Up to $1,300.00 830-672-6556 1-888-562-6588 506 St. Paul., Gonzales, TX. 78629 Serving Texas for over 40 Years! Bags of Ice 830-672-3447 830-672-5599 BY CHOICE HOTELS 2138 Water Street/Hwy. 183, Gonzales, Texas 78629 Phone 830.672.1888 Fax 830.672.1884 Store Manager Store 0290 1620 N. Sarah DeWitt Dr. Gonzales, Tx. 78629 T 830.672.7573 F 830.672.7752 Adan Davila (830) 672-9581 Duane & Tina Zumwalt 178 CR 281 P.O. Box 63 Harwood, TX 78632 Office (830) 540-4208 Fax (830) 540-4203 Cell (830) 857-4556 Email: dntwrecker@gvtc.com 672-1554 830-672-7100 The Cannon Page B11 Check saws.org for drought tolerant plants for your garden and other water savings ideas. AUSTIN Labor Day Texas Parks and Wildlife with a water recovery of a weekend proved to be very Department Game War- homicide victim. busy for Texas Game War- dens also filed 268 water Game Wardens also indens who filed a wide vari- safety cases, 36 penal code vestigated several hunting ety of hunting, water safety, cases, and made multiple accidents, boating accifishing, and penal code vio- arrests. dents, and drownings as lations. State-wide arrests in- well as searches and boater A total of 2,655 hunting- cluded boating while in- assists. related citations and warn- toxicated, driving while Im proud of the work ings were issued. Hunting intoxicated, possession of our Game Wardens are citations included hunting narcotics, and active war- doing to protect our natudoves over bait, possession rants. ral resources while also of over the limit of doves, A Game Warden as- providing public safety to hunting migratory birds signed to Bosque County the people of Texas, said with unplugged shotguns, who was patrolling Lake TPWD Law Enforcement hunting deer in closed sea- Whitney looking for water Division Director Col. Michael McCloud Jr., founder and tournament director of Big Bass Mania, was son, and no hunter educa- safety violations arrested a Craig Hunter. The number booked in to the Jasper County Jail on Tuesday, Sept. 3 by Texas Parks and Wildtion certificate. man with an active warrant of compliments and lack of life Game Wardens Ellis Powell and Brooks Yeates, following an investigation of Fishing violations in- for sexual abuse of a child. complaints given the numthe tournaments alleged fradulent activity. (Photo by Alison Hart) cluded several gill netting In Liberty County, Game ber of contacts made is a AUSTIN Texas Game a bass tournament on Lake Due to good police cases as well as commercial Wardens assisted the Lib- testament to their profesWardens have arrested Mi- Sam Rayburn in June 2012. work, collaboration and fishing violations. erty County Sheriff s Office sionalism. chael Shane McCloud of After an extensive, multi- teamwork this case is now Florida (formerly of Bryan- jurisdictional investigation ready to be put in the hands College Station) for theft in which numerous tour- of the court, said Lt. Col. related to a fishing tourna- nament participants and Danny Shaw, assistant comment. sponsors in several states mander of the Texas Parks Following his arrest, the were interviewed, a sealed and Wildlife Department 44-year-old McCloud was indictment naming Mc- Law Enforcement Division. booked into the Jasper Cloud was returned by a Texas Game Wardens inCounty Jail. No bond has Jasper County grand jury. tend to remain focused on been set. Ultimately, an arrest war- protecting our resources as The investigation that rant was issued for Mc- well as the citizens of Texas culminated in his arrest Cloud on the theft charge, a from those who wish to exbegan in June 2012 after state jail felony punishable ploit either. authorities received nu- by a $1,500 to $20,000 fine Fishing tournaments in merous complaints related and from 180 days to two Texas are a fabric of many to fishing tournament prize years in jail. communities and reserpayouts that allegedly did Florida Fish and Wildlife voirs and Game Wardens not occur. Texas Parks and Conservation Department will continue to play a role Wildlife Department Game law enforcement officers in ensuring they are conWardens and investigators assisted Texas Game War- ducted in a manner consiswith other law enforce- dens in locating McCloud. tent with the law. ment agencies spent more After being notified to the McClouds arrest marks Seeking new ways to combine their childrens love of digital devices with the than a year looking into indictment pending against the first time a fishing tour- health benefits and fun of being outdoors, many parents are turning to geothe practices and methods him, he turned himself in nament director has been caching, a hunt for hidden treasures, or caches, using the latest technology. McCloud used to promote to authorities. arrested in Texas. For more information on this craze, visit. BASTROP Water clear; 8892 degrees. Black bass are fair on watermelon/white spinnerbaits, crankbaits, and RatLTraps. Crappie are good on minnows. Channel and blue catfish are good on shrimp, liver, and nightcrawlers. Yellow catfish are slow. CEDAR CREEK Water clear; 8387 degrees; 5.30 low. Black bass are fair on shakyheads around docks. Football jigs and deep diving crankbaits on deeper brush piles working later in the day. White bass are good on slabs. Hybrid striper are good on live shad and topwaters. Crappie are good on minnows. Catfish are good on trotlines and prepared bait. FAYETTE Water stained. Black bass are good on shad colored swim baits, Zara Spooks, and Carolina rigged soft plastics. Channel and blue catfish are fair on cut shad. COLETO CREEK Water clear; 2.43 low. Black bass are slow. White bass are fair on Lil Fishies and pet spoons. Crappie are slow. Channel and blue catfish are slow. Yellow catfish are slow. CHOKE CANYON Water clear; 8387 degrees; 21.32 low. Black bass are good on dark crankbaits and large soft plastic lizards and worms. Crappie are slow. Drum are slow. Channel and blue catfish are good on liver and stinkbait. Yellow catfish are fair on trotlines baited with live perch. EAST MATAGORDA BAY Trout are fair for drifters on live shrimp over humps and scattered shell. Redfish are fair to good on the edge of the Intracoastal on crabs and mullet.. LTraps and Zara spooks. White bass are fair on troll tubes and pet spoons. Crappie are good on minnows. Blue catfish are good on shad. Yellow catfish are slow. ALAN HENRY Water lightly stained; 8792 degrees; 12.78 low. Black bass are fair to good on Zara Spooks early, later switching to Carolina rigs, drop shot rigs and Texas rigs. Crappie are fair to good on jigs and minnows over brush piles. Catfish are good on nightcrawlers and prepared bait. ARROWHEAD Water off color; 8689 degrees; 14.9 low. Black bass are good on topwaters early, later switching to weightless Senkos, Texas rigs and medium running crankbaits. Crappie are fair to good on minnows and jigs. White bass are good on slabs. Catfish are good on prepared bait. BROWNWOOD Water stained to murky; 8690 degrees; 8.49 low. Black bass to 5 pounds are good on crankbaits, Shaky Heads, chartreuse/white spinnerbaits, and on green pumpkin, redbug, or watermelon seed soft plastic worms around docks in 410 feet, and on flukes and buzzbaits in flooded grass. White bass are good on Lil Fishies off lighted docks at night in 515 feet. Crappie are excellent on minnows and white or shad Lil Fishies over baited brush piles in 815 feet. Channel catfish to 5 pounds are good on cheesebait and cut shad near the Hwy. 279 Bridge. Blue catfish to 5 pounds are good on prepared bait near the Hwy. 279 Bridge in 58 feet. Yellow catfish are slow. COLEMAN Water clear; 8286 degrees; 14.27 low. Black bass are fair on watermelon red spinnerbaits, crankbaits, and soft plastics. Hybrid striper are slow. Crappie are fair on minnows. Channel catfish are good on stinkbait, and liver. Page B12 The Cannon Volleyball Roundup Brant Philippus finds some running room behind the blocking of D.J. Gonzales (left) and Jose Contreras (right). Philippus ran for a touchdown in his first ever varsity start. See story, B3 (Photo by Cedric Iglehart) BRIEFS fell in two, 25-21 and 25-8. The 7th Grade B team lost in two sets, 25-13 and 2515. 8th Grade A lost 2-0 to La Grange, 25-13 and 2518. The 8th Grade B lost to La Grange in three sets, 1925, 25-9, 15-5. Gonzales volleyball hosting alumni game on Sept. 13 The Gonzales Lady Apaches volleyball team will be holding an alumniversus-varsity game at 6 p.m. Sept. 13 at the GHS Special Events Center. All former Lady Apache players are invited to come and play. For more information, please contact coach Jenna Philips at 830672-6641 or at jenna.philips@gonzales.txed.net. Shiner Lions to host NFL Punt, Pass, Kick contest The Shiner Lions Club will join forces this year with the National Football League as they host the first annual Punt, Pass and Kick competition in Comanche Stadium on Sept. 8, beginning at 4 p.m. The competition will be open to all boys and girls ages 6-15 and is based upon the childs age on Dec. 31 of the current year. Boys and girls will compete in separate divisions and there will be no charge to participate. Following punt, pass and kick guidelines set up by the NFL, competition will begin with local level competition. Winning participants at the local level will advance to the sectional round to be held in Needville in October. The sectional winners will advance to the state level, where those winners will be able to compete in Houston at Reliant Stadium during a Texans game in December. State level winners will advance to national competition to be held during a NFL playoff game in Janu- ary. Registration begins at 3 p.m. at the stadium, located at 510 CR 348 in Shiner. For more information, call 361-594-3281. Flag football league forming in Yoakum An adult flag football league will be forming in Yoakum with games set to take place on Saturday afternoons starting in midSeptember. All players must be 18 years of age or older and/ or not currently competing in high school football. The league will be limited to the first eight teams to register with the winner of the league advancing to the TAAF Championships in December. Entry fee per team will be $375. Individuals who may not have a team can call to be placed on a team as well. To sign up or for more information, call 361-6552909. football and be very physical up front, Henke said. He said it will be interesting to see how players from both teams respond to losing their respective first games of the season. Sacred Hearts offense will likely ride the shoulders of tailback Jonathan Vanek and fullback Dylan Jahn as quarterback Scott Stoner will put up a couple of passes to keep Flatonias defense honest. Flatonias offense will need production from its main running threats including Marcus Mica, Aaron Manzano, Gus Venegas, Will Bruns and Mitchell Mica. Victoria West at Cuero The Gobblers return home to face the Victoria West Warriors on Friday. We are looking forward to playing at home for the first time, Cuero head coach Travis Reeve said. Victoria West will be a formidable opponent for us. Cuero dropped a close one to Wharton, 23-22, last week in the first game of the season. Our offense needs to take care of the football better and have more consistent execution. The Warriors were on the good side of a one-point game as they held off the Lockhart Lions, 35-34. Victoria West runs a spread offense and is extremely balanced. Quarterback Anthony Navarro passed for 235 yards and three touchdowns, and also ran for 91 yards on 19 carries and one touchdown. Running back Zevaughn Shelton had five carries for 22 yards and Qualian Bry- ant had 13 yards on eight carries and one touchdown. Leading the receivers was Jacob Armstrong, who had five catches for 124 yards and two touchdowns. We are going to have to fly to the football and make sure we tackle in the open field, Reeve said. The Warrior defense lines up in multiple fronts and is aggressive, and is led by linebacker Nathan Hermes, who led the team with 71 tackles a year ago. Three Rivers at NixonSmiley The Mustangs look to build on their seasonopening win against Flatonia by hosting Three Rivers for a 7:30 p.m. game on Friday at Mustang Stadium. Nixon head coach Carlton McKinney said the Stangs need to improve on what they did last week to have a good shot on going 2-0 on the year. He described Three Rivers as a well-coached and hardnosed team that is similar to Nixon. They are a Wing-T offense like we run, McKinney said. Their line does a great job and the running backs run hard. They will drive to eat a lot of clock on their drives. Primary ball carriers will be running backs Jesse Perez and Paul Almendarez. Our defense will tackle hard and slow them down, McKinney said. Three Rivers key defensive players are linebacker Weston Huff, linebacker Adam Romero and defensive back Dillon Guajardo. We will need to control the football with our running game, McKinney said. Three Rivers also started things with a win as they blanked Skidmore-Tynan 30-0. Sugarland Fort Bend Christian at Shiner St. Paul Shiner St. Paul made some improvements in its opening loss to Pettus but made too many mistakes. The Cardinals will look to rebound as they host Fort Bend Christian in Homecoming at 7:30 p.m. at Comanche Stadium. Our mistakes against Pettus came at critical times, St. Paul head coach Jake Wachsmuth said. The Eagles opened their season by beating Acadiana Homeschool (Lafeyette, La.), 62-12. Fort Bend Christian runs a spread offense, using mostly one-back and shotgun formations. Last year, they were more of a running team, he said. It looks like this year they will run to set up the pass. The offense will be led by quarterback Jake Bruns, wide outs Cody Beeman, Kevin Imperio and Tyler Ciacarra, along with linemen Ty Stubbs, John Slotsted and Connor Brand. Our defense did not play bad against Pettus; we just gave up a couple of big plays, Wachsmuth said. We need to play with that same intensity against Fort Bend and prevent the big play. On defense, Fort Bend is led by aggressive linebacker Jackson Beasley. St. Paul did well on offense against Pettus with 400 yards but was unable to score on several of its trips inside the red zone. We need to score when we get close to the Fort Bend end zone and not Dalton Couch of Gonzales runs the course at the Gonhave any turnovers, Wazales Relays cross country meet, held August 24 in Inchsmuth said. dependence Park. (Courtesy photo) Puzzle Page The Cannon Page B13 Cannon Crossword 228 St. George Street, Gonzales, Texas 78629 830-672-6511 Mon.-Thurs. 8-5, Fri., 8-5 Fax: (830) 672-6430 Saturday - Closed Sunday - Closed Most insurances accepted, we welcome Medicare - Medicaid. (No one is turned away for inability to pay.) ARIES - Mar 21/Apr 20 Aries, no matter how hard you work, you just cannot seem to get ahead this week. Instead of tiring yourself unnecessarily, take a break and regroup. TAURUS - Apr 21/May 21 Taurus, although you have many questions, the answers will not come so easily to you in the next few days. Bide your time for a revelation. GEMINI - May 22/Jun 21 It will be really difficult to put you in a bad mood this week, Gemini. Your energy and cheer will be a bright light to those around you, so enjoy the next few days. CANCER - Jun 22/Jul 22 Cancer, you may want to be friends with everyone, but you may have to accept that you have a few people who just do not meld with your interests. Hang out with those who do. LEO - Jul 23/Aug 23 Exercise can do more than just keep you physically fit, Leo. It also can help boost your mood when you need a pickme. Its/Mar 20 There are enough diversions around to take your mind off of your problems, Pisces. They may not disappear, but you can address some issues later. FAMOUS BIRTHDAYS SEPTEMBER 1 Zendaya Coleman, Actress (17) SEPTEMBER 2 Keanu Reeves, Actor (49) SEPTEMBER 3 Jennie Finch, Athlete (33) SEPTEMBER 4 Wes Bentley, Actor (35) SEPTEMBER 5 Michael Keaton, Actor (62) SEPTEMBER 6 Swoosie Kurtz, Actress (69) SEPTEMBER 7 Oliver Hudson, Actor (37) Page B14 Cannon Comics The Cannonholdershours lunchwagons. *** Thought for the Day: I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco (c) 2013 King Features Synd., Inc. Mechanic Needed tish_westmotors@yahoo.com Se Habla Espanol
https://de.scribd.com/document/165552807/Gonzales-Cannon-September-5-Issue
CC-MAIN-2019-26
refinedweb
24,945
73.88
Guest essay by Eric Worrall The initial explosion of green Euphoria at the announcement of the COP21 climate agreement, is rapidly giving way to dismay, as various environmentalists and other expectant parties realise how feeble their climate “victory” really is. According to The Guardian; Leaders from around the world have hailed the agreement struck in Paris on climate change, but some analysts and environmentalists are less sure about its impact. …. … But investors should take it as a signal, he added. “Does this give investors confidence? Probably, yes. It’s all very woolly [in language and aims] but the direction of travel is clear – to low-carbon.” Read (plenty) more: A pretty fair assessment, in my opinion, is the only real achievement of the new climate agreement, is perpetuity of employment for the climate conference class – an agreement for regular “reviews”, to ensure our jetset climate heroes don’t run short of conferences to attend. 79 thoughts on “COP21: Shortest Climate Agreement Honeymoon Ever?” The current low oil price is also a signal not to invest in energy at the moment. CO2 emitting or not. oh I would disagree, it’s a strong buy signal. The deferral of billions of $$ in forward investment in O&G exploration and production globally is storing huge structural issues in the medium term (3-10 years) for forward petrochemical (note I did not type fossil fuel as petrochem products make up a large part of the output from hydrocarbons) production. China, India, Brazil and other developing countries energy demands will also not be going away any time soon, even with the eco-loons attempting to bribe them back to the Stone Age. And (sorry for starting a sentence with an And) if said eco-loons get their legal way, oil and gas price/bbl will soar when they make it illegal to produce. This is when WWIII will happen. ‘This is when WWIII will happen.’ Oh I doubt that. Limited strikes on UN facilities and targeted assassinations of their bureaucrats and the lawyers – always the lawyers, possibly some tar and feathering of Democrats and Greenies but hardly much more. Jeff. You forgot the politicians. I don’t suppose there’s a chance for a little more collateral damage? Kevin, Yes. That should be explicit. I’ll build it into the SIOP.:) AleaJactaEst, I thoroughly agree with you. With at least a 20 year horizon required to recoup the capital investment in very expensive oil refining/petrochemical equipment, what board in its right mind would approve any new construction or replacement of existing equipment in this loony environemnt? Petrochemical and refining profits are not based on the price of oil/natural gas, but on the margin they get when products are created from the raw materials. It’s my understanding that those margins are currently quite high. And in grammar, if you know the rules, you can break ’em. Scientific method, not so much. I agree with you but we probably have not hit a bottom yet. I wrote this yesterday: Wayne Delbeke December 14, 2015 at 9:17 pm Brians356- Anyone notice what the price of crude was today, or the price of natural gas? Anyone notice what the amount of oil being pumped by OPEC is? And how much more will come on stream when the embargo is removed from Iran and the US starts shipping overseas again? How much oil has ISIS been shipping to Turkey? How much oil and gas is Russia producing and where is it going? Looks like a race to the bottom. I sort of think that CNN has it wrong if price, supply and demand are an indicator. The world seems rather awash in fossil fuels and most of the world is going to use more of it regardless of what suicidal policies North America and Europe adopt. There is an fossil fuel energy war going on that could make COP21 and CO2 control in the west almost trivial and meaningless. I think this old fossil will just put another log on the fire and hunker down. WD Thanks for the oilpro link. Very fine article. AleaJactaEst I read a piece a day or so ago that said, inter alia, that so much production had been taken off line that available capacity (i.e that which can be turned on by ‘opening a tap’) exceeded demand by only a very small amount, 1.5 million bbl/day IIRC. The consequence of this is that the price is likely to be unstable. A increase in demand that is quite small compared to the size of the overall market could see all of the slack taken up and thus prices rise suddenly. That would get a lot of production that had been (semi-)mothballed brought back into use, but of course not overnight. Hence six months later the price might well drop again. I would disagree. Now is the perfect time. For governments in countries not endowed with natural energy resources like China, now is a great chance to look into a dozen different nuclear technologies and figure out what will work. Price manipulation is primarily political (carbon tax and market share) driven. It will go back up when demand goes up and OPEC cut (kill off competition enough) production. For individuals it is a lot more dicey as the carnage in the fossil fuel group is just starting (IMHO). You would have to be very careful but there will be bargains to be had over the next few years. When stocks are low, is the time to buy. The current glut is temporary and those stocks will rise in price in a few months to a few years. check out ZERO HEDGE for some interesting items on the opil/gas supply issue and Russia feels its more like 7 yrs its going to be low priced and they are planning accordingly. the storages are full, the offshore tankers are brimming, and saudis are still madly pumping it up. rather funny theyd tried to coner mkt n screw usa..well they have to a degree also run emselves into the red doing it. Hmmm Interesting timing. That’s when projections for MSR reactors should be making market penetration. 10 years of continued low oil. Wind and solar boondoggles. MSRs on their white horse as fossil start to increase in price again ? Should be entertaining to watch unfold. You know, had Obama and the Climonauts crossed the Atlantic to Paris in a windjammer I would, despite myself, have been half impressed. That would have taken too much time from golf vacations. The current record holder for a west to east Atlantic passage under sail is the Banque Populaire V, which made New York to the imaginary point linking Lizard Point, Cornwall to Ushant (5,330 km, 3,310 statutory miles, 2,880 nautical miles) in 3 days, 15 and one half hours, averaging almost 33 knots or 61.0 km/hr. Impressive for a sailboat, considering that back in the days when people actually travelled by sail the fastest passage was around 15 days. To this we would have to add some additional time to get to a French port, and then on to Paris by sustainable horse-drawn carriage. East to west passage takes longer due to prevailing winds. All together, it would take at least seven weeks for the round trip to Paris and two weeks of meetings if the delegates emitted no CO2 from fossil fuels. Maybe it’s a good idea. If we increase the travel time while reducing comfort for these COP meetings, we will get fewer of them. If we follow the COP21 plan, we are all taking a one-way trip back to the 18th century. How come is it OK for these movers and shakers to off-set their CO2 by planting some tress, or by buying some carbon credits? Why can’t I plant a few trees and/or buy some credits which are trading in cents to off-set my lifetimes CO2 emissions and then no longer have to pay any of the green taxes whether on fuel, airfare or whatever. We could all easily become Carbon neutral in this manner. So how much is a carbon credit for say 500 tonnes of CO2 trading on the European or Chicago floor? You produce your certificate and you get your petrol (gas) at a price less the government green taxes, dittp when purchasing flights, ditto when paying your electricity bill etc. Better get those Morocco hotel reservation made soon before the room scalpers get all the good ones And the price of the local hashish goes through the roof. Delegates from Colorado … BYOD. They were busy achieving nothing of any significance whatsoever: Nice one, Admad … You brightened my day with your musical dose of reality 🙂.” Think the global corruption has to be dealt with before “the poor” get a sniff of a buck. Some hope with the 190 troughers and bag carriers we saw. Though it does look as if the poor will see some benefit from continued and increasing use of cheap fossil fuels. Jeff (FL), Ex-expat Colin, you are right, and the arguments regarding economic development are obviously in favor of cheap energy to all people. The corruption moves top-down, we see from Mr. Singh, where the draw of short-term “aid” beats out that of a new, long-term infrastructure that might just catalyze the kind of life in perpetuity for many people (ideally) that the “aid” might give a few people for a short time. poor fafa cried – I mean Fabius – but this the great new the big problem with cows is going to be studied Attention Anthony, or MODS Why is that if I try to LIKE your page on Facebook, Word Press tries to change my home page ?? That is not a good thing and discourages people from LIKING your page !! Emperor’s New Clothes. What other explanation exists when the “planet-saving agreement” is panned by “climate guilt” activists and climate model skeptics alike? “…the only real achievement of the new climate agreement, is perpetuity of employment for the climate conference class…” Bingo! People who would otherwise not be qualified to count recycling containers now get taxpayer-funded jobs, pretend to be scientific, generally make nuisances of themselves and posture, lecture and scold non-True Believers. Do we have a number for the CO 2 molecules per ten thousand (currently about four) that will raise “global temperatures” by 1.5C and 2.0C? I have a funny feeling there’s no such answer but I could be wrong Well the current altered surface record shows 1.4 degrees, so I am not certain what they consider pre industrial times to be, but we may struggle to get that .1 degree if the AMO continues to turn with a strong LaNina. Coeur de Lion: You ask: That would depend on the climate sensitivity (CS) and the longer the misnamed ‘Pause’ lasts the lower CS must be. In the context of discussing the CoP21 Climate Agreement, the pertinent issue is the amount by which emissions of CO2 from human activities need to be reduced to stop “global temperatures” rising by more than 1.5°C or 2.0°C from pre-industrial values. And the IPCC says that is not known. success – if any – of any activity aimed at avoiding a 1.5°C or 2.0°C rise is not known. Richard Eric, “…. A pretty fair assessment, in my opinion, is the only real achievement of the new climate agreement, is perpetuity of employment for the climate conference class – an agreement for regular “reviews”, to ensure our jetset climate heroes don’t run short of conferences to attend.” I believe that is likely to be the primary goal of all the COP Circus events. “…pathway to keep temperature rises below 1.5C above pre-industrial levels left that goal unclear …” This always bugged me. Pre-industrial times were horrible. First, people like me lived a subsistence life in squalor. Second, the climate was incredibly harsh in England, Scotland, Canada, etc. Why on earth would we ever want to use that time as any kind of useful benchmark! I have a dream, That the world would sign an environment deal. A deal where all countries would agree to make every effort to minimize emissions of NOX, soot particles, sulphur, heavy metals, and try to clean all emissions from toxic elements. Where all would agree to help developing countries get toxic-free cooking and heating. To support developing countries to clean garbage-burning and agree to stop dumping plastic and garbage in the sea and clean fresh water to all. But we didn’t get that, did we. Instead we got the opposite, a deal where all agreed on minimizing a trace gas without any toxic effect and that plants need to flourish. + 1 rolfalmlund +1 doesn’t say enough. Regardless of position, don’t let the perfect be the enemy of the good Feckless agreement locked in. This will be the *ceiling* for future efforts. Here in Canada, our new Prime Minister and Minister Responsible for Photo Ops, Justin Zoolander, has never met a cause he didn’t belief in with all his heart and soul. A nice sentiment for a teenager, but some of us expect someone responsible for hundreds of billions of dollars to have a BIT of gravitas. Then again, the One that currently occupies the White House has even less of an excuse for style over substance. Nice hair, though. Why do so many continue to speak as if we can actually control atmospheric co2 by cotrolling emissions? And why do so many continue to speak as if we can actually control the world’s climate by varying the % of CO2 in the atmosphere, currently 0.04% For the money of course YMMV, but I chalk it up to 42+ years of (completely unscientific) propaganda inspired by the pronouncements and manipulations of the recently deceased (non-scientist), Maurice Strong. Without Strong’s initial interventions and creations via the – to this day – un-mandated, ever-growing arms, elbows, hands, fingers etc. of the United Nations Environment Program (UNEP) are highly unlikely to ever have seen the light of day. What a wonderful world it might have been without the precedence accorded to the pronouncements of these primary promulgators and purveyors of doom and gloom, if we don’t do things their way! Then again, Strong’s UNEP has morphed into a so-called agency of the United Nations. This is a bureaucratic body that nowadays seems to be totally dedicated to the maxim: Let’s you and him fight – and please send us more megabucks to assist you in the pursuit of our never-ending, ever-changing “noble cause”. You don’t have to be a gullible fool to be a newspaper environment correspondent, but it helps. The person who wrote that Guardian article on 14 December about how the Paris deal is too weak and doesn’t help the poor, tweeted this on Dec 12th: “I’ve never seen anything like it. #COP21 Jubilation, celebration, people hugging, weeping in hall. Real sense this is historic agreement.” They are mostly Marxists and are fighting a War against the Western civilization from within. They thought this deal would destroy it economically and culturally? As with so much is generated by the UN’s hype and hoopla division in action, the above gives a whole new meaning to the word “historic”, does it not?! Chatterton has it wrong. Yes, 4.2 is a paen to transparency. Rendered meaningless by preamble paragraph 27, which lays out a smorgasbord of reporting options with no auditability. Which in turn renders the name and shame mechanism impotent except against those countries foolish enough to have transparent INDCs. The only way China coild be named and shamed before 2031 is if somehow they accidentally reduced emissions. Success will be determined by PR agencies and propaganda, just as it is now. It’s win-win: the greens get what they want “agreement to restrict CO2 and destroy the western economy” and we sceptics get what we want: no meaningful action. That’s the benefit of having two groups: greens who are as gullible as you get and sceptics who don’t care at all about the PR. Meanwhile back at the Iran “agreement” we have this brush with reality. No doubt the climate will still be changing long after WWIII. They cannot complain about the agreement they got since it was the only one they were going to get: a face-saving, empty bag of nothing much. Green politicians appear to have heard the electorate are no longer panicked by fears of “climate change” and waiting with baited breath to hear what government is going to “do” about it. So putting on a good show to claim bragging rights to neuter the nutters in their ranks is a good days work well done for lefties on the make. The dogs bark. The caravan moves on. “The dogs bark. The caravan moves on.” Enough Alpo. Time to put them on dry food. Why would anyone ‘invest in low carbon’? Without a subsidy what is there to ‘invest in’? Who would build a wind farm or PV array in the absence of a contract to exploit the public purse for years to come? People in the business of manufacturing the products are interested of course, in selling as many as they can. Quelle surprise. An ‘investment’ is something that has a positive rate of return (or in some countries, no loss). Show me a low carbon option worth investing in. It will have splitting atoms for a state. Because the politicos paying you have a gun to the head of the taxpayers to collect your loot. It’s a no-brainer, really. Right up until the time it isn’t. You think you’ve got trouble. Spare a thought for our leaders. World leaders stuck in Paris after summit announces end to fossil fuels Now THAT is FUNNY ! Regards, WL Even if it were possible for CO2 to raise the world’s temperature by 1.5C, why should we assume that this would be a bad thing? It’s a cop out. Full of hot air and no meaningful actions. And the hot air from Paris is still very active, driving a wedge of heat northwards from France across England Wales and Scotland, raising temperatures to 6 degrees above normal today , as it has been for the last 4 weeks in England at least . A difficult time for sceptics of global warming. The penny is dropping across a whole slew of media outlets that the Paris ‘deal’ is effectively a binding agreement to *not* have a binding agreement, thus it’s all-but worthless. India, China et al can emit away to their hearts content so what, pray, was the point of it all? You know all is not as it seems when even the Guardian is questioning the deal. ”Climate change’ is supposed to be the worlds most pressing threat, yet approving a continuation to emit CO2 as if there’s no tomorrow reveals an entirely different reality to their stated fantasy. Verdict: it’s already a busted flush. Or a flushed bust. i don’t think any government really believes this rubbish, they just have to be seen to be throwing a bone to the mad dogs. Has anyone noticed how the 2degC figure has now become a 1.5degC figure. Further, since industrialisation, which coincided with the end of the LIA, there has been about 0.7degC of warming which is not anthropogenic in origin. Even the IPCC acknowledges that manmade contribution prior to 1950 is miniscule. The land based thermometer anomaly record (which is a meaningless data set for many reasons often explained by Richard Courtney) shows about 0.7degC of warming from the early 1800s to the highs of the late 1930s/40s. So it appears that the agenda is now to try and restrict manmade warming to about 0.8degC. The goal posts have most definitely changed, and no one appears to be shouting foul and highlighting this. Repeated often enough by MSM it will soon pass into accepted human consciousness. We should try and stop this from happening (not the warming which I doubt that we can do anything about, and which is likely to be net beneficial), but rather the moving of the goal posts. + 1 Yes, I noticed that baseless insertion, too. Particularly since it seems to have been touted and spouted by Canada’s “because it’s 2015” Minister of Environment and Climate Change, Catherine McKenna – as dutifully reported by the CBC, circa December 8, with the headline “”COP21: Catherine McKenna endorses goal of limiting warming to 1.5 degrees C”. But, that aside … Don’t know about you, but I’ve lost track of the number of years that we’ve been fed the line that the deliberations of the UNFCCC are “informed by” and rooted in the “science” – and/or “scientific assessments” – of the “gold standard” IPCC. Yet, if you read this latest and greatest abominable and abstruse word salad called an “Agreement” carefully, you will notice that one of the clauses was a so called “Associated Decision”, of the UNFCCC in which this oh-so-noble body: “invites the IPCC to provide a special report in 2018 on the impacts of global warming of 1.5°C above pre-industrial levels and related global GHG emission pathways.” Translation from UN-speak: “1.5°C above pre-industrial levels” does not have a scintilla of “science” – even of the IPCC- kind – to support it! So much for the IPCC “informing” the work of the UNFCCC, eh?! Eric, Polite rant. (Your comments will be most welcome of course, thank you). I have just read your post, having also read the “earth’s tilt” post by Anthony. Whilst I really do appreciate the information you (both) give us, I end up shouting “Bollocks” at the screen ! Please allow me to explain. “Climate Agreement” – this expression is complete “bollocks” ! (“Bollocks” is a quaint, old, English expression, an insult, which means “nonsense” or “rubbish” or “garbage” as you might say in the North America). The expression itself, “Climate Agreement”, must be thrown into the NOT EVER TO BE USED VAULT. How the hell can anyone agree about or seek to control any climate system ? Similarly, “Climate Change” – is complete “bollocks” ! Thread bloggers “asybot” and “richard verney” make similar objection and please know that we each have made this point several times before. There is no such bloody thing as climate change. The LANGUAGE has been hijacked enough by the EPA, the UN, a community organiser, a qualified railway engineer, pseudo-scientists at the BBC and others too many to mention. We are all so tired of it. It is time to fight back with language which is plain and true. I again ASK: please look at the WUWT header page and PLEASE DELETE the word “change”. It should read as follows:- WUWT Watts Up With That The world’s most viewed site on global warming and climate. Regards and thanks, WL Hey I’ve got to have some fun… 🙂 The above is ‘spot on’ + 1 mighty fine observation 2.0 degrees? 1.5 degrees? Decisions.. decisions.. “There’s no sense in being precise when you don’t know what you’re talking about.” J von Neumann Forget the atmospheric physics arguments, along with the Paris Climate Agreement climate change has suddenly ended now and forever. No more global warming, extreme weather events, or rising sea levels. Those are all in the past so we do not have to worry about climate any more nor do we need to waste money studying the now non problem. We are a poor nation with a huge national debt, huge annual deficits, huge trade deficit, and huge unfunded liabilities. Our President’s economic “plan” has failed. Obama once said that that deficit spending showed ” a lack of leadership” so “a lack of leadership” is the Hallmark of the Obama administration so our status of being a poor nation is not going to change. As part of the Paris agreement, everything is going to be paid for by “rich” nations so our poor nation does not need to pay anything for the climate solution. I expect that in the very near future we will all be receiving electric cars and solar powered changing stations all paid for by “rich” nations. Now we can concentrate on more pressing problems such as Man’s out of control population. We need to gradually reduce our human population so we can turn farm, urban, and suburban areas back into wilderness areas and forests. The ABC in Australia and the Green activists (same thing) are claiming the new agreement will keep temperature rise ‘well below’ 2 degrees. If they could not agree on 1.5 degrees what does well below mean? In Isaac Asimov’s novel “Foundation,” a group of nervous Encyclopediaists welcome a sub-vice-consul-whatever from the Empire to assure them that the Galactic Empire hasn’t forgotten about them and will protect them from their increasingly agressive neighbors. The Mayor isn’t so impressed, and secretly records every statement the visitor makes during his stay. After the official has left Terminus, the Mayor admits his transgression, and then provides them a semantic analysis of all the official’s remarks. The committee is dumfounded to discover then when all the contradictory statements have been eliminated, THE MAN HAD SAID NOTHING AT ALL. Sounds like the same thing happened in Paris. The reality is that the worlds best chance to keep temperatures to 1.5 degrees will be to do nothing . If one extrapolates the trend for the last 18 years they should be there in 2100 with room to spare. How can any deal that allows the worlds two largest emitters in the world to do nothing for fifteen years to slow their emissions be serious. Not only is the honeymoon over hopefully so will be the party that warmists have been having at our expense. A comment on Paris doing the rounds ( from Notrickszone I think) “Rich people from rich countries met in Paris with rich people from poor countries and decided to transfer money from poor people in rich countries to rich people in poor countries and screw poor people everywhere “A pretty fair assessment, in my opinion, is the only real achievement of the new climate agreement, is perpetuity of employment for the climate conference class – an agreement for regular “reviews”, to ensure our jetset climate heroes don’t run short of conferences to attend.” Correct, the only aim of the COP21 was to ensure that the perpetual Party continues, year after year. The participants are not interested in Science, Economics, Welfare or the Poor, they just want another big Party next year. I recently read Past Climates by Leona Marshall Libby It’s an old book published in 1983, but I liked it for its simple writing style and experimental rigor. Ms Libby must have been quite the pistol in her day. Sorry I never knew her. I know there are some old timers on this webpage. Is there anyone who knew her ? Not an Ice Core You can fill in the current prices with your favorite reason for price movement. After reading WUWT and the wacky world of reconstructions, I have found new admiration for financial price charts. I have far less concern about their reliability. Unless you think the world has no real use for fossils anymore, then we are getting into the range where sovereign wealth investors start backing up the truck.
https://wattsupwiththat.com/2015/12/15/cop21-shortest-climate-agreement-honeymoon-ever/?shared=email&msg=fail
CC-MAIN-2019-39
refinedweb
4,648
70.94
0 I have a bank class below. What is the best way to add amounts to any instance variable in any of the constructors to make it o when i add different amounts from 2 or more different classes it will update in a way that when i call the method it should print out the overall amount added between the variables placed of all the classes. If you have a better method of doing such please tell. public class Person { public double balance = 0.0; public double happy = 0.0; public double newBalance = 0.0; public double newHappy = 0.0; public Person(){ balance = 0; happy = 0; } public double getPaid(double moneys){ newBalance = balance + moneys; return newBalance; } public double getSpend(double moneys){ newBalance = balance - moneys; return newBalance; } public double getHappy(double happys){ newHappy = happy + happys; return newHappy; } public double getSad(double happys){ newHappy = happy - happys; return newHappy; } }
https://www.daniweb.com/programming/software-development/threads/417189/data-structure-help
CC-MAIN-2018-17
refinedweb
147
53.81
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. How to append sale order line in qweb report ? Hello, I have multiple sale order line and sale order line have one field called order id. When I print sale order line, qweb create a new page for every line that is i want. But now, when the order id is same for multiple sale order line, it append in one report. How to do this ?? Thanks, Hello, I have taken one field in sale order line which is many2one to sale order line. Now search the record where reference id are same and in that record written the first sale order line id. For report, Create a parser class and take method render_html. Then search the record in the sale order line that line_id is the sale_order_line.id so i get same reference_id record in list and append in the main list. Because there are many records which have multiple sale order line. class PackingListReport(models.AbstractModel): _name = 'report.work_order.report_packing_list' @api.multi def render_html(self, data=None): family = [] report_obj = self.env['report'] work_order_id = self.env['work.order'].browse(self.id) for line in work_order_id.work_order_line: search_id = work_order_id.work_order_line.search([('order_work_id', '=', self.id), ('reference_id', '=', line.reference_id), ('line_id', '=', line.id)]) if search_id: family.append(search_id) report = report_obj._get_report_from_name('work_order.report_packing_list') docargs = { 'doc_ids': self._ids, 'doc_model': report.model, 'docs': work_order_id, 'family': family, } return report_obj.render('work_order.report_packing_list', docargs) and this family list append in the dictionary and pass through render method. So I can easily fetch it into my report template. Thanks, About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now It's Done.
https://www.odoo.com/forum/help-1/question/how-to-append-sale-order-line-in-qweb-report-98934
CC-MAIN-2018-22
refinedweb
309
62.04
Hello everyone, is it possible to import labels for the object classification workflow? I am doing a cross validation for my bachelor thesis, where i have ten segmented images. My idea was to train the classifier on 8 of them and test it on 2 of them in every combination. If I could import object classification labels, i would only have to label them once for all of the 10 images. It would be great, if anyone could help me! Cheers Justus Hello everyone, Hi @Justusschl, there is some import/export option for labels in debug mode, however I would not recommend to use it. What you are trying to do should involve as little manual labor as possible (source of errors). I thought about it a bit and found something that could work. Did you know the .ilp project file is just another h5 file? That means that you can manipulate it. So for starters you should create a project and annotate all 10 datasets. Then you’d write a script (in Python?!) where you would: - Populate a list of image-file - probability file pairs (in the same order as you have it in your project file) - Use sklearn.model_selection.KFoldto generate your splits () - iterate over the splits, delete the trained random forest and the annotations belonging to the test data Some python pseudocode (haven’t tested it): import numpy from sklearn.model_selection import KFold import h5py import os # project with annotations in all images master_project_file = "/paht/to/your/project.ilp" out_folder = "/some/out/folder/" file_list = [ ("/path/to/image01.h5", "/path/to/probs01.h5"), ("/path/to/image02.h5", "/path/to/probs02.h5"), ... ("/path/to/image10.h5", "/path/to/probs10.h5"), ] # leave two out: should yield 5 combinations with 8 v 2? kf = KFold(n_splits=5) # generate a new project file for every split, with the test training data # deleted for train_indieces, test_indices in kf.split(file_list): # make a copy of the file fout = "".join(map(str, test_indices)) fout = f"{out_folder}/test_{fout}.ilp" os.copy(master_project_file, fout) # open the copied file with h5py.File(fout, "r+") as f: # very important: remove the trained random forest del f["ObjectClassification"]["ClassifierForests"] for ind in test_indices: del f["ObjectClassification"]["LabelInputs"][f"{ind:04d}"]["0"] f["ObjectClassification"]["LabelInputs"][f"{ind:04d}"]["0"] = numpy.array( [0.0, 0.0], dtype="<f8" ) # bonus, construct a bash/shell script that that calls ilastik in headless mode with the # appropriate new project file and the right input files from the file list ... if you make sure that the original project file was created with all data copied to it (in the dataset properties, data selection applet), then you can open the created files in the gui without having to re-link the input files via a dialog… Thanks a lot! It works well, except when i am changing the feature selection in my master_project the python code gives me the error: KeyError: "Couldn’t delete link (callback link pointer is NULL (specified link may be ‘.’ or not exist)) and it points to the part [“ClassifierForests”]. I changed the feature selection back, but it still doesn’t work. Luckily i made a copy of the master_project, which still works. But why doesn’t the code work as soon as i change the feature selection of the masterfile? To be precise, I changed in “object feature selection” the “neighboorhood size in pixels”. Cheers Justus Awesome that it worked But really interesting that you got problems, once changing the feature set in the master file… Have you switched to the object classification applet after changing the selection before saving? It appears there is some redundant information in the project file… Maybe also delete the f["ObjectClassification"]["SelectedFeatures"]. Cheers Dominik I tried switching back to the object classification applet after that, but it still doesn’t work with the file. Deleting f [“ObjectClassification”][“SelectedFeatures”][“ClassifierForests”] doesn’t work either. ah, sorry, I think I get it now. What went wrong, is that, after changing the features, the classifier got invalidated and is thus not in the project anymore after saving. Just wrap the code (but only this one line that deletes the classifier) with if “ClassifierForests” in f["ObjectClassification"]: del f["ObjectClassification"]["ClassifierForests"] else: print("Warning, no classifier found")
https://forum.image.sc/t/object-classification-import-labels/29286
CC-MAIN-2020-40
refinedweb
708
54.63
I have a class as shown below. This class has a method addFilter with 2 parameters (type String and type Command1 ) public class Command1 { public StringBuffer addFilter(String query, Command1 dataBase) { //concrete implementation return query; } } I have another class Command2. Here I need a similar method. The only difference is in the type of parameters passed. (type String and type Command). public class Command2 { //TO DO: public StringBuffer addFilter(String query, Command2 cmd) { //concrete implementation return query; } } I have started by using Interface public interface Helper { public StringBuffer addFilter(String query, XXXXX parameter2); } I would like the classes Command1 and Command2 to implement the interface Helper and override it these two public classes. However my problem is in dealing with the 2nd parameter. Am I right in my approach? Can anybody tell me how do I handle this issue?
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/38603-java-how-design-interface-usage-printingthethread.html
CC-MAIN-2015-22
refinedweb
139
56.15
Standing in the Field Notes from SJS Application Server Field Engineering Roughly four years ago, Scott McNealy addressed a group of iPlanet employees, including myself. This was in the middle of the dot com boom, and there were still a lot of questions about what direction the internet was going to take. At the end of his speech, Scott commented that there were a lot of companies trying to make the web proprietary and trying to lock customers into proprietary solutions. He said that Sun was in a battle to keep the network open and to develop solutions that favored customers and not vendors. The last part I remember exactly. He said, "isn't it nice to be working for the company wearing the white hat."* That has always been important to me. It has been nice to be working for the company in the white hat. Sun has had its ups and down since then and so has its stock price. I've been re-org'd more times than I care to count. But Sun has never wavered from its commitment to openness, to its customers, and to operating with integrity. There are lots of companies out there that claim to be open. But most of them are just interested in how they can make money from the open source contributions of others. A lot of companies "talk the talk, but don't walk the walk" when it comes to contributing to the commons. Executive management at Sun may not have always been effective at "talking the talk", but Sun has always "walked the walk" about open source and open platforms. However, the time has come for me to leave Sun. After working with Java since version 1.1 and J2EE from the very beginning, it's time for me to move up the software stack. I've accepted a position with Fuego, a leader in the exciting market of BPM software (business process management). I see in Fuego the same commitment to customers, to innovation, and to openness. And I believe that BPM software will be the key to making Service Oriented Architecture (SOA) a reality. BPM is the glue that will make everything (people/processes/systems/services) work together. Anyway, thanks to all of those of you who have read my blog or had me come to your company. You can now find me blogging at BPM Blog. ( RSS feed ) My first couple of posts will be about why I've made this move and why I think that people who are interested in J2EE should be learning about BPM. (I promise I'll be better at keep the blog updated. I have a lot of plane rides ahead of me: lots of time to be writing blog posts. :-) ) Thanks again for reading and I hope to see you at BPM Blog. (If you have trouble connecting today, the DNS may not have propogated to you yet. Try again tomorrow.) David *For those non-US readers not familiar with the expression "white hat", old western movies stereotypically had the good characters wearing white cowboy hats and the villains wearing black hats.(2005-05-20 10:44:57.0) Permalink Comments [1] So everyone is calling IBM's acquisition of Gluecode a move to create a "JBoss killer". Gluecode is a very small company that provides an integrated application server suite around the Apache Geronimo application server, some other related Apache projects, and some management and monitoring tools. Since there have been rumors of IBM trying to create an open source implementation of J2SE, it's entirely reasonable that IBM would want an open source application server to go with their J2SE implementation. All in all, I find the acquisition interesting, but not earth shattering. Geronimo and the other Apache projects have existed for some time now and I don't think that IBM's acquisition of Gluecode really changes the industry that much. But Marc Fleury, Founder/Chairman/CEO of JBoss, is his usual acerbic self. (Fleury was the one who called the Apache Foundation “a bunch of fat ladies drinking tea” and who got caught "astroturfing" TheServerSide.) Like Rich, I can't follow Marc's argument about why this acquisition is bad for Sun. Sun would love to see an open source implementation of J2EE that is more than grudgingly J2EE certified. (When Marc spoke at my JUG he complained at length about what a waste of time the J2EE certification is.) And with a couple million downloads of Sun Application Server, I'm not sure that Sun has to worry about Gluecode suddenly becoming a volume play that takes Sun out of the picture. All things considered, IBM has been a good friend to Java and I can't see IBM making an investment in open source as any kind of threat to the integrity of the Java Community Process.(2005-05-13 20:21:10.0) Permalink Comments [1] Sun has a very colorful past when it comes to open letters. We write them. We receive them. The press has a field day talking about them. So, given the fact that "Standing in the Field" gets a reasonable amount of traffic from the publicity of blogs.sun.com, I'd like to continue this Sun tradition of open letters. To: Jane Ogren janeogren.com Dear Mom: I wanted to take advantage of this public space to tell you how much I love you and I how proud I am to be your son. I am proud of the values you have instilled in me. I am even more proud that you were able to instill those values so subtly while still allowing me to pick my own paths and make my own mistakes. Growing up I always thought I took after Dad. But as an adult I see how much of you there is in me. I am proud of your art. I am proud of all of your work: as a mom, as a teacher, as an artist, as a volunteer, and as a citizen. Thank you for continuing to teach me things as an adult. Thanks for listening to me. Thank you for being an example I can be proud of. Thank you for always being there for me. In the end, the results speak for themselves. Your children love you and we've both managed to be happy and well adjusted. Our family has a deep bond. We may live further away that you like, but we always feel you near. Happy Mother's Day. You are the best Mom ever. Love,(2005-05-08 07:58:52.0) Permalink David Lots of people are familiar with the Sun Java System Application Server Platform Edition as the J2EE server they downloaded as part of the J2EE SDK. But I bet a lot of those people don't realize that you can use that application server in production for free. Sun has now published some impressive SPEC benchmarks for SJS Application Server Platform Edition. I can't wait to see the price/performance numbers for this configuration. With a free application server and the price/performance of the V20Z Opteron servers it's going to be very impressive. Thanks to Rich for both the original link and for all of the work he and his product team have done to make this possible.(2005-04-28 21:33:50.0) Permalink News.com had an article recently about how many PC users do a bad job of wiping their hard drive before selling, donating, or trashing their PC. Obviously this is a bad thing considering the sensitive information the average person keeps on their PC. I understand why this is difficult for the average PC user. Wiping a hard drive is a tedious process for a PC. Properly wiping a hard drive is very easy on a Mac, however. If you are planning on selling or giving away your Mac, here are some easy steps,/p> Things you will need: Steps to permanently erase the hard drive of an old Mac. Nothing really too much different than a PC, but the built-in secure disk overwrite and firewire target mode makes it much more convenient on a Mac.(2005-04-22 10:10:34.0) Permalink Severalpeople have blogged this new java.net project that is a DTrace agent for Java. Since I've talked about DTrace and Java previously I figured that I should throw in my two cents. (Especially since I've been less than diligent in posting recently.) This project is very interesting and I'm hoping that it will be available as part of the standard JDK in the future. Most interestly, it has several probes that are going to allow DTrace to instrument method calls and GC events. But it's important for me to note that you can already use DTrace to probe Java applications. Most notably jstack() does a reasonably good job of translating stacks into Java method names. Don't assume that you need this module to use DTrace effectively on a Java application. The new module does allow you to be more proactive and has some very useful trace points for doing active troubleshooting, but don't discount the out of the box DTrace functionality. Also, the downside of this module is that it has to be actively installed into the JVM. Which takes away one of the advantages of DTrace: the fact that it is pre-integrated into the OS. It is great to see this module. And it's especially great to see this as a java.net project with CDDL licensed source code. But it's probably best to just see this as a technology preview for what we will see as far as DTrace integration in Mustang.(2005-04-20 11:18:57.0) Permalink One of my projects this month is to review the Sun Java System Application Server Performance Tuning Guide. This is part of a combined effort between the field and the product team to review the complete documentation set. It's interesting work. I've always found this document helpful but sitting down and reviewing it page by page has been a much different experience. There are a lot of places I'd make it more concise or differently organized. So, take a look at the Perf Guide with me. I'll include any comments and feedback with my own review for the documentation team.(2005-04-05 21:31:38.0) Permalink Comments [1] Tim Bray (the co-worker I developed my Jython instructions for) tells me that he needs to run his installation headless. Which I didn't document last time. So here is an addendum to my previous instructions if you don't have X11 access to your box. When executing the SJSAS installer (j2eesdk-1401_2005Q1-solaris-i586.bin or similar), just add the argument of "-console". This runs the installer in text mode. Using the installer is generally self-explanatory but there some basic instructions displayed when the installer begins. Just type in the same options you would have selected in the graphical installer. When executing the Jython installer add the argument "-o /install-jython". Adjusting for the directory where you want Jython, of course. ("java jython-21 -o /install-jython") This skips the installer completely and makes an installation in the specified directory. At this point you can perform the rest of the installation instructions as they are all browser and command line oriented. However, just for reference, I'll show how to use the command line to deploy the application template rather than the browser based admin GUI. The deployment command is as follows: "/install-dir/bin/asadmin deploy --name jythondemo --contextroot jythondemo /install-dir/samples/quickstart/hello.war " The admin server must be started for this command to work.(2005-03-28 09:22:15.0) Permalink Comments [1] A co-worker of mine was doing a project that used servlets written. Sean McGrath wrote a tutorial on getting this up and running. Unfortunately, the tutorial assumes that you will be deploying to Tomcat. I wanted to encourage my co-worker to use Sun Java System Application Platform Edition, so I volunteered to get Jython servlets running on Sun's appserver. There really isn't any significant difference in the way Jython works on these two platforms, but for those who are new to SJS Application Server's filesystem layout and administrative interface this document may be helpful. After following these instructions you will want to go read Sean's original documentation as this document only covers the server setup and not the Jython programming. All code is the property of Sean McGrath as I just tweaked the install instructions a little. This document was developed using Sun Java Application Server Platform Edition 8.1 2005Q1 UR1 on Solaris 10 x86 Edition. However, these instructions should work for any platform, and for any edition of SJS Application Server. (This document is written with UNIX style PATH names and command prompts, however. Adjust appropriately for Windows machines.) These instructions do not assume root privileges, although you will need to choose directories and ports appropriate to your account. It is assumed that you have a monitor. There are headless installation alternatives available for both SJS Application Server and Jython, but they are not covered in this document. Download Sun Java System Application Server from. These instructions assume that you are using the "All-In-One-Bundle". Make the downloaded file executable : "chmod +x j2eesdk-1401_2005Q1-solaris-i586.bin". (Your filename may differ if you are running a different patch level or platform.) Now start your application server by executing "/install-dir/bin/asadmin start-domain" (adjusting for your installation directory). You should now be able to reach the application server on and the adminstrative interface on . Download Jython 2.1 from . (More detailed instructions can be found at . These documents include some platform specific notes and troubleshooting tips if you run into trouble.) Jython is distributed as a self-extracting Java class file. You can run the installer by executing "java jython-21". If you do not have java in your PATH, you can use the java installed as part of the Application Server "/install-dir/jdk/bin/java jython-21". You should now be able to bring up a jython command line. Execute "/install-jython/jython" (substituting your own install directory) and jython will give you an interactive command line after doing some initial processing. Type ^c twice or ^d once to exit from the command line. Rather than compiling and deploying a web application from the command line as the Sean does in his Tomcat instructions, we will use one of the sample applications that comes with SJS Application Server as a template. We will expand this simple hello world application with Jython in the next section. First we will add the jython library to the CLASSPATH of the server by placing it in the server's lib directory. Copy the jython.jar directory from your Jython install into the application server's lib directory. ( "cp /install-jython/jython.jar /intall-dir/lib/" ) Change your directory to the home of the application you just deployed by executing "cd /install-dir/domains/domain1/applications/j2ee-modules/jythondemo/WEB-INF". (As always, adjusting for your installation directory.) Here you will find the web.xml file that describes the application to the application server. We will add a line to this configuration file that tells SJS Application to use Jython to execute requests ending in ".py". Replace the existing web.xml with the following: <?xml version="1.0" encoding="UTF-8"?> <web-app <display-name>hello</display-name> <distributable/> <servlet> <servlet-name>PyServlet</servlet-name> <servlet-class>org.python.util.PyServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>PyServlet</servlet-name> <url-pattern>*.py</url-pattern> </servlet-mapping> </web-app> While we are in this directory we will also copy the Jython libraries into the application's web context so that we can use later. ("cp -r /install-jython/Lib lib") We will now use Sean's first Jython servlet to test that everything is working. Go up one directory to /install-dir/domains/domain1/applications/j2ee-modules/jythondemo/ ("cd ..") and create a JythonServlet1.py file with the following code: from javax.servlet.http import HttpServlet class JythonServlet1 (HttpServlet): def doGet(self,request,response): self.doPost (request,response) def doPost(self,request,response): toClient = response.getWriter() response.setContentType ("text/html") toClient.println ("<html><head><title>Servlet Test</title>" + "<body><h1>Servlet Test</h1></body></html>") You will now need to restart the server so that it picks up the changes to the web.xml file. (You can add more Jython Servlets without restarting: it is only the web.xml changes that require a restart.) Execute "/install-dir/bin/asadmin stop-domain" to stop the server and "/install-dir/bin/asadmin start-domain" to restart it. Once the server has restarted you should be able to access your test Jython servlet from "". Just to make sure that the Python library is accessable we will also deploy Sean's third sample. Put the following code in JythonServlet3.py import sys,calendar,time from java.io import * from javax.servlet.http import HttpServlet from JythonServletUtils import * class JythonServlet3 (HttpServlet): def doGet(self,request,response): self.doPost (request,response) def doPost(self,request,response): toClient = response.getWriter() response.setContentType ("text/html") toClient.println ("<html><head><title>Servlet Test 3</title>") toClient.println ("<body><h1>Calendar</h1><pre>%s</pre></body></html>" % calendar.calendar(time.localtime()[0])) if __name__ == "__main__": JS3 = JythonServlet3() dummyRequest = DummyHttpRequest() dummyResponse = DummyHttpResponse() JS3.doPost (dummyRequest,dummyResponse) You will also need to create the JythonServletUtils module referenced in that code. Create another file called JythonServletUtils.py with the following code: from java.lang import System class DummyHttpRequest: pass class DummyHttpResponse: def setContentType(self,t): System.out.println ("Content-Type:%s" % t) def getWriter (self): return System.out After creating these files you should be able to access Sean's calendar sample on . Hopefully all of these instructions worked for you and you are now productively writing Jython servlets. Make sure to read Sean's tutorial for more about programming servlets in Jython and keep watching his blog for more updates to the tutorial.(2005-03-24 13:48:16.0) Permalink Comments [2] Yeah, I know. Almost a month since my last post and a long time since I've been posting regularly. February was insane. In addition to just being a busy month in general, I took on a major project for my boss's boss that I knew I didn't have time for. Plus I was a speaker at CEC and had a huge amount of prep work for that. And then I got sick (probably from working the crazy schedule I was working). But things are better now. Once I clear some backlog I have lots of stuff I want to post. But one thing caught my attention today that should be quick to post. Tim Bray points out the benefits of blogging on your personal career. It made me laugh because it reminded me so much of Jonathan's talk at CEC. Like many of Jonathan's talks, his opening line was: "Do you read my blog? You should.". His next comment (if I recall correctly) was encouraging the audience to blog. Immediately afterwards, he asks if John Clingan is in the audience. I've seen him do this multiple times now. John is clearly a rock star. (Or techno celeb if you prefer Mary's terminology.) When your boss's boss's boss's boss's boss's boss asks for you by name when walking into a crowd of thousands because of your celeb status, that has to be good for both your career and your job satisfaction. I'll take it as a lesson learned and try to get back to blogging regularly. :-)(2005-03-10 12:56:09.0) Permalink] This is the wrap up to my series about Java Metadata (aka annotations). Part one here, part two here. In the previous two sections I discuss the basics of metadata and some of the interesting advanced functionality available through the apt annotation processing tool. In this section I'll present some of my thoughts about how metadata affects the future of Java and some of the pros and cons of using metadata today. If you've ever heard the Java engineering folks (both J2SE and J2EE) speak, you'll know that they are very excited about the possibilities that metadata brings to Java. Both the J2SE and J2EE teams are looking for ways to make Java easier to learn and use. Metadata is a way for them to reduce lines of code required while at the same time as improving code readability and tools support. There are lots of examples of using metadata in active JSRs. Metadata is going to be used to enable declarative web services, O/R Mapping, and the next version of CMP. There is also the hope that tools vendors are going to find interesting ways to use annotations. Perhaps custom annotation libraries. Perhaps GUI tools that use annotation markers to enable full lifecycle development. But it is easy to see that while metadata may not be commonplace in production code yet, a couple of years it is going to be an integral part of Java. Knowing how to use metadata will be as important as knowing how to use the Collection library or deployment descriptors. Unfortunately, however, metadata is still on the bleeding edge of Java. Java 5.0 has dipped its toe into the water of declarative programming by introducing metadata into the language. But using the more advanced features, like modifying the behavior of the compiler, requires you to use apt and APIs like com.mirror.* that aren't guaranteed not to change. Not to mention that tools like apt do not have any tools support and have some known bugs. It was very frustrating not being able to use tools like ant in my demo because of their lack of apt support. Not to mention the fact that my IDE wasn't smart enough to know that the Factory classes were going to be autogenerated. As much as the J2SE team would like to see apt begin to replace other tools like XDoclet, there are still significant gaps that have to be addressed before apt becomes a mainstream tool. It reminds me of the early days of JSP where you had to be careful about which API's you used because of the differences between the 0.92, 1.0, and 1.1 specifications. I can't really recommend that creating customer annotation processors be a part of enterprise application development yet. The tool support and API stability isn't there yet. But there isn't any question that metadata is going to be a fact of life for Java developers. Nor is there any doubt about the power that annotations will be able to bring to developers and tool vendors. So I recommend that everyone get familiar with the basic syntax of Java annotations. It's going to be an absolute requirement for using J2EE 5.0. But I'd also recommend that people start to experiment with what is possible in apt. When you are architecting your code, think about what would be better expressed as declarative functionality and how you might implement it as an annotation. Write a demo application or step through mine to learn some of the possibilities for metatdata. Because, based on the current JSRs, metadata is going to be adopted very rapidly by the Java community. Being able to demonstrate your ability to extend the functionality of Java via metadata will be a very powerful competitive differentiator for developers.(2005-02-01 19:16:52.0) Permalink So I have a couple of websites I maintain as side projects. The one I've been spending the most time recently is my Mom's fabric arts page. Because of some of the precise layout that my Mom wanted, I used XHTML and CSS to layout the pages. Which is great: CSS is easier to do than table based layout and greatly reduces the page size. But browser compatibility has haunted me somewhat. The nastiest example so far was that my Mom updated a couple of the pages to make a couple of minor tweaks. But once she made the changes the pages no longer rendered correctly in Internet Explorer. I was trying to troubleshoot the problem, but couldn't find anything wrong with the code. It was the exact same CSS style code as all of the other pages. It turns out that Outlook Express had added an HTML comment to the top of the HTML page when my Mom saved some versions of the page we had been emailing back and forth. I hadn't noticed it because it was just a comment. But as HTML gurus know, browsers look at the first line of the HTML to determine the DOCTYPE and sometimes adjust their rendering based on that DOCTYPE. IE was rendering most of the pages correctly because it was using a strict XHTML mode. But with the comment at the top it must have fallen back to a quirks mode that didn't render the page correctly. This triggered one of my longtime frustrations: comments that affect behavior. In everyone's first computer language class they are taught that comments are for increasing code readability but do not affect the functionality of the application. Shortly thereafter, however, we start learning all of the little exceptions to that rule. UNIX scripts declare their interpretive shell in comments. Java embedds its API documentation in comments. HTML embeds style sheet and script information in comments. This has always bothered me. It seems a dangerous practice that violates the "contract" between developers and their code. This IE troubleshooting was a perfect example: I completely ignored the comment because my mind just automatically ignored it. And Dreamweaver helped me ignore it by greying it out. Both Dreamweaver and I were making the bad assumption that comments don't affect the layout. I've learned to just accept this practice because we've needed these hacks. JavaDoc is a great feature of Java even if it violates my aesthetics about comments. Metadata, however, has the chance to clean up some of these hacks, at least in the Java world. It gives a way to let tools interact with source code without having to hide the interaction from the compiler using comments. HAll of the examples above (JavaDoc, shell interpreters, HTML styles/scripts, and HTML DOCTYPES) are really examples of application metadata. Now that Java has a declarative method for Metadata, hopefully we can move forward with cleaner code.(2005-01-31 12:02:28.0) Permalink This week I'm out at Sun's corporate offices in California. A bunch of us software folks are getting some advanced training and some face time with the product engineering folks. This is a good thing, especially considering the new versions of Java Enterprise System and Sun Java System Application Server around the corner. Unfortunately, I live in an area with relatively poor access to airports. I can drive east an hour and a half to a major airport or I can drive west an hour and a half to a smaller airport. Driving to the major airport is tough during rush hour and is susceptible to all kinds of traffic, parking, and security delays. The smaller airport, Harrisburg International, is a much more pleasant drive, the service is great, and it's generally just easier getting in and out. They even promote themselves as the "antidote to the big airport". So, when the flight schedules work out, I choose to fly out of the smaller airport. Now I'm a pretty seasoned business traveler. I think that I'm pretty savvy about the whole process. I pack light. I always have my iPod so that I can kill time. But most importantly I try to keep a positive attitude about the whole experience. Because when you travel frequently, you are going to run into problems sooner or later. My cardinal rule for travel is to be nice to gate agents and to trust them to help you. I've had lots of issues when traveling, some of them my own fault, but the airlines have always done the best the could for me. (Everyone should have to watch the TV show Airline before getting upset with a gate agent.) So when I ran late on Sunday and missed my flight I was optimistic that the airline would be able to help me out. Unfortunately, however, being at a smaller airport does limit your choices significantly. Harrisburg only has a dozen or so gates, and they are divided between a lot of airlines. Combine that with a flood of people heading to San Francisco for MacWorld and some bad weather on the west coast and I was pretty much out of luck. I'm stunned at how crazy San Francisco is over MacWorld. The flights are packed. Changing car and hotel arrangements has been near impossible. Anyway it's been a stressful day and a half getting here. I finally made it to my hotel room. I guess the lesson to learn from this experience is to know when the system has a small tolerance for failure and to plan accordingly. I suppose the same thing could be said about software system design. A skilled system architect should be able to know in advance where to the stress points of a system will be and to put plans in place to reduce those risks. That's a big stretch to try and create an analogy, but you'll have to forgive me. It's a been a long day.(2005-01-10 23:42:08.0) Permalink I really have to stop taking on big blog articles like this. They always take a lot longer to write than I expect. It's been a month since the last article in this series, but here we go with part two on my annotations preso, converted to blog format. Sorry it's so long, I really should have broken it into smaller posts. But I got on a roll and since I'm a month late I figured I might as well get it done. Last article was just a basic introduction to the concept of Metadata. We introduced annotations, the reason behind introducing them into Java, the basic syntax for using annotations, and the built-in annotations. Now that we understand the basics of metadata, we can now take a look at the more interesting topic of how to create our own metadata. The pre-built annotations have a certain amount of value, but creating your own annotations is where metadata gets interesting. (At least until EJB 3.0 and J2EE 1.5, which will have lots of time saving new annotations.) Why would we want to create a new annotation? @inject (arg="ObjectPoolSize", field="size") @todo (owner="David F. Ogren", note="upgrade") There are several articles on the web about how to add markers to code and how to use reflection to allow code to inspect itself. I'd recommend starting with the annotations section of the language guide. It walks through creating a new marker interface @Preliminary and creating a single valued interface of @Copyright. It also creates a @Test marker interface and then shows how to use reflection to determine if that marker exists for a given class. I'm not going to take a lot of time detail those simple examples again here. In summary, creating new annotations is a lot like creating new interfaces. The major difference (besides the @ symbol) is that you have to be conscious of the meta annotations such as @Retention and @Target. And there are some new methods and in the java.lang.reflect package such as isAnnotationpresent and getDeclaredAnnotations that allow you to detect and manipulate annotations. Here's a quick example of a single value custom annotation with a default value. And here is a little command line app to parse for those annotations:And here is a little command line app to parse for those annotations:package AnnotationDemo; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Maintainer { String value() default "unknown"; } package AnnotationDemo; //This class accepts a class and returns the value of the @maintainer //annotation. (If the targeted class has one.) @Maintainer(value="ogren") public class SingleValueDemo { public static String findMaintainer(String className) { String maintainer; try { Maintainer notation = (Maintainer) Class.forName(className).getAnnotation(Maintainer.class); if (notation!=null) { maintainer="Maintainer is " + notation.value(); } else { maintainer="Class exists but is not annotated with maintainer."; } } catch (ClassNotFoundException e) { maintainer= "No such class found"; } return maintainer; } public static void main(String[] args) { if (args[0]!=null) { System.out.println(findMaintainer(args[0])); } else System.out.println("Usage: SingleValueDemo classname"); } } But if you want to change the compiler behavior, the most interesting part of annotations in my opinion, you have to venture into the world of apt and annotation factories. apt is a javac replacement that finds and executes annotation processors. Yes, this means that you have to change your build chain if you want to use these new features. If you use javac directly it will not perform all of your custom metadata enhanced behavior. Annotation Factories implement a simple interface with three methods: getProcessorFor, supportedAnnotationTypes, and supportedOptions. These three methods allow the apt tool to determine which factories are interested in which annotation types and to obtain a AnnotationProcessor object for a given annotation type. Here is the bulk of the code from the annotation factory I use in my demo: (for the reasons I explained a while ago, I'm not going post all of the code.) public class PooledFactoryApf implements AnnotationProcessorFactory { private static final String FQTAGNAME = "AnnotationDemo.PooledFactory"; //(This commented line is how you would declare the annotations you support. //So that this demo can watch all //annotations, however, this factory tells apt we process all ("*") annotations. // private static final Collection supportedAnnotations = // Collections.unmodifiableCollection(Arrays.asList("AnnotationDemo.PooledFactory")); private static final Collection supportedAnnotations = Collections.unmodifiableCollection(Arrays.asList("*")); private static final Collection supportedOptions = emptySet(); public Collection supportedAnnotationTypes() { return supportedAnnotations; } public Collection supportedOptions() { return supportedOptions; } public AnnotationProcessorFor( Set atds, AnnotationProcessorEnvironment env) { return new PooledFactoryProcessor(env); } } The code is pretty self explanatory. You return collections of Strings defining the annotations and options you support. You can use wildcards in those Strings to support ranges of items. My particular demo accepts all annotations (just for demo purposes) and no options. And when asked for a AnnotationProcessor the factory blindly returns the PooledFactoryProcessor which I define below, regardless of what the annotation is or what is going on in the environment. The AnnotationProcessor is the place where we we actually place our customized behavior. AnnotationProcessors support a simple interface with only one method: process(). Once the apt tool has obtained the correct AnnotationProcessor from the factory, it will call the process method. Once we receive this call to the process method we can use the environment (which we received during construction) to search for instances the annotation we are looking for and perform our custom behavior. For my demo application I developed an annotation that would automagically generate the code to implement a factory pattern classes it decorates. In theory, this could be used to automatically make any class a pooled resource, although I built this as a proof of concept and didn't actually add the logic to implement pooling. Here is the declaration for my annotation: @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface PooledFactory { int poolSize(); } As you can see it is a single valued annotation that marks types (classes and interfaces) and is discarded after compilation. The annotation is discarded after compilation because its job generating the factory code is complete after compile time. Another thing to note is that legally this annotation could be placed on an interface since the annotation syntax considers both classes and interfaces to be types. My demo does throw an error at compile time if an interface is marked with @PooledFactory, but it will not show up as syntactically invalid in an IDE. The following is a simple illustration of how the @PooledFactory annotation might be used: Clients would then access an instance via the automatically generated factory class:Clients would then access an instance via the automatically generated factory class:@PooledFactory(poolSize=4) public class ExpensiveClass { ExpensiveClass() { System.out.println( "For some reason, I take a long time to create so I am being pooled."); } public void someMethod() { System.out.println("Some business method is executing"); } } ExpensiveClass myClass = ExpensiveClassFactory.getInstance(); myClass.someMethod(); ExpensiveClassFactory.returnInstance(myClass); To me, this is why annotations are exciting. We have just extended Java with a new piece of declarative functionality. If we are using a profiler and discover a bottleneck creating ExpensiveClass objects we can attempt a fix with three lines of code (one to add the annotation, one to change the allocation, and one to return the object to the pool). We also get the added benefits of code readability and code reuse. So let's implement the code generation in the AnnotationProcessor. The first step is to receive the process() call from apt and find all of the classes that are marked with our annotation: private final AnnotationProcessorEnvironment env; private final AnnotationTypeDeclaration myType; PooledFactoryProcessor(AnnotationProcessorEnvironment env) { this.env = env; this.myType = (AnnotationTypeDeclaration) env.getTypeDeclaration("AnnotationDemo.PooledFactory"); } public void process() { Collection annotatedClasses = env.getDeclarationsAnnotatedWith(myType); for (Declaration decl : annotatedClasses) { if (decl instanceof ClassDeclaration) //this method creates the new source file createFactorySource((ClassDeclaration) decl); else env.getMessager().printWarning( "An interface was marked with @PooledFactory"); } } In the constructor we save the environment we receive from the factory and save the AnnotationTypeDeclaration we are looking for. Once in the process method all we have to do is use the com.sun.mirror.apt.AnnotationProcessorEnvironment to get a list of types that implement our annotation and then iterate over that Collection (using the new foreach style of for loop). As mentioned before we have to check to make sure that our types are classes and then we can execute our custom method (below) to generate the new java source. Notice how that we can print a compiler warning via the AnnotationProcessorEnvironment object. We could use the same technique to implement annotations that perform syntax checking or analysis. The createFactorySource method is were we actually generate the new source file for the factory class. This demo uses a very simplistic method for doing so, shown below: void createFactorySource(ClassDeclaration decl) { //Determine new class name String realClass = decl.getSimpleName(); String newClassName = realClass + "Factory"; String newQualName = decl.getQualifiedName() + "Factory"; System.out.println("Attempting to create factory :" + newQualName); try { PrintWriter out = env.getFiler().createSourceFile(newQualName); out.println("//autogenerated by PooledFactoryProcessor"); out.println("package " + decl.getPackage() + ";"); out.println("public class " + newClassName +" { "); out.println("public static " + realClass + " getInstance() { return new " + realClass + "(); }"); out.println("public static void returnInstance( " + realClass + " old) { }"); out.println("}"); } catch (java.io.IOException e) { System.out.println("Factory already exists or cannot be created"); } } This class is a bit of a hack, but it shows the basics of source code generation. We figure out what class name (and qualified class name) to use and then use the AnnotationProcessorEnvironment to get a PrintWriter leading to a new source file. (The new source file ends up getting created in a temp directory that can be specified using the -s apt argument.) We then write out the new code to PrintWriter and apt handles the rest. It will automatically pass the new code through the AnnotationFactory again since we might have annotations in our generated code. After that recursive step completes it will then use javac to compile all of the code, including our generated code. At that point ExpensiveClassFactory exists just as if it had been coded by hand. Obviously this is just a little demo hack and doesn't do any real pooling. Real world code generation takes more than six println statements. But it illustrates the basics of modifying compile time behavior and its a lot more fun than the little reflection samples I see in most annotation tutorials. The same techniques cold be used to do all kinds of powerful compile time behavior. In the next an final chapter, I'll share some my closing thoughts about metadata. I'll talk about the pros and cons of apt and the future of annoations, such as how metadata will be used in J2EE 1.5 and EJB 3.0.(2005-01-06 06:47:40.0) Permalink
http://blogs.sun.com/roller/page/ogren/
crawl-001
refinedweb
6,829
56.05
If there’s one thing guaranteed to spark a huge amount of e-mail on any of our mailing lists, it’s raising the issue of the difference between an information resource (IR) and a non-information resource (NIR). The poster boy example is that of a toucan*. If I put in my browser I might receive all manner of things down the wire. An image of a toucan, an audio clip of its call, a video of it in flight. Who knows, I might receive the virtual reality experience of having a toucan sitting on my desk. But a toucan cannot be transmitted as a series of bytes. The most recent version of this debate began with a blog post by Ian Davis, CTO of (W3C Member) Talis, in which he argued for a new solution to the IR/NIR debate for linked data. After several days of intense e-mail discussion, he posted an updated version that relies on the Content-location HTTP header to disambiguate between the two. Whether the proposal survives and becomes an accepted alternative way of publishing an electronic document describing a real world object, both of which have URI identifiers, remains to be seen. But it looks hopeful and well worth considering. It was during the debate that I realised that there was a mistake in the POWDER specifications, work on which I lead between 2007 and 2009. Admitting a mistake is always embarrassing but not to do so would only prolong the agony. As part of POWDER, we specified a link relationship type of describedby. Now included in RFC 5988, this is a very general relationship that is defined thus: The relationship A ‘describedby’ B asserts that resource B provides a description of resource A. There are no constraints on the format or representation of either A or B, neither are there any further constraints on either resource. So far so good. But POWDER can be serialized as RDF/OWL and so we wanted to create a semantically identical RDF property. The relevant prefix used is wdrs so the property in question is wdrs:describedby. The error made was that we had written into the namespace document and one part of the spec an inference that wdrs:describedby pointed specifically to POWDER documents. This was a mistake as evidenced by other parts of the text. So, an erratum has been published, with full details of the error, the (unlikely but) possible implications and the steps taken already to rectify the situation. Having done this, we can say that all of the following are legitimate and semantically identical: - XHTML, ATOM <link rel="describedby" href="/doc" type="foo/bar" /> - HTTP Link: </doc>; rel="describedby" type="foo/bar"; - RDF @prefix wdrs: <> . <> wdrs:describedby </doc> . * Anyone know where the toucan meme came from originally? 5 thoughts on “A toucan describedby data” I actually just made up the toucan idea as I was writing my first post. I just needed an example of something that clearly wasn’t an electronic document. Phil, You wrote: what about inert object. If the URI contains all instructions which leads to the copy of the object at a different place. I’m thinking about fabs for example. It will not be the same atoms, but does it matter? Just silly thoughts in the afternoon. :) I think your describedby is similar in meaning to foaf:topic, and to one use of dcterms:subject. There are some variations… X foaf:topic Y, says that Y is one of the (possibly many) things that is a subject/topic of (a Document) X. (Y foaf:page X says the same thing backwards) X foaf:primaryTopic Y, says that Y is the thing that is the main or primary topic of the document X. (Y foaf:isPrimaryTopicOf X says the same thing backwards; also foaf:homepage is similar, but raises some broad expectations/intuitions about the kind of document, it’s content, role etc.) X dcterms:subject Y says that either Y is a subject code that stands for one or more of document X’s subjects; perhaps represented as a string, or using SKOS. Or in some uses, same as foaf:topic, that Y (perhaps a Person or Place) is one of the things that X is actually about. As an aside, foaf:focus is a relationship that mediates between these two idioms; it links from a ‘subject as a thing’ to the thing itself, eg. from a SKOS concept of the city Paris, to ‘Paris itself’. If we see X wdrs:describedby Y, … is it more like foaf:page, or foaf:isPrimaryTopicOf? That is, could it be repeated with multiple non-identical values? Is it an inverseFunctionalProperty? Can we figure out the mappings between all these similar constructs? Dan. I quite see your point, and that there are many instances where foaf:topic etc. may be used where wdrs:describedby is used. However, if we anchor our thinking in the @rel type of describedby, the object of the wdrs:describedby property is always expected to be a URIref and never a literal. Can you have X foaf:topic Y or X dcterms Y where Y is a string literal? A wise person (you) once told me that the finest specification writing can never tell people exactly how to use something. The final arbiter is always implementations and common consensus. If an individual feels that foaf:topic or foaf:isPrimaryTopic or dcterms:subject is appropriate to their situation, that’s what they’ll use. I think in the particular scenarios that @iand was talking about wdrs:describedby is a marginally better fit, but only marginally. Hi Phil. Yes, foaf:topic is always a thing, a thing that some doc is about. Re Dublin Core … the dc usage in the subject: is a mix of strings and things. I believe the intent with the newer dcterms namespace is to point more to things, but that this isn’t an absolute rule. I’ve absolutely no problem with people using other properties, for whatever reason. But if there are actual counter examples where the one property (on its own definition) applies, and the other doesn’t, we ought to write those down so that folk have a clear map of the options. Do we have one for the subject / topic / describedby situation yet?
http://www.w3.org/blog/2010/11/a-toucan-describedby-data/
CC-MAIN-2015-06
refinedweb
1,056
61.77
Credit: Doug Blanding Your image files are in various formats (GIF, JPG, PNG, TIF, BMP), and you need to convert among these formats. The Python Imaging Library (PIL) can read and write all of these formats; indeed, net of user -interface concerns, image-file format conversion using PIL boils down to a one-liner: Image.open(infile).save(outfile) where filenames infile and outfile have the appropriate file extensions to indicate what kind of images we're reading and writing. We just need to wrap a small GUI around this one-liner functionalityfor example: #!/usr/bin/env python import os, os.path, sys from Tkinter import * from tkFileDialog import * import Image openfile = '' # full pathname: dir(abs) + root + ext indir = '' outdir = '' def getinfilename( ): global openfile, indir ftypes=(('Gif Images', '*.gif'), ('Jpeg Images', '*.jpg'), ('Png Images', '*.png'), ('Tiff Images', '*.tif'), ('Bitmap Images', '*.bmp'), ("All files", "*")) if indir: openfile = askopenfilename(initialdir=indir, filetypes=ftypes) else: openfile = askopenfilename(filetypes=ftypes) if openfile: indir = os.path.dirname(openfile) def getoutdirname( ): global indir, outdir if openfile: indir = os.path.dirname(openfile) outfile = asksaveasfilename(initialdir=indir, initialfile='foo') else: outfile = asksaveasfilename(initialfile='foo') outdir = os.path.dirname(outfile) def save(infile, outfile): if infile != outfile: try: Image.open(infile).save(outfile) except IOError: print "Cannot convert", infile def convert( ): newext = frmt.get( ) path, file = os.path.split(openfile) base, ext = os.path.splitext(file) if var.get( ): ls = os.listdir(indir) filelist = [ ] for f in ls: if os.path.splitext(f)[1] == ext: filelist.append(f) else: filelist = [file] for f in filelist: infile = os.path.join(indir, f) ofile = os.path.join(outdir, f) outfile = os.path.splitext(ofile)[0] + newext save(infile, outfile) win = Toplevel(root) Button(win, text='Done', command=win.destroy).pack( ) # Divide GUI into 3 frames: top, mid, bot root = Tk( ) root.title('Image Converter') topframe = Frame(root, borderwidth=2, relief=GROOVE) topframe.pack(padx=2, pady=2) Button(topframe, text='Select image to convert', command=getinfilename).pack(side=TOP, pady=4) multitext = "Convert all image files\n(of this format) in this folder?" var = IntVar( ) chk = Checkbutton(topframe, text=multitext, variable=var).pack(pady=2) Button(topframe, text='Select save location', command=getoutdirname).pack(side=BOTTOM, pady=4) midframe = Frame(root, borderwidth=2, relief=GROOVE) midframe.pack(padx=2, pady=2) Label(midframe, text="New Format:").pack(side=LEFT) frmt = StringVar( ) formats = ['.bmp', '.gif', '.jpg', '.png', '.tif'] for item in formats: Radiobutton(midframe, text=item, variable=frmt, value=item).pack(anchor=NW) botframe = Frame(root) botframe.pack( ) Button(botframe, text='Convert', command=convert).pack( side=LEFT, padx=5, pady=5) Button(botframe, text='Quit', command=root.quit).pack( side=RIGHT, padx=5, pady=5) root.mainloop( ) Needing 80 lines of GUI code to wrap a single line of real functionality may be a bit extreme, but it's not all that far out of line in my experience with GUI coding ;-). I needed this tool when I was making .avi files from the CAD application program I generally use. That CAD program emits images in .bmp format, but the AVI [1] -generating program I normally use requires images in .jpg format. Now, thanks to the little script in this recipe (and to the power of Python, Tkinter, and most especially PIL), with a couple of clicks, I get a folder full of images in .jpg format ready to be assembled into an AVI file, or, just as easily, files in .gif ready to be assembled into an animated GIF image file. [1] AVI (Advanced Visual Interface) [1] AVI (Advanced Visual Interface) I used to perform this kind of task with simple shell scripts on Unix, using ImageMagick's convert command. But, with this script, I can do exactly the same job just as easily on all sorts of machines, be they Unix, Windows, or Macintosh. I had to work around one annoying problem to make this script work as I wanted it to. When I'm selecting the location into which a new file is to be written, I need that dialog to give me the option to create a new directory for that purpose. However, on Windows NT, the Browse for Folder dialog doesn't allow me to create a new folder, only to choose among existing ones! My workaround, as you'll see by studying this recipe's Solution, was to use instead the Save As dialog. That dialog does allow me to create a new folder. I do have to indicate the dummy file in that folder, and the file gets ignored; only the directory part is kept. This workaround is not maximally elegant, but it took just a few minutes and almost no work on my part, and I can live with the result. Information about Tkinter can be obtained from a variety of sources, such as Fredrik Lundh, An Introduction to Tkinter , (PythonWare:), New Mexico Tech's Tkinter Reference (), Python in a Nutshell , and various other books; PIL is at. Python in a Nutshell, Second Edition (In a Nutshell) Python Pocket Reference: Python in Your Pocket (Pocket Reference (O'Reilly)) Programming Python Python Essential Reference (4th Edition) The Quick Python Book, Second Edition
http://flylib.com/books/en/2.9.1.233/1/
CC-MAIN-2013-20
refinedweb
857
59.19
One of the most common ways of terrain texturing is blending multiple tiled layers. Each layer has an opacity map which defines the extent of texture presence on the terrain. The method works by applying an opacity map to the higher levels, revealing the layers underneath where the opacity map is partially or completely transparent. Opacity map is measured in percentage. Of course on each point of a terrain the sum of opacities of all layers makes one-hundred percent as the terrain can't be transparent. Instead of tile textures, the opacity map stretches entirely on all terrain and therefore has quite a low level of detail. Now we will pass to the most interesting part — algorithms of blending of textures. For simplicity and obviousness our terrain will consist of sand and large cobble-stones. Simplest way of blending is to multiply texture color with opacity and then sum results. float3 blend(float4 texture1, float a1, float4 texture2, float a2) { return texture1.rgb * a1 + texture2.rgb * a2; } Such a technique is used in Unity3D in the standard terrain editor. As you can see, the transition is smooth but unnatural. Stones look evenly soiled by sand, but in the real world it doesn't happen like that. Sand doesn't stick to stones, instead it falls down and fills cracks between them, leaving the tops of stones pure. Let's try to simulate this behavior in Excel plots. As we want sand to be "fallen down" between cobble-stones, for each texture we need the depth map. In this example we consider the depth map is generated from grayscaled image and stored in the alpha channel of a texture. In Unity3D it can be done in the texture inspector by setting the flag "Alpha From Grayscale". First of all we will consider the simplified model of depth map of sand and stones. The blue line on the plot symbolizes the depth map of sand and red is cobble-stones. Notice that tops of stones lie higher than sand level. Considering this fact, we will try to draw pixels of that texture which is above. float3 blend(float4 texture1, float a1, float4 texture2, float a2) { return texture1.a > texture2.a ? texture1.rgb : texture2.rgb; } Excellent! Tops of cobble-stones remain pure whereas sand lies in cracks between them. But we didn't consider layer opacity yet. To use it we just sum depth map and opacity map. float3 blend(float4 texture1, float a1, float4 texture2, float a2) { return texture1.a + a1 > texture2.a + a2 ? texture1.rgb : texture2.rgb; } At the expense of summation less transparent texture will be higher than usual. So we have a more natural transition from sand to stones. As you can see, grains of sand start filling cracks between cobble-stones, gradually hiding them. But as calculations happens pixel-by-pixel, artifacts begin to appear on the border between textures. To get a smooth result we will take several pixels in depth instead of one and blend them. float3 blend(float4 texture1, float a1, float4 texture2, float a2) { float depth = 0.2; float ma = max(texture1.a + a1, texture2.a + a2) - depth; float b1 = max(texture1.a + a1 - ma, 0); float b2 = max(texture2.a + a2 - ma, 0); return (texture1.rgb * b1 + texture2.rgb * b2) / (b1 + b2); } In the code above we at first get part of a ground seen at a certain depth. And then we normalize it to get new opacities. As a result we found the algorithm of textures blending, which allows us to reach close to a natural terrain image. In summary I want to explain what this algorithm was developed for and how we use it. The shader was developed for turn-based strategic indie game Steam Squad. As engine and developing platform we use Unity3D. And as the Unity IDE is extremely flexible, we made our own level designer extension. In general the level designer is a simplified Unity3D terrain editor with some features of Titan Quest Editor. When you paint the texture on a terrain there is a recalculation of the opacity map corresponding to this texture. And as the sum of all opacities has to make 100%, the editor automatically normalizes opacity maps of other layers. Here is short YouTube video showing how it works. Shader which uses this algorithm in Unity3D Asset Store License GDOL (Gamedev.net Open License) That's a really cool technique! It adds quite a lot visually for only a little work. Thanks for sharing! This is one of those techniques that when seen, causes you to ask yourself: "Why hasn't anyone thought of this before?" The bottom picture looks natural. This is very impressive! I think many people have, the issue is the draw call and the load times; which leads me to my question. Doesnt the pixel shader run slower and cause considerable lag on a procedurally generated terrain setup? This setup would work on solid, never changing terrain, but I think it would cause serious issues with terrain that was to change on a constant or semi constant basis. Each modification of the land would require another draw call, would it not? Also, with our system we have been looking at doing this but we have 3 textures maps ( normal, specular, color ). Each one of these would need a new sample, this means 3 * 3 = 9 samples. We would have to blend this with another texture ( for the edges of the blocks/regions ) making a total of 18 samples.... is this correct? I have no clue why my post generated two down votes... as there was nothing negative about it. Oh well.... whatever! Seemed to me like you raised some valid points. O.o I like it as well... i just want to understand how it could be used in a modular world rather than a static one. Riuthamus, good questions! Shader behaves exactly like default one. Of course, it has more math operations, but delay is absolutely insignificant. In the my implementation of shader I can blend 9 textures: 4 color maps + 4 normal maps + noise map. And with some math magic I still fit in SM2.0 limitations. Also with some storage magic the changing of texture transparency isn't more difficult than moving point of a mesh. I can change it in realtime, but changing of set of textures is still expensive operation. Sorry but I can't show you all sources because the shader is part of commercial project. It would be helpful to people attempting to duplicate your results if the textures depicted above could be provided (or a modified version of them, such as with a text watermark). You. Great effect, thanks for sharing! This'd look nice with some sort of emboss-mapping like effect. Amazing! Keep up the good work! I implemented this technique in Unity3D. You can find shaders in Unity Asset Store and here is a demo. Thanks Andrey, this technique is beyond fantastic!
http://www.gamedev.net/page/resources/_/technical/graphics-programming-and-theory/advanced-terrain-texture-splatting-r3287?st=0
CC-MAIN-2016-44
refinedweb
1,164
66.94
On Thu, Feb 24, 2011 at 08:37:00PM +0100, Diego Elio Petten? wrote: > Il giorno gio, 24/02/2011 alle 18.12 +0100, Michael Niedermayer ha > scritto: > > > > + CODEC_ID_UNUSED_USE_FOR_NEXT_CODEC > > #endif > > You forgot a comma. > > [Add yourself a snide comment on not testing the change] i tested it. under the old versions it works. for testing under the new version ffmpeg first has to compile in that case. it doesnt. a patch with , is attached If you still want a snide comment i can look into that too? [...] --: 0001-Replace-CODEC_ID_XVID-by-CODEC_ID_UNUSED_USE_FOR_NEX.patch Type: text/x-patch Size: 784 bytes Desc: not available URL: <> -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: Digital signature URL: <>
http://ffmpeg.org/pipermail/ffmpeg-devel/2011-February/105113.html
CC-MAIN-2016-44
refinedweb
126
67.45
Before delving too deep into scope rules with Java, you should keep in mind the benefits of restricting access to an object’s data using encapsulation techniques. In addition, you should be aware that by limiting access to data and methods, you can modify the implementation of our object's infrastructure without changing the public interfaces. This is important because it allows future enhancements to be made with very little impact on existing programs, thus avoiding backward-compatibility problems. If you need a refresher on these topics, I recommend you take a look at "Intro to OOP: Restricting access to object properties." Here, we will further explore Java’s scope features and begin looking at how Java objects are constructed and initialized. Catch up on past articles covering the transition to OOP with Java - "Transitioning into object-oriented programming using Java" - ”Intro to OOP: Understanding classes and objects” - "Intro to OOP: A closer look at inheritance and polymorphism" - "Intro to OOP: Restricting access to object properties" A deeper look into scope The scope modifiers provided by Java give us the ability to limit the access to our methods and fields as we see fit. This enables us to encapsulate the data within our classes and to hide the data from outside access. Remember the difference between public, private, protected, and package scope. Public scope exposes a method or field to all outside access, and private scope completely hides a method or field from all outside access. Protected scope allows limited access from outside. Package scope groups related classes into a package using a kind of reverse domain-naming mechanism. Let's take a look at how we can use packages to encapsulate groups of classes. Java restricts each source file to one public class. The source file must be named the same as the public class. Thus, the class HelloWorld should be placed in the file HelloWorld.java. With this in mind, a company named Acme might place the HelloWorld class in a package named com.acme.apps. This would make the full, or qualified, name of the HelloWorld class com.acme.apps.HelloWorld. Let's assume that the Acme Company wants to create some utility classes for the HelloWorld application to use. They might place the utility classes in a package named com.acme.utils. Perhaps the Acme Company needs some specialized input/output classes. They could place them in a file named AcmeIO.java inside the com.acme.utils package. The public class inside the AcmeIO.java file would have the qualified name com.acme.utils.AcmeIO. Now, the HelloWorld class could use the AcmeIO class to perform specialized input/output. Since the AcmeIO class belongs to a different package than HelloWorld, the AcmeIO class must be "imported" into the HelloWorld class before HelloWorld can use it. This is accomplished either by referring to the AcmeIO class by its qualified name, com.acme.utils.AcmeIO, or placing an import statement at the top of the file, as follows: import com.acme.utils.AcmeIO; This import statement imports one class from the com.acme.utils package. We could use the import statement to import all classes from the AcmeIO package by using a wildcard, as follows: import com.acme.utils.*; The name space created by Java's package and import mechanisms allow the Acme Company and any other company to define classes with the same name without running into name conflicts. Remember that private scope restricts outside callers from accessing the data of an object and that public scope allows all outside callers access to our data or methods. Let's assume that we want all outside callers to have access to a particular method, but we don’t want them to override the method. Java offers the final modifier that enables this very thing. Defining a method or field as final restricts a caller of the method or variable from overriding or changing the method or variable, as follows: public final void addCustomer(CustomerData customer) { customers.add(customer); } The need arises, at times, for a method or field to be offered globally without the presence of an instantiated object. For this, Java offers the static modifier. Defining a method or field as static makes the method or field globally available to callers without creating an instance of the class. The Singleton pattern defines a class that instantiates, at most, one instance. This is a good case for a static or, as it is called, class method, as follows: public class Singleton { protected Singleton() { } private static Singleton _instance = null; public static Singleton getInstance() { if (null == _instance) { _instance = new Singleton(); } return _instance; } } To call a static method or access a static field, you must precede the method or field with the class name, as follows: Singleton localField = Singleton.getInstance(); Construction and initialization So far we’ve talked about objects, classes, operations on objects, properties of objects, and so on. Let's backtrack a little and discuss how Java objects are created and initialized. In Java, before an object can be used, it must be created, or instantiated. The process of object instantiation in Java is handled in two steps. First, the Java Virtual Machine (JVM) allocates the storage area for the object when the new operator is called. This is demonstrated as follows: _instance = new Singleton(); Second, the matching constructor is called on the object. For the above example, the constructor with no arguments is called. The code for this constructor is as follows: protected Singleton() { } Constructors are special code blocks that look a lot like methods but must follow certain guidelines, among them: - Constructors can have no return type. - Constructors cannot be called explicitly. - Constructors must be named the same as the class they belong to. - Constructors cannot be overridden. Constructors do share some similarities with methods, however, including the following: - Constructors can have public, package, protected, or private scope - Constructors can have an arbitrary list of arguments or no arguments at all The following examples are all legal constructor definitions for the Singleton class: public Singleton () { } private Singleton(String name) { _name = name; } Singleton(int ID, String name) { _ID = ID; _name = name; } The above examples would be called, respectively, when the following code is executed: Singleton firstObj = new Singleton(); Singleton secondObj = new Singleton("secondObj"); Singleton thirdObj = new Singleton(45, "thirdObj"); Moving on This article has been our look at how to use Java scope rules to limit access to data and methods. We also took a look at object instantiation and constructors. In our next article, we’ll talk about the intricacies and dangers of constructing and initializing Java objects.
http://www.techrepublic.com/article/intro-to-oop-java-scope-rules/5035301/
CC-MAIN-2016-30
refinedweb
1,101
51.68
Of course you know that XML denotes element names with greater-than and less-than symbols, such as: <name>value</name> Therefore, to avoid confusing the XML parser, the greater/less symbols (and the ampersand, an HTML special character) must be encoded. For example, given the following string: string text = "Here is a <Test String> & more"; To encode the string to an XML value, use the HttpUtility.HtmlEncode method: string xmlValue = HttpUtility.HtmlEncode( text ); The HttpUtility class is found in the System.Web namespace. Note that you may have to add a System.Web reference to your Windows Forms or Console project. Given the example above, xmlValue will be: Here is a <Test String> & more The XMLWriter class will encode values for you automatically, but this tip is handy if you are generating your own XML text. Note that if you need to encode text that will be used as an XML element name (rather than its value), you can use the XmlConvert.EncodeLocalName method found in the System.Xml namespace. It’s a mystery to me why the .NET designers did not include the HtmlEncode capability in the XmlConvert class. The ideal place would have been the overloaded XmlConvert.ToString method, which accepts just about every .NET native type except a string. Thanks. That was very helpful. This is a useful site. Awesome, dude, thanks! This wasn’t obvious when I was searching the massive .NET framework for a solution. Why does this not work in a VB.NET Windows Forms project? Imports System.Web Private Function EncodeText(ByVal sText As String) As String Return HttpUtility.HtmlEncode(sText) End Function The return value remains unchanged from the input (sText) variable.
https://www.csharp411.com/format-string-for-xml-value/
CC-MAIN-2021-43
refinedweb
281
68.36
Before we dig into CAS (Compare And Swap) strategy and how is it used by atomic constructs like AtomicInteger, first consider this code: public class MyApp { private volatile int count = 0; public void upateVisitors() { ++count; //increment the visitors count } } This sample code is tracking the count of visitors to the application. Is there anything wrong with this code? What will happen if multiple threads try to update count? Actually the problem is simply marking count as volatile does not guarantee atomicity and ++count is not an atomic operations. To read more check this. Can we solve this problem if we mark the method itself synchronized as shown below: public class MyApp { private int count = 0; public synchronized void upateVisitors() { ++count; //increment the visitors count } } Will this work? If yes then what changes have we made actually? Does this code guarantee atomicity? Yes. Does this code guarantee visibility? Yes. Then what is the problem? It makes use of locking and that introduces lot of delay and overhead. Check this article. This is very expensive way of making things work. To overcome these problems atomic constructs were introduced. If we make use of an AtomicInteger to track the count it will work. public class MyApp { private AtomicInteger count = new AtomicInteger(0); public void upateVisitors() { count.incrementAndGet(); //increment the visitors count } } The classes that support atomic operations e.g. AtomicInteger, AtomicLong etc. makes use of CAS. CAS does not make use of locking rather it is very optimistic in nature. It follows these steps: - Compare the value of the primitive to the value we have got in hand. - If the values do not match it means some thread in between has changed the value. Else it will go ahead and swap the value with new value. Check the following code in AtomicLong class: public final long incrementAndGet() { for (;;) { long current = get(); long next = current + 1; if (compareAndSet(current, next)) return next; } } In JDK 8 the above code has been changed to a single intrinsic: public final long incrementAndGet() { return unsafe.getAndAddLong(this, valueOffset, 1L) + 1L; } What advantage this single intrinsic have? Actually this single line is JVM intrinsic which is translated by JIT into an optimized instruction sequence. In case of x86 architecture it is just a single CPU instruction LOCK XADD which might yield better performance than classic load CAS loop. Now think about the possibility when we have high contention and a number of threads want to update the same atomic variable. In that case there is a possibility that locking will outperform the atomic variables but in realistic contention levels atomic variables outperform lock. There is one more construct introduced in Java 8, LongAdder. As per the documentation:. So LongAdder is not always a replacement for AtomicLong. We need to consider the following aspects: - When no contention is present AtomicLong performs better. - LongAdder will allocate Cells (a final class declared in abstract class Striped64) to avoid contention which consumes memory. So in case we have a tight memory budget we should prefer AtomicLong. That's all folks. Hope you enjoyed it. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/how-cas-compare-and-swap-java
CC-MAIN-2017-04
refinedweb
523
57.47
Build a realtime spreadsheets application - Part 1: Users and spreadsheets To follow this tutorial you will need PHP 7.2 or higher, with the MongoDB driver enabled. You will also need Composer, MongoDB and a Pusher account. This is part 1 of a 4-part tutorial. You can find part 2 here, part 3 here and part 4 here. Apps like Google Docs and Google Sheets are very popular today, partly because they allow users to easily share documents for others to collaborate. They also enable multiple users to work on the same document simultaneously without clashes or fear of lost data. In this four-part guide, we’ll build a spreadsheet app that works similar to Google Sheets. A user can create spreadsheets and share the link to the sheet with someone else, giving that person the ability to collaborate on the sheet in realtime without overwriting each other’s edits. Our app will also display the users who are currently viewing the sheet. Prerequisites - PHP 7.2 or higher, with the MongoDB driver installed. You can find installation instructions here. - Composer - MongoDB (version 3.4 or higher). Get it here. - A Pusher account. Create one here. Setting up the app Laravel by default uses SQL databases as the backend for its Eloquent models, but we’re using MongoDB in this project, so we’ll start off with a Laravel installation configured to use MongoDB. Clone the repo by running: git clone You can also. User authentication We’ll take advantage of the inbuilt user authentication system that comes with Laravel by running: php artisan make:auth We’ll need to configure a few things. Replace the create method of your app/Http/Controllers/Auth/RegisterController.php with the following: protected function create() { return \App\Models\User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), 'viewed_sheets' => [] ]); } Then in your app/Models/User.php, add viewed_sheets as an entry in the $fillable array: protected $fillable = [ 'name', 'email', 'password', 'viewed_sheets' ]; The viewed_sheets property is where we’ll store the IDs of all sheets the user has opened recently, so we can display them on the user’s dashboard. Building the user dashboard Now, let’s build the dashboard that a user sees when they log in. Similar to Google Sheets, we’ll display a list of spreadsheets they’ve viewed recently, along with a button to create a new spreadsheet. Replace the contents of your resources/views/home.blade.php with the following: @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">Dashboard</div> <div class="card-body"> <div class="text-center"> <a class="btn btn-lg btn-primary" href="{{ route('sheets.new') }}">Create new spreadsheet</a> </div> <div class="list-group"> @if($sheets = \Auth::user()->viewedSheets()) @foreach($sheets as $sheet) <a href="/sheets/{{ $sheet->_id }}" class="list-group-item"> {{ $sheet->name }} </a> @endforeach @endif </div> </div> </div> </div> </div> </div> @endsection We’ll add a new method to our User model, viewedSheets. This method will search for all sheets whose IDs are in the viewed_sheets property and retrieve them. First, create the Sheet model ( app/Models/Sheet.php) with the following content: <?php namespace App\Models; use Jenssegers\Mongodb\Eloquent\Model; class Sheet extends Model { protected $guarded = []; } Then add the viewedSheets method to your app/Models/User.php: public function viewedSheets() { return \App\Models\Sheet::whereIn('_id', $this->viewed_sheets)->get(); } Working with sheets We have a few more things to achieve at this point: - Clicking the Create a Spreadsheet button should create a new, empty sheet and open it up for editing - Clicking on a spreadsheet in the list of recently viewed sheets should also open it up for editing - Our app will have autosave enabled; we’ll save changes to a sheet via AJAX as the user makes them. This means we need an endpoint for updating our sheets Our sheets will have the following properties: - An ID. MongoDB automatically generates this for us as _id - A name. (for now, sheets will be called “Untitled spreadsheet”) - An owner. We’ll store this as _owner. (The _indicates that it’s an ID.) - Content in rows and columns. We’ll store this as an array of rows. Each rowis an array with each entry being a column. For instance, with a table like this: | A | B | C -------------- 1 | 2 | 3 | 4 | The columns and rows will be represented as: content = [ [ 'A1', 'B1', 'C1' ], [ 'A2', 'B2', 'C2' ], [ 'A3', 'B3', 'C3', ],, [ 'A4', 'B4', 'C4', ], ]; Let’s create the routes we need: one each for creating, viewing and updating a sheet. Add the following to the end of your routes/web.php: Route::get('sheets/new', 'SheetsController@newSheet')->name('sheets.new'); Route::get('sheets/{sheet}', 'SheetsController@view')->name('sheets.view'); Route::put('sheets/{id}', 'SheetsController@update'); Now, we’ll implement the logic for these in the controller. Create the file app/Http/Controllers/SheetsController.php with the following content: <?php namespace App\Http\Controllers; use App\Models\Sheet; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class SheetsController extends Controller { public function __construct() { $this->middleware('auth'); } public function newSheet() { $sheet = Sheet::create([ 'name' => 'Untitled spreadsheet', '_owner' => Auth::user()->_id, 'content' => [[]] ]); return redirect(route('sheets.view', ['sheet' => $sheet])); } public function view(Sheet $sheet) { Auth::user()->push('viewed_sheets', $sheet->_id); return view('spreadsheet', ['sheet' => $sheet]); } public function update($id) { $sheet = Sheet::where('_id', $id)->update(['content' => \request('content') ?: [[]]]); return response()->json(['sheet' => $sheet]); } } What’s left now is the view. We’ll be making use of Handsontable, a library that provides us with a spreadsheet interface. Create the file spreadsheet.blade.php with the following content: > let csrfToken = document.head.querySelector('meta[name="csrf-token"]').content; let data = @json($sheet->content); let container = document.getElementById('sheet'); let table = new Handsontable(container, { data: data, rowHeaders: true, colHeaders: true, minCols: 20, minRows: 20, afterChange: function (change, source) { if (source === 'loadData') return; console.log(change, source); fetch('/sheets/{{ $sheet->_id }}', { method: 'PUT', body: JSON.stringify({content: data}), headers: { 'X-CSRF-TOKEN': csrfToken, 'Content-Type': 'application/json' }, credentials: 'same-origin' }) } }); </script> Here’s what’s happening here: - We initialize our Handsontable spreadsheet containing the data in the contentof our sheet. The datavariable is bound as a reference. This means that whenever a user makes a change to the spreadsheet, the value of datais automatically updated by Handsontable to include the new changes - We listen for the afterChangeevent. This event is fired whenever a user finishes editing a cell (for instance, he changes a value in a cell and presses Enter). When this event is fired, we grab the current value of dataand make the HTTP request (using Fetch) to our backend to update the sheet in the database. Start your MongoDB server by running mongod. Note: on Linux/macOS, you might need to run it as sudo. Then start your app by running: php artisan serve Create a new user at You should be able to create a new spreadsheet and edit it. On refreshing the page, you’ll see the changes you make are saved. Conclusion In the next part, we’ll add collaboration to our app. We’ll see how we can enable realtime editing of the same document by different users using Pusher. You can check out the source code of the app thus far here. April 30, 2018 by Shalvah Adebayo
https://pusher.com/tutorials/realtime-spreadsheets-part-1/
CC-MAIN-2022-21
refinedweb
1,237
56.66
Solving an ode for a specific solution value Posted August 31, 2011 at 09:00 AM | categories: ode | tags: | View Comments Updated February 27, 2013 at 02:58 PM Matlab post The analytical solution to an ODE is a function, which can be solved to get a particular value, e.g. if the solution to an ODE is y(x) = exp(x), you can solve the solution to find the value of x that makes \(y(x)=2\). In a numerical solution to an ODE we get a vector of independent variable values, and the corresponding function values at those values. To solve for a particular function value we need a different approach. This post will show one way to do that in python.. We will get a solution, then create an interpolating function and use fsolve to get the answer. from scipy.integrate import odeint from scipy.interpolate import interp1d from scipy.optimize import fsolve import numpy as np import matplotlib.pyplot as plt k = 0.23 Ca0 = 2.3 def dCadt(Ca, t): return -k * Ca**2 tspan = np.linspace(0, 10) sol = odeint(dCadt, Ca0, tspan) Ca = sol[:,0] plt.plot(tspan, Ca) plt.xlabel('Time (s)') plt.ylabel('$C_A$ (mol/L)') plt.savefig('images/ode-specific-1.png') >>> >>> >>> >>> ... >>> [<matplotlib.lines.Line2D object at 0x1b710d50>] <matplotlib.text.Text object at 0x1b2f8410> <matplotlib.text.Text object at 0x1b2fae10> You can see the solution is near two seconds. Now we create an interpolating function to evaluate the solution. We will plot the interpolating function on a finer grid to make sure it seems reasonable. ca_func = interp1d(tspan, Ca, 'cubic') itime = np.linspace(0, 10, 200) plt.figure() plt.plot(tspan, Ca, '.') plt.plot(itime, ca_func(itime), 'b-') plt.xlabel('Time (s)') plt.ylabel('$C_A$ (mol/L)') plt.legend(['solution','interpolated']) plt.savefig('images/ode-specific-2.png') plt.show() >>> >>> >>> <matplotlib.figure.Figure object at 0x1b2dfed0> [<matplotlib.lines.Line2D object at 0x1c103b90>] [<matplotlib.lines.Line2D object at 0x1c107050>] >>> <matplotlib.text.Text object at 0x1c0e65d0> <matplotlib.text.Text object at 0x1b95bfd0> <matplotlib.legend.Legend object at 0x1c107550> that loos pretty reasonable. Now we solve the problem. tguess = 2.0 tsol, = fsolve(lambda t: 1.0 - ca_func(t), tguess) print tsol # you might prefer an explicit function def func(t): return 1.0 - ca_func(t) tsol2, = fsolve(func, tguess) print tsol2 >>> 2.4574668235 >>> ... ... >>> 2.4574668235 That is it. Interpolation can provide a simple way to evaluate the numerical solution of an ODE at other values. For completeness we examine a final way to construct the function. We can actually integrate the ODE in the function to evaluate the solution at the point of interest. If it is not computationally expensive to evaluate the ODE solution this works fine. Note, however, that the ODE will get integrated from 0 to the value t for each iteration of fsolve. def func(t): tspan = [0, t] sol = odeint(dCadt, Ca0, tspan) return 1.0 - sol[-1] tsol3, = fsolve(func, tguess) print tsol3 ... ... ... >>> >>> 2.45746688202 Copyright (C) 2013 by John Kitchin. See the License for information about copying.
http://kitchingroup.cheme.cmu.edu/blog/2011/08/31/Solving-an-ode-for-a-specific-solution-value/
CC-MAIN-2019-26
refinedweb
512
53.68
SNMP counter¶ This document explains the meaning of SNMP counters. General IPv4 counters¶ All layer 4 packets and ICMP packets will change these counters, but these counters won't be changed by layer 2 packets (such as STP) or ARP packets. - IpInReceives Defined in RFC1213 ipInReceives The number of packets received by the IP layer. It gets increasing at the beginning of ip_rcv function, always be updated together with IpExtInOctets. It will be increased even if the packet is dropped later (e.g. due to the IP header is invalid or the checksum is wrong and so on). It indicates the number of aggregated segments after GRO/LRO. - IpInDelivers Defined in RFC1213 ipInDelivers The number of packets delivers to the upper layer protocols. E.g. TCP, UDP, ICMP and so on. If no one listens on a raw socket, only kernel supported protocols will be delivered, if someone listens on the raw socket, all valid IP packets will be delivered. - IpOutRequests Defined in RFC1213 ipOutRequests The number of packets sent via IP layer, for both single cast and multicast packets, and would always be updated together with IpExtOutOctets. - IpExtInOctets and IpExtOutOctets They are Linux kernel extensions, no RFC definitions. Please note, RFC1213 indeed defines ifInOctets and ifOutOctets, but they are different things. The ifInOctets and ifOutOctets include the MAC layer header size but IpExtInOctets and IpExtOutOctets don't, they only include the IP layer header and the IP layer data. - IpExtInNoECTPkts, IpExtInECT1Pkts, IpExtInECT0Pkts, IpExtInCEPkts They indicate the number of four kinds of ECN IP packets, please refer Explicit Congestion Notification for more details. These 4 counters calculate how many packets received per ECN status. They count the real frame number regardless the LRO/GRO. So for the same packet, you might find that IpInReceives count 1, but IpExtInNoECTPkts counts 2 or more. - IpInHdrErrors Defined in RFC1213 ipInHdrErrors. It indicates the packet is dropped due to the IP header error. It might happen in both IP input and IP forward paths. - IpInAddrErrors Defined in RFC1213 ipInAddrErrors. It will be increased in two scenarios: (1) The IP address is invalid. (2) The destination IP address is not a local address and IP forwarding is not enabled - IpExtInNoRoutes This counter means the packet is dropped when the IP stack receives a packet and can't find a route for it from the route table. It might happen when IP forwarding is enabled and the destination IP address is not a local address and there is no route for the destination IP address. - IpInUnknownProtos Defined in RFC1213 ipInUnknownProtos. It will be increased if the layer 4 protocol is unsupported by kernel. If an application is using raw socket, kernel will always deliver the packet to the raw socket and this counter won't be increased. - IpExtInTruncatedPkts For IPv4 packet, it means the actual data size is smaller than the "Total Length" field in the IPv4 header. - IpInDiscards Defined in RFC1213 ipInDiscards. It indicates the packet is dropped in the IP receiving path and due to kernel internal reasons (e.g. no enough memory). - IpOutDiscards Defined in RFC1213 ipOutDiscards. It indicates the packet is dropped in the IP sending path and due to kernel internal reasons. - IpOutNoRoutes Defined in RFC1213 ipOutNoRoutes. It indicates the packet is dropped in the IP sending path and no route is found for it. ICMP counters¶ - IcmpInMsgs and IcmpOutMsgs Defined by RFC1213 icmpInMsgs and RFC1213 icmpOutMsgs As mentioned in the RFC1213, these two counters include errors, they would be increased even if the ICMP packet has an invalid type. The ICMP output path will check the header of a raw socket, so the IcmpOutMsgs would still be updated if the IP header is constructed by a userspace program. - ICMP named types Every ICMP type has two counters: 'In' and 'Out'. E.g., for the ICMP Echo packet, they are IcmpInEchos and IcmpOutEchos. Their meanings are straightforward. The 'In' counter means kernel receives such a packet and the 'Out' counter means kernel sends such a packet. - ICMP numeric types. And if kernel gets an ICMP Echo Reply packet, IcmpMsgInType0 would increase 1. - IcmpInCsumErrors This counter indicates the checksum of the ICMP packet is wrong. Kernel verifies the checksum after updating the IcmpInMsgs and before updating IcmpMsgInType[N]. If a packet has bad checksum, the IcmpInMsgs would be updated but none of IcmpMsgInType[N] would be updated. - IcmpInErrors and IcmpOutErrors Defined by RFC1213 icmpInErrors and RFC1213 icmpOutErrors When an error occurs in the ICMP packet handler path, these two counters would be updated. The receiving packet path use IcmpInErrors and the sending packet path use IcmpOutErrors. When IcmpInCsumErrors is increased, IcmpInErrors would always be increased too. relationship of the ICMP counters¶ The sum of IcmpMsgOutType[N] is always equal to IcmpOutMsgs, as they are updated at the same time. The sum of IcmpMsgInType[N] plus IcmpInErrors should be equal or larger than IcmpInMsgs. When kernel receives an ICMP packet, kernel follows below logic: - increase IcmpInMsgs - if has any error, update IcmpInErrors and finish the process - update IcmpMsgOutType[N] - handle the packet depending on the type, if has any error, update IcmpInErrors and finish the process So if all errors occur in step (2), IcmpInMsgs should be equal to the sum of IcmpMsgOutType[N] plus IcmpInErrors. If all errors occur in step (4), IcmpInMsgs should be equal to the sum of IcmpMsgOutType[N]. If the errors occur in both step (2) and step (4), IcmpInMsgs should be less than the sum of IcmpMsgOutType[N] plus IcmpInErrors. General TCP counters¶ - TcpInSegs Defined in RFC1213 tcpInSegs The number of packets received by the TCP layer. As mentioned in RFC1213, it includes the packets received in error, such as checksum error, invalid TCP header and so on. Only one error won't be included: if the layer 2 destination address is not the NIC's layer 2 address. It might happen if the packet is a multicast or broadcast packet, or the NIC is in promiscuous mode. In these situations, the packets would be delivered to the TCP layer, but the TCP layer will discard these packets before increasing TcpInSegs. The TcpInSegs counter isn't aware of GRO. So if two packets are merged by GRO, the TcpInSegs counter would only increase 1. - TcpOutSegs Defined in RFC1213 tcpOutSegs The number of packets sent by the TCP layer. As mentioned in RFC1213, it excludes the retransmitted packets. But it includes the SYN, ACK and RST packets. Doesn't like TcpInSegs, the TcpOutSegs is aware of GSO, so if a packet would be split to 2 by GSO, TcpOutSegs will increase 2. - TcpActiveOpens Defined in RFC1213 tcpActiveOpens It means the TCP layer sends a SYN, and come into the SYN-SENT state. Every time TcpActiveOpens increases 1, TcpOutSegs should always increase 1. - TcpPassiveOpens Defined in RFC1213 tcpPassiveOpens It means the TCP layer receives a SYN, replies a SYN+ACK, come into the SYN-RCVD state. - TcpExtTCPRcvCoalesce When packets are received by the TCP layer and are not be read by the application, the TCP layer will try to merge them. This counter indicate how many packets are merged in such situation. If GRO is enabled, lots of packets would be merged by GRO, these packets wouldn't be counted to TcpExtTCPRcvCoalesce. - TcpExtTCPAutoCorking When sending packets, the TCP layer will try to merge small packets to a bigger one. This counter increase 1 for every packet merged in such situation. Please refer to the LWN article for more details: - TcpExtTCPOrigDataSent This counter is explained by kernel commit f19c29e3e391, I pasted the explaination below:. - TCPSynRetrans This counter is explained by kernel commit f19c29e3e391, I pasted the explaination below: TCPSynRetrans: number of SYN and SYN/ACK retransmits to break down retransmissions into SYN, fast-retransmits, timeout retransmits, etc. - TCPFastOpenActiveFail This counter is explained by kernel commit f19c29e3e391, I pasted the explaination below: TCPFastOpenActiveFail: Fast Open attempts (SYN/data) failed because the remote does not accept it or the attempts timed out. - TcpExtListenOverflows and TcpExtListenDrops When kernel receives a SYN from a client, and if the TCP accept queue is full, kernel will drop the SYN and add 1 to TcpExtListenOverflows. At the same time kernel will also add 1 to TcpExtListenDrops. When a TCP socket is in LISTEN state, and kernel need to drop a packet, kernel would always add 1 to TcpExtListenDrops. So increase TcpExtListenOverflows would let TcpExtListenDrops increasing at the same time, but TcpExtListenDrops would also increase without TcpExtListenOverflows increasing, e.g. a memory allocation fail would also let TcpExtListenDrops increase. Note: The above explanation is based on kernel 4.10 or above version, on an old kernel, the TCP stack has different behavior when TCP accept queue is full. On the old kernel, TCP stack won't drop the SYN, it would complete the 3-way handshake. As the accept queue is full, TCP stack will keep the socket in the TCP half-open queue. As it is in the half open queue, TCP stack will send SYN+ACK on an exponential backoff timer, after client replies ACK, TCP stack checks whether the accept queue is still full, if it is not full, moves the socket to the accept queue, if it is full, keeps the socket in the half-open queue, at next time client replies ACK, this socket will get another chance to move to the accept queue. TCP Fast Open¶ - TcpEstabResets Defined in RFC1213 tcpEstabResets. - TcpAttemptFails Defined in RFC1213 tcpAttemptFails. - TcpOutRsts Defined in RFC1213 tcpOutRsts. The RFC says this counter indicates the 'segments sent containing the RST flag', but in linux kernel, this couner indicates the segments kerenl tried to send. The sending process might be failed due to some errors (e.g. memory alloc failed). - TcpExtTCPSpuriousRtxHostQueues When the TCP stack wants to retransmit a packet, and finds that packet is not lost in the network, but the packet is not sent yet, the TCP stack would give up the retransmission and update this counter. It might happen if a packet stays too long time in a qdisc or driver queue. - TcpEstabResets The socket receives a RST packet in Establish or CloseWait state. - TcpExtTCPKeepAlive This counter indicates many keepalive packets were sent. The keepalive won't be enabled by default. A userspace program could enable it by setting the SO_KEEPALIVE socket option. - TcpExtTCPSpuriousRTOs The spurious retransmission timeout detected by the F-RTO algorithm. TCP Fast Path¶ When kernel receives a TCP packet, it has two paths to handler the packet, one is fast path, another is slow path. The comment in kernel code provides a good explanation of them, I pasted them below: It is split into a fast path and a slow path. The fast path is disabled when: - A zero window was announced from us - zero window probing is only handled properly on the slow path. - Out of order segments arrived. - Urgent data is expected. - There is no buffer space left - Unexpected TCP flags/window values/header lengths are received (detected by checking the TCP header against pred_flags) - Data is sent in both directions. The fast path only supports pure senders or pure receivers (this means either the sequence number or the ack value must stay constant) - Unexpected TCP option. Kernel will try to use fast path unless any of the above conditions are satisfied. If the packets are out of order, kernel will handle them in slow path, which means the performance might be not very good. Kernel would also come into slow path if the "Delayed ack" is used, because when using "Delayed ack", the data is sent in both directions. When the TCP window scale option is not used, kernel will try to enable fast path immediately when the connection comes into the established state, but if the TCP window scale option is used, kernel will disable the fast path at first, and try to enable it after kernel receives packets. - TcpExtTCPPureAcks and TcpExtTCPHPAcks If a packet set ACK flag and has no data, it is a pure ACK packet, if kernel handles it in the fast path, TcpExtTCPHPAcks will increase 1, if kernel handles it in the slow path, TcpExtTCPPureAcks will increase 1. - TcpExtTCPHPHits If a TCP packet has data (which means it is not a pure ACK packet), and this packet is handled in the fast path, TcpExtTCPHPHits will increase 1. TCP abort¶ - TcpExtTCPAbortOnData It means TCP layer has data in flight, but need to close the connection. So TCP layer sends a RST to the other side, indicate the connection is not closed very graceful. An easy way to increase this counter is using the SO_LINGER option. Please refer to the SO_LINGER section of the socket man page: By default, when an application closes a connection, the close function will return immediately and kernel will try to send the in-flight data async. If you use the SO_LINGER option, set l_onoff to 1, and l_linger to a positive number, the close function won't return immediately, but wait for the in-flight data are acked by the other side, the max wait time is l_linger seconds. If set l_onoff to 1 and set l_linger to 0, when the application closes a connection, kernel will send a RST immediately and increase the TcpExtTCPAbortOnData counter. - TcpExtTCPAbortOnClose This counter means the application has unread data in the TCP layer when the application wants to close the TCP connection. In such a situation, kernel will send a RST to the other side of the TCP connection. - TcpExtTCPAbortOnMemory When an application closes a TCP connection, kernel still need to track the connection, let it complete the TCP disconnect process. E.g. an app calls the close method of a socket, kernel sends fin to the other side of the connection, then the app has no relationship with the socket any more, but kernel need to keep the socket, this socket becomes an orphan socket, kernel waits for the reply of the other side, and would come to the TIME_WAIT state finally. When kernel has no enough memory to keep the orphan socket, kernel would send an RST to the other side, and delete the socket, in such situation, kernel will increase 1 to the TcpExtTCPAbortOnMemory. Two conditions would trigger TcpExtTCPAbortOnMemory: 1. the memory used by the TCP protocol is higher than the third value of the tcp_mem. Please refer the tcp_mem section in the TCP man page: - the orphan socket count is higher than net.ipv4.tcp_max_orphans - TcpExtTCPAbortOnTimeout This counter will increase when any of the TCP timers expire. In such situation, kernel won't send RST, just give up the connection. - TcpExtTCPAbortOnLinger When a TCP connection comes into FIN_WAIT_2 state, instead of waiting for the fin packet from the other side, kernel could send a RST and delete the socket immediately. This is not the default behavior of Linux kernel TCP stack. By configuring the TCP_LINGER2 socket option, you could let kernel follow this behavior. - TcpExtTCPAbortFailed The kernel TCP layer will send RST if the RFC2525 2.17 section is satisfied. If an internal error occurs during this process, TcpExtTCPAbortFailed will be increased. TCP Hybrid Slow Start¶ The Hybrid Slow Start algorithm is an enhancement of the traditional TCP congestion window Slow Start algorithm. It uses two pieces of information to detect whether the max bandwidth of the TCP path is approached. The two pieces of information are ACK train length and increase in packet delay. For detail information, please refer the Hybrid Slow Start paper. Either ACK train length or packet delay hits a specific threshold, the congestion control algorithm will come into the Congestion Avoidance state. Until v4.20, two congestion control algorithms are using Hybrid Slow Start, they are cubic (the default congestion control algorithm) and cdg. Four snmp counters relate with the Hybrid Slow Start algorithm. - TcpExtTCPHystartTrainDetect How many times the ACK train length threshold is detected - TcpExtTCPHystartTrainCwnd The sum of CWND detected by ACK train length. Dividing this value by TcpExtTCPHystartTrainDetect is the average CWND which detected by the ACK train length. - TcpExtTCPHystartDelayDetect How many times the packet delay threshold is detected. - TcpExtTCPHystartDelayCwnd The sum of CWND detected by packet delay. Dividing this value by TcpExtTCPHystartDelayDetect is the average CWND which detected by the packet delay. TCP retransmission and congestion control¶ The TCP protocol has two retransmission mechanisms: SACK and fast recovery. They are exclusive with each other. When SACK is enabled, the kernel TCP stack would use SACK, or kernel would use fast recovery. The SACK is a TCP option, which is defined in RFC2018, the fast recovery is defined in RFC6582, which is also called 'Reno'. The TCP congestion control is a big and complex topic. To understand the related snmp counter, we need to know the states of the congestion control state machine. There are 5 states: Open, Disorder, CWR, Recovery and Loss. For details about these states, please refer page 5 and page 6 of this document: - TcpExtTCPRenoRecovery and TcpExtTCPSackRecovery When the congestion control comes into Recovery state, if sack is used, TcpExtTCPSackRecovery increases 1, if sack is not used, TcpExtTCPRenoRecovery increases 1. These two counters mean the TCP stack begins to retransmit the lost packets. - TcpExtTCPSACKReneging A packet was acknowledged by SACK, but the receiver has dropped this packet, so the sender needs to retransmit this packet. In this situation, the sender adds 1 to TcpExtTCPSACKReneging. A receiver could drop a packet which has been acknowledged by SACK, although it is unusual, it is allowed by the TCP protocol. The sender doesn't really know what happened on the receiver side. The sender just waits until the RTO expires for this packet, then the sender assumes this packet has been dropped by the receiver. - TcpExtTCPRenoReorder The reorder packet is detected by fast recovery. It would only be used if SACK is disabled. The fast recovery algorithm detects recorder by the duplicate ACK number. E.g., if retransmission is triggered, and the original retransmitted packet is not lost, it is just out of order, the receiver would acknowledge multiple times, one for the retransmitted packet, another for the arriving of the original out of order packet. Thus the sender would find more ACks than its expectation, and the sender knows out of order occurs. - TcpExtTCPTSReorder The reorder packet is detected when a hole is filled. E.g., assume the sender sends packet 1,2,3,4,5, and the receiving order is 1,2,4,5,3. When the sender receives the ACK of packet 3 (which will fill the hole), two conditions will let TcpExtTCPTSReorder increase 1: (1) if the packet 3 is not re-retransmitted yet. (2) if the packet 3 is retransmitted but the timestamp of the packet 3's ACK is earlier than the retransmission timestamp. - TcpExtTCPSACKReorder The reorder packet detected by SACK. The SACK has two methods to detect reorder: (1) DSACK is received by the sender. It means the sender sends the same packet more than one times. And the only reason is the sender believes an out of order packet is lost so it sends the packet again. (2) Assume packet 1,2,3,4,5 are sent by the sender, and the sender has received SACKs for packet 2 and 5, now the sender receives SACK for packet 4 and the sender doesn't retransmit the packet yet, the sender would know packet 4 is out of order. The TCP stack of kernel will increase TcpExtTCPSACKReorder for both of the above scenarios. - TcpExtTCPSlowStartRetrans The TCP stack wants to retransmit a packet and the congestion control state is 'Loss'. - TcpExtTCPFastRetrans The TCP stack wants to retransmit a packet and the congestion control state is not 'Loss'. - TcpExtTCPLostRetransmit A SACK points out that a retransmission packet is lost again. - TcpExtTCPRetransFail The TCP stack tries to deliver a retransmission packet to lower layers but the lower layers return an error. - TcpExtTCPSynRetrans The TCP stack retransmits a SYN packet. DSACK¶ The DSACK is defined in RFC2883. The receiver uses DSACK to report duplicate packets to the sender. There are two kinds of duplications: (1) a packet which has been acknowledged is duplicate. (2) an out of order packet is duplicate. The TCP stack counts these two kinds of duplications on both receiver side and sender side. - TcpExtTCPDSACKOldSent The TCP stack receives a duplicate packet which has been acked, so it sends a DSACK to the sender. - TcpExtTCPDSACKOfoSent The TCP stack receives an out of order duplicate packet, so it sends a DSACK to the sender. - TcpExtTCPDSACKRecv The TCP stack receives a DSACK, which indicates an acknowledged duplicate packet is received. - TcpExtTCPDSACKOfoRecv The TCP stack receives a DSACK, which indicate an out of order duplicate packet is received. invalid SACK and DSACK¶ When a SACK (or DSACK) block is invalid, a corresponding counter would be updated. The validation method is base on the start/end sequence number of the SACK block. For more details, please refer the comment of the function tcp_is_sackblock_valid in the kernel source code. A SACK option could have up to 4 blocks, they are checked individually. E.g., if 3 blocks of a SACk is invalid, the corresponding counter would be updated 3 times. The comment of the Add counters for discarded SACK blocks patch has additional explaination: - TcpExtTCPSACKDiscard This counter indicates how many SACK blocks are invalid. If the invalid SACK block is caused by ACK recording, the TCP stack will only ignore it and won't update this counter. - TcpExtTCPDSACKIgnoredOld and TcpExtTCPDSACKIgnoredNoUndo When a DSACK block is invalid, one of these two counters would be updated. Which counter will be updated depends on the undo_marker flag of the TCP socket. If the undo_marker is not set, the TCP stack isn't likely to re-transmit any packets, and we still receive an invalid DSACK block, the reason might be that the packet is duplicated in the middle of the network. In such scenario, TcpExtTCPDSACKIgnoredNoUndo will be updated. If the undo_marker is set, TcpExtTCPDSACKIgnoredOld will be updated. As implied in its name, it might be an old packet. SACK shift¶ The linux networking stack stores data in sk_buff struct (skb for short). If a SACK block acrosses multiple skb, the TCP stack will try to re-arrange data in these skb. E.g. if a SACK block acknowledges seq 10 to 15, skb1 has seq 10 to 13, skb2 has seq 14 to 20. The seq 14 and 15 in skb2 would be moved to skb1. This operation is 'shift'. If a SACK block acknowledges seq 10 to 20, skb1 has seq 10 to 13, skb2 has seq 14 to 20. All data in skb2 will be moved to skb1, and skb2 will be discard, this operation is 'merge'. - TcpExtTCPSackShifted A skb is shifted - TcpExtTCPSackMerged A skb is merged - TcpExtTCPSackShiftFallback A skb should be shifted or merged, but the TCP stack doesn't do it for some reasons. TCP out of order¶ - TcpExtTCPOFOQueue The TCP layer receives an out of order packet and has enough memory to queue it. - TcpExtTCPOFODrop The TCP layer receives an out of order packet but doesn't have enough memory, so drops it. Such packets won't be counted into TcpExtTCPOFOQueue. - TcpExtTCPOFOMerge The received out of order packet has an overlay with the previous packet. the overlay part will be dropped. All of TcpExtTCPOFOMerge packets will also be counted into TcpExtTCPOFOQueue. TCP PAWS¶ PAWS (Protection Against Wrapped Sequence numbers) is an algorithm which is used to drop old packets. It depends on the TCP timestamps. For detail information, please refer the timestamp wiki and the RFC of PAWS. - TcpExtPAWSActive Packets are dropped by PAWS in Syn-Sent status. - TcpExtPAWSEstab Packets are dropped by PAWS in any status other than Syn-Sent. TCP ACK skip¶ In some scenarios, kernel would avoid sending duplicate ACKs too frequently. Please find more details in the tcp_invalid_ratelimit section of the sysctl document. When kernel decides to skip an ACK due to tcp_invalid_ratelimit, kernel would update one of below counters to indicate the ACK is skipped in which scenario. The ACK would only be skipped if the received packet is either a SYN packet or it has no data. - TcpExtTCPACKSkippedSynRecv The ACK is skipped in Syn-Recv status. The Syn-Recv status means the TCP stack receives a SYN and replies SYN+ACK. Now the TCP stack is waiting for an ACK. Generally, the TCP stack doesn't need to send ACK in the Syn-Recv status. But in several scenarios, the TCP stack need to send an ACK. E.g., the TCP stack receives the same SYN packet repeately, the received packet does not pass the PAWS check, or the received packet sequence number is out of window. In these scenarios, the TCP stack needs to send ACK. If the ACk sending frequency is higher than tcp_invalid_ratelimit allows, the TCP stack will skip sending ACK and increase TcpExtTCPACKSkippedSynRecv. - TcpExtTCPACKSkippedPAWS The ACK is skipped due to PAWS (Protect Against Wrapped Sequence numbers) check fails. If the PAWS check fails in Syn-Recv, Fin-Wait-2 or Time-Wait statuses, the skipped ACK would be counted to TcpExtTCPACKSkippedSynRecv, TcpExtTCPACKSkippedFinWait2 or TcpExtTCPACKSkippedTimeWait. In all other statuses, the skipped ACK would be counted to TcpExtTCPACKSkippedPAWS. - TcpExtTCPACKSkippedSeq The sequence number is out of window and the timestamp passes the PAWS check and the TCP status is not Syn-Recv, Fin-Wait-2, and Time-Wait. - TcpExtTCPACKSkippedFinWait2 The ACK is skipped in Fin-Wait-2 status, the reason would be either PAWS check fails or the received sequence number is out of window. - TcpExtTCPACKSkippedTimeWait Tha ACK is skipped in Time-Wait status, the reason would be either PAWS check failed or the received sequence number is out of window. - TcpExtTCPACKSkippedChallenge The ACK is skipped if the ACK is a challenge ACK. The RFC 5961 defines 3 kind of challenge ACK, please refer RFC 5961 section 3.2, RFC 5961 section 4.2 and RFC 5961 section 5.2. Besides these three scenarios, In some TCP status, the linux TCP stack would also send challenge ACKs if the ACK number is before the first unacknowledged number (more strict than RFC 5961 section 5.2). TCP receive window¶ - TcpExtTCPWantZeroWindowAdv Depending on current memory usage, the TCP stack tries to set receive window to zero. But the receive window might still be a no-zero value. For example, if the previous window size is 10, and the TCP stack receives 3 bytes, the current window size would be 7 even if the window size calculated by the memory usage is zero. - TcpExtTCPToZeroWindowAdv The TCP receive window is set to zero from a no-zero value. - TcpExtTCPFromZeroWindowAdv The TCP receive window is set to no-zero value from zero. Delayed ACK¶ The TCP Delayed ACK is a technique which is used for reducing the packet count in the network. For more details, please refer the Delayed ACK wiki - TcpExtDelayedACKs A delayed ACK timer expires. The TCP stack will send a pure ACK packet and exit the delayed ACK mode. - TcpExtDelayedACKLocked A delayed ACK timer expires, but the TCP stack can't send an ACK immediately due to the socket is locked by a userspace program. The TCP stack will send a pure ACK later (after the userspace program unlock the socket). When the TCP stack sends the pure ACK later, the TCP stack will also update TcpExtDelayedACKs and exit the delayed ACK mode. - TcpExtDelayedACKLost It will be updated when the TCP stack receives a packet which has been ACKed. A Delayed ACK loss might cause this issue, but it would also be triggered by other reasons, such as a packet is duplicated in the network. Tail Loss Probe (TLP)¶ TLP is an algorithm which is used to detect TCP packet loss. For more details, please refer the TLP paper. - TcpExtTCPLossProbes A TLP probe packet is sent. - TcpExtTCPLossProbeRecovery A packet loss is detected and recovered by TLP. TCP Fast Open¶ TCP Fast Open is a technology which allows data transfer before the 3-way handshake complete. Please refer the TCP Fast Open wiki for a general description. - TcpExtTCPFastOpenActive When the TCP stack receives an ACK packet in the SYN-SENT status, and the ACK packet acknowledges the data in the SYN packet, the TCP stack understand the TFO cookie is accepted by the other side, then it updates this counter. - TcpExtTCPFastOpenActiveFail This counter indicates that the TCP stack initiated a TCP Fast Open, but it failed. This counter would be updated in three scenarios: (1) the other side doesn't acknowledge the data in the SYN packet. (2) The SYN packet which has the TFO cookie is timeout at least once. (3) after the 3-way handshake, the retransmission timeout happens net.ipv4.tcp_retries1 times, because some middle-boxes may black-hole fast open after the handshake. - TcpExtTCPFastOpenPassive This counter indicates how many times the TCP stack accepts the fast open request. - TcpExtTCPFastOpenPassiveFail This counter indicates how many times the TCP stack rejects the fast open request. It is caused by either the TFO cookie is invalid or the TCP stack finds an error during the socket creating process. - TcpExtTCPFastOpenListenOverflow When the pending fast open request number is larger than fastopenq->max_qlen, the TCP stack will reject the fast open request and update this counter. When this counter is updated, the TCP stack won't update TcpExtTCPFastOpenPassive or TcpExtTCPFastOpenPassiveFail. The fastopenq->max_qlen is set by the TCP_FASTOPEN socket operation and it could not be larger than net.core.somaxconn. For example: setsockopt(sfd, SOL_TCP, TCP_FASTOPEN, &qlen, sizeof(qlen)); - TcpExtTCPFastOpenCookieReqd This counter indicates how many times a client wants to request a TFO cookie. Challenge ACK¶ For details of challenge ACK, please refer the explaination of TcpExtTCPACKSkippedChallenge. - TcpExtTCPChallengeACK The number of challenge acks sent. - TcpExtTCPSYNChallenge The number of challenge acks sent in response to SYN packets. After updates this counter, the TCP stack might send a challenge ACK and update the TcpExtTCPChallengeACK counter, or it might also skip to send the challenge and update the TcpExtTCPACKSkippedChallenge. prune¶ When a socket is under memory pressure, the TCP stack will try to reclaim memory from the receiving queue and out of order queue. One of the reclaiming method is 'collapse', which means allocate a big sbk, copy the contiguous skbs to the single big skb, and free these contiguous skbs. - TcpExtPruneCalled The TCP stack tries to reclaim memory for a socket. After updates this counter, the TCP stack will try to collapse the out of order queue and the receiving queue. If the memory is still not enough, the TCP stack will try to discard packets from the out of order queue (and update the TcpExtOfoPruned counter) - TcpExtOfoPruned The TCP stack tries to discard packet on the out of order queue. - TcpExtRcvPruned After 'collapse' and discard packets from the out of order queue, if the actually used memory is still larger than the max allowed memory, this counter will be updated. It means the 'prune' fails. - TcpExtTCPRcvCollapsed This counter indicates how many skbs are freed during 'collapse'. examples¶ ping test¶ Run the ping command against the public dns server 8.8.8.8: nstatuser@nstat-a:~$ ping 8.8.8.8 -c 1 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=17.8 ms --- 8.8.8.8 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 17.875/17.875/17.875/0.000 ms The nstayt result: nstatuser@nstat-a:~$ nstat #kernel IpInReceives 1 0.0 IpInDelivers 1 0.0 IpOutRequests 1 0.0 IcmpInMsgs 1 0.0 IcmpInEchoReps 1 0.0 IcmpOutMsgs 1 0.0 IcmpOutEchos 1 0.0 IcmpMsgInType0 1 0.0 IcmpMsgOutType8 1 0.0 IpExtInOctets 84 0.0 IpExtOutOctets 84 0.0 IpExtInNoECTPkts 1 0.0 The Linux server sent an ICMP Echo packet, so IpOutRequests, IcmpOutMsgs, IcmpOutEchos and IcmpMsgOutType8 were increased 1. The server got ICMP Echo Reply from 8.8.8.8, so IpInReceives, IcmpInMsgs, IcmpInEchoReps and IcmpMsgInType0 were increased 1. The ICMP Echo Reply was passed to the ICMP layer via IP layer, so IpInDelivers was increased 1. The default ping data size is 48, so an ICMP Echo packet and its corresponding Echo Reply packet are constructed by: - 14 bytes MAC header - 20 bytes IP header - 16 bytes ICMP header - 48 bytes data (default value of the ping command) So the IpExtInOctets and IpExtOutOctets are 20+16+48=84. tcp 3-way handshake¶ On server side, we run: nstatuser@nstat-b:~$ nc -lknv 0.0.0.0 9000 Listening on [0.0.0.0] (family 0, port 9000) On client side, we run: nstatuser@nstat-a:~$ nc -nv 192.168.122.251 9000 Connection to 192.168.122.251 9000 port [tcp/*] succeeded! The server listened on tcp 9000 port, the client connected to it, they completed the 3-way handshake. On server side, we can find below nstat output: nstatuser@nstat-b:~$ nstat | grep -i tcp TcpPassiveOpens 1 0.0 TcpInSegs 2 0.0 TcpOutSegs 1 0.0 TcpExtTCPPureAcks 1 0.0 On client side, we can find below nstat output: nstatuser@nstat-a:~$ nstat | grep -i tcp TcpActiveOpens 1 0.0 TcpInSegs 1 0.0 TcpOutSegs 2 0.0 When the server received the first SYN, it replied a SYN+ACK, and came into SYN-RCVD state, so TcpPassiveOpens increased 1. The server received SYN, sent SYN+ACK, received ACK, so server sent 1 packet, received 2 packets, TcpInSegs increased 2, TcpOutSegs increased 1. The last ACK of the 3-way handshake is a pure ACK without data, so TcpExtTCPPureAcks increased 1. When the client sent SYN, the client came into the SYN-SENT state, so TcpActiveOpens increased 1, the client sent SYN, received SYN+ACK, sent ACK, so client sent 2 packets, received 1 packet, TcpInSegs increased 1, TcpOutSegs increased 2. TCP normal traffic¶ Run nc on server: nstatuser@nstat-b:~$ nc -lkv 0.0.0.0 9000 Listening on [0.0.0.0] (family 0, port 9000) Run nc on client: nstatuser@nstat-a:~$ nc -v nstat-b 9000 Connection to nstat-b 9000 port [tcp/*] succeeded! Input a string in the nc client ('hello' in our example): nstatuser@nstat-a:~$ nc -v nstat-b 9000 Connection to nstat-b 9000 port [tcp/*] succeeded! hello TheTCPPureAcks 1 0.0 TcpExtTCPOrigDataSent 1 0.0 IpExtInOctets 52 0.0 IpExtOutOctets 58 0.0 IpExtInNoECTPkts 1 0.0 The IpExtInOctets 58 0.0 IpExtOutOctets 52 0.0 IpExtInNoECTPkts 1 0.0 Input a string in nc client side again ('world' in our exmaple): nstatuser@nstat-a:~$ nc -v nstat-b 9000 Connection to nstat-b 9000 port [tcp/*] succeeded! hello worldTCPHPAcks 1 0.0 TcpExtTCPOrigDataSent 1 0.0 IpExtInOctets 52 0.0 IpExtOutOctets 58 0.0 IpExtInNoECTPkts 1 0.0 TcpExtTCPHPHits 1 0.0 IpExtInOctets 58 0.0 IpExtOutOctets 52 0.0 IpExtInNoECTPkts 1 0.0 Compare the first client-side nstat and the second client-side nstat, we could find one difference: the first one had a 'TcpExtTCPPureAcks', but the second one had a 'TcpExtTCPHPAcks'. The first server-side nstat and the second server-side nstat had a difference too: the second server-side nstat had a TcpExtTCPHPHits, but the first server-side nstat didn't have it. The network traffic patterns were exactly the same: the client sent a packet to the server, the server replied an ACK. But kernel handled them in different ways. When the TCP window scale option is not used, kernel will try to enable fast path immediately when the connection comes into the established state, but if the TCP window scale option is used, kernel will disable the fast path at first, and try to enable it after kerenl receives packets. We could use the 'ss' command to verify whether the window scale option is used. e.g. run below command on either server or client: nstatuser@nstat-a:~$ ss -o state established -i '( dport = :9000 or sport = :9000 ) Netid Recv-Q Send-Q Local Address:Port Peer Address:Port tcp 0 0 192.168.122.250:40654 192.168.122.251:9000 ts sack cubic wscale:7,7 rto:204 rtt:0.98/0.49 mss:1448 pmtu:1500 rcvmss:536 advmss:1448 cwnd:10 bytes_acked:1 segs_out:2 segs_in:1 send 118.2Mbps lastsnd:46572 lastrcv:46572 lastack:46572 pacing_rate 236.4Mbps rcv_space:29200 rcv_ssthresh:29200 minrtt:0.98 The 'wscale:7,7' means both server and client set the window scale option to 7. Now we could explain the nstat output in our test: In the first nstat output of client side, the client sent a packet, server reply an ACK, when kernel handled this ACK, the fast path was not enabled, so the ACK was counted into 'TcpExtTCPPureAcks'. In the second nstat output of client side, the client sent a packet again, and received another ACK from the server, in this time, the fast path is enabled, and the ACK was qualified for fast path, so it was handled by the fast path, so this ACK was counted into TcpExtTCPHPAcks. In the first nstat output of server side, fast path was not enabled, so there was no 'TcpExtTCPHPHits'. In the second nstat output of server side, the fast path was enabled, and the packet received from client qualified for fast path, so it was counted into 'TcpExtTCPHPHits'. TcpExtTCPAbortOnClose¶ On the server side, we run below python script: import socket import time port = 9000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('0.0.0.0', port)) s.listen(1) sock, addr = s.accept() while True: time.sleep(9999999) This python script listen on 9000 port, but doesn't read anything from the connection. On the client side, we send the string "hello" by nc: nstatuser@nstat-a:~$ echo "hello" | nc nstat-b 9000 Then, we come back to the server side, the server has received the "hello" packet, and the TCP layer has acked this packet, but the application didn't read it yet. We type Ctrl-C to terminate the server script. Then we could find TcpExtTCPAbortOnClose increased 1 on the server side: nstatuser@nstat-b:~$ nstat | grep -i abort TcpExtTCPAbortOnClose 1 0.0 If we run tcpdump on the server side, we could find the server sent a RST after we type Ctrl-C. TcpExtTCPAbortOnMemory and TcpExtTCPAbortOnTimeout¶ Below is an example which let the orphan socket count be higher than net.ipv4.tcp_max_orphans. Change tcp_max_orphans to a smaller value on client: sudo bash -c "echo 10 > /proc/sys/net/ipv4/tcp_max_orphans" Client code (create 64 connection to server): nstatuser@nstat-a:~$ cat client_orphan.py import socket import time server = 'nstat-b' # server address port = 9000 count = 64 connection_list = [] for i in range(64): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((server, port)) connection_list.append(s) print("connection_count: %d" % len(connection_list)) while True: time.sleep(99999) Server code (accept 64 connection from client): nstatuser@nstat-b:~$ cat server_orphan.py import socket import time port = 9000 count = 64 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('0.0.0.0', port)) s.listen(count) connection_list = [] while True: sock, addr = s.accept() connection_list.append((sock, addr)) print("connection_count: %d" % len(connection_list)) Run the python scripts on server and client. On server: python3 server_orphan.py On client: python3 client_orphan.py Run iptables on server: sudo iptables -A INPUT -i ens3 -p tcp --destination-port 9000 -j DROP Type Ctrl-C on client, stop client_orphan.py. Check TcpExtTCPAbortOnMemory on client: nstatuser@nstat-a:~$ nstat | grep -i abort TcpExtTCPAbortOnMemory 54 0.0 Check orphane socket count on client: nstatuser@nstat-a:~$ ss -s Total: 131 (kernel 0) TCP: 14 (estab 1, closed 0, orphaned 10, synrecv 0, timewait 0/0), ports 0 Transport Total IP IPv6 * 0 - - RAW 1 0 1 UDP 1 1 0 TCP 14 13 1 INET 16 14 2 FRAG 0 0 0 The explanation of the test: after run server_orphan.py and client_orphan.py, we set up 64 connections between server and client. Run the iptables command, the server will drop all packets from the client, type Ctrl-C on client_orphan.py, the system of the client would try to close these connections, and before they are closed gracefully, these connections became orphan sockets. As the iptables of the server blocked packets from the client, the server won't receive fin from the client, so all connection on clients would be stuck on FIN_WAIT_1 stage, so they will keep as orphan sockets until timeout. We have echo 10 to /proc/sys/net/ipv4/tcp_max_orphans, so the client system would only keep 10 orphan sockets, for all other orphan sockets, the client system sent RST for them and delete them. We have 64 connections, so the 'ss -s' command shows the system has 10 orphan sockets, and the value of TcpExtTCPAbortOnMemory was 54. An additional explanation about orphan socket count: You could find the exactly orphan socket count by the 'ss -s' command, but when kernel decide whither increases TcpExtTCPAbortOnMemory and sends RST, kernel doesn't always check the exactly orphan socket count. For increasing performance, kernel checks an approximate count firstly, if the approximate count is more than tcp_max_orphans, kernel checks the exact count again. So if the approximate count is less than tcp_max_orphans, but exactly count is more than tcp_max_orphans, you would find TcpExtTCPAbortOnMemory is not increased at all. If tcp_max_orphans is large enough, it won't occur, but if you decrease tcp_max_orphans to a small value like our test, you might find this issue. So in our test, the client set up 64 connections although the tcp_max_orphans is 10. If the client only set up 11 connections, we can't find the change of TcpExtTCPAbortOnMemory. Continue the previous test, we wait for several minutes. Because of the iptables on the server blocked the traffic, the server wouldn't receive fin, and all the client's orphan sockets would timeout on the FIN_WAIT_1 state finally. So we wait for a few minutes, we could find 10 timeout on the client: nstatuser@nstat-a:~$ nstat | grep -i abort TcpExtTCPAbortOnTimeout 10 0.0 TcpExtTCPAbortOnLinger¶ The server side code: nstatuser@nstat-b:~$ cat server_linger.py import socket import time port = 9000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('0.0.0.0', port)) s.listen(1) sock, addr = s.accept() while True: time.sleep(9999999) The client side code: nstatuser@nstat-a:~$ cat client_linger.py import socket import struct server = 'nstat-b' # server address port = 9000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 10)) s.setsockopt(socket.SOL_TCP, socket.TCP_LINGER2, struct.pack('i', -1)) s.connect((server, port)) s.close() Run server_linger.py on server: nstatuser@nstat-b:~$ python3 server_linger.py Run client_linger.py on client: nstatuser@nstat-a:~$ python3 client_linger.py After run client_linger.py, check the output of nstat: nstatuser@nstat-a:~$ nstat | grep -i abort TcpExtTCPAbortOnLinger 1 0.0 TcpExtTCPRcvCoalesce¶ On the server, we run a program which listen on TCP port 9000, but doesn't read any data: import socket import time port = 9000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('0.0.0.0', port)) s.listen(1) sock, addr = s.accept() while True: time.sleep(9999999) Save the above code as server_coalesce.py, and run: python3 server_coalesce.py On the client, save below code as client_coalesce.py: import socket server = 'nstat-b' port = 9000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((server, port)) Run: nstatuser@nstat-a:~$ python3 -i client_coalesce.py We use '-i' to come into the interactive mode, then a packet: >>> s.send(b'foo') 3 Send a packet again: >>> s.send(b'bar') 3 On the server, run nstat: ubuntu@nstat-b:~$ nstat #kernel IpInReceives 2 0.0 IpInDelivers 2 0.0 IpOutRequests 2 0.0 TcpInSegs 2 0.0 TcpOutSegs 2 0.0 TcpExtTCPRcvCoalesce 1 0.0 IpExtInOctets 110 0.0 IpExtOutOctets 104 0.0 IpExtInNoECTPkts 2 0.0 The client sent two packets, server didn't read any data. When the second packet arrived at server, the first packet was still in the receiving queue. So the TCP layer merged the two packets, and we could find the TcpExtTCPRcvCoalesce increased 1. TcpExtListenOverflows and TcpExtListenDrops¶ On server, run the nc command, listen on port 9000: nstatuser@nstat-b:~$ nc -lkv 0.0.0.0 9000 Listening on [0.0.0.0] (family 0, port 9000) On client, run 3 nc commands in different terminals: nstatuser@nstat-a:~$ nc -v nstat-b 9000 Connection to nstat-b 9000 port [tcp/*] succeeded! The nc command only accepts 1 connection, and the accept queue length is 1. On current linux implementation, set queue length to n means the actual queue length is n+1. Now we create 3 connections, 1 is accepted by nc, 2 in accepted queue, so the accept queue is full. Before running the 4th nc, we clean the nstat history on the server: nstatuser@nstat-b:~$ nstat -n Run the 4th nc on the client: nstatuser@nstat-a:~$ nc -v nstat-b 9000 If the nc server is running on kernel 4.10 or higher version, you won't see the "Connection to ... succeeded!" string, because kernel will drop the SYN if the accept queue is full. If the nc client is running on an old kernel, you would see that the connection is succeeded, because kernel would complete the 3 way handshake and keep the socket on half open queue. I did the test on kernel 4.15. Below is the nstat on the server: nstatuser@nstat-b:~$ nstat #kernel IpInReceives 4 0.0 IpInDelivers 4 0.0 TcpInSegs 4 0.0 TcpExtListenOverflows 4 0.0 TcpExtListenDrops 4 0.0 IpExtInOctets 240 0.0 IpExtInNoECTPkts 4 0.0 Both TcpExtListenOverflows and TcpExtListenDrops were 4. If the time between the 4th nc and the nstat was longer, the value of TcpExtListenOverflows and TcpExtListenDrops would be larger, because the SYN of the 4th nc was dropped, the client was retrying. IpInAddrErrors, IpExtInNoRoutes and IpOutNoRoutes¶ server A IP address: 192.168.122.250 server B IP address: 192.168.122.251 Prepare on server A, add a route to server B: $ sudo ip route add 8.8.8.8/32 via 192.168.122.251 Prepare on server B, disable send_redirects for all interfaces: $ sudo sysctl -w net.ipv4.conf.all.send_redirects=0 $ sudo sysctl -w net.ipv4.conf.ens3.send_redirects=0 $ sudo sysctl -w net.ipv4.conf.lo.send_redirects=0 $ sudo sysctl -w net.ipv4.conf.default.send_redirects=0 We want to let sever A send a packet to 8.8.8.8, and route the packet to server B. When server B receives such packet, it might send a ICMP Redirect message to server A, set send_redirects to 0 will disable this behavior. First, generate InAddrErrors. On server B, we disable IP forwarding: $ sudo sysctl -w net.ipv4.conf.all.forwarding=0 On server A, we send packets to 8.8.8.8: $ nc -v 8.8.8.8 53 On server B, we check the output of nstat: $ nstat #kernel IpInReceives 3 0.0 IpInAddrErrors 3 0.0 IpExtInOctets 180 0.0 IpExtInNoECTPkts 3 0.0 As we have let server A route 8.8.8.8 to server B, and we disabled IP forwarding on server B, Server A sent packets to server B, then server B dropped packets and increased IpInAddrErrors. As the nc command would re-send the SYN packet if it didn't receive a SYN+ACK, we could find multiple IpInAddrErrors. Second, generate IpExtInNoRoutes. On server B, we enable IP forwarding: $ sudo sysctl -w net.ipv4.conf.all.forwarding=1 Check the route table of server B and remove the default route: $ ip route show default via 192.168.122.1 dev ens3 proto static 192.168.122.0/24 dev ens3 proto kernel scope link src 192.168.122.251 $ sudo ip route delete default via 192.168.122.1 dev ens3 proto static On server A, we contact 8.8.8.8 again: $ nc -v 8.8.8.8 53 nc: connect to 8.8.8.8 port 53 (tcp) failed: Network is unreachable On server B, run nstat: $ nstat #kernel IpInReceives 1 0.0 IpOutRequests 1 0.0 IcmpOutMsgs 1 0.0 IcmpOutDestUnreachs 1 0.0 IcmpMsgOutType3 1 0.0 IpExtInNoRoutes 1 0.0 IpExtInOctets 60 0.0 IpExtOutOctets 88 0.0 IpExtInNoECTPkts 1 0.0 We enabled IP forwarding on server B, when server B received a packet which destination IP address is 8.8.8.8, server B will try to forward this packet. We have deleted the default route, there was no route for 8.8.8.8, so server B increase IpExtInNoRoutes and sent the "ICMP Destination Unreachable" message to server A. Third, generate IpOutNoRoutes. Run ping command on server B: $ ping -c 1 8.8.8.8 connect: Network is unreachable Run nstat on server B: $ nstat #kernel IpOutNoRoutes 1 0.0 We have deleted the default route on server B. Server B couldn't find a route for the 8.8.8.8 IP address, so server B increased IpOutNoRoutes. TcpExtTCPACKSkippedSynRecv¶ In this test, we send 3 same SYN packets from client to server. The first SYN will let server create a socket, set it to Syn-Recv status, and reply a SYN/ACK. The second SYN will let server reply the SYN/ACK again, and record the reply time (the duplicate ACK reply time). The third SYN will let server check the previous duplicate ACK reply time, and decide to skip the duplicate ACK, then increase the TcpExtTCPACKSkippedSynRecv counter. Run tcpdump to capture a SYN packet: nstatuser@nstat-a:~$ sudo tcpdump -c 1 -w /tmp/syn.pcap port 9000 tcpdump: listening on ens3, link-type EN10MB (Ethernet), capture size 262144 bytes Open another terminal, run nc command: nstatuser@nstat-a:~$ nc nstat-b 9000 As the nstat-b didn't listen on port 9000, it should reply a RST, and the nc command exited immediately. It was enough for the tcpdump command to capture a SYN packet. A linux server might use hardware offload for the TCP checksum, so the checksum in the /tmp/syn.pcap might be not correct. We call tcprewrite to fix it: nstatuser@nstat-a:~$ tcprewrite --infile=/tmp/syn.pcap --outfile=/tmp/syn_fixcsum.pcap --fixcsum On nstat-b, we run nc to listen on port 9000: nstatuser@nstat-b:~$ nc -lkv 9000 Listening on [0.0.0.0] (family 0, port 9000) On nstat-a, we blocked the packet from port 9000, or nstat-a would send RST to nstat-b: nstatuser@nstat-a:~$ sudo iptables -A INPUT -p tcp --sport 9000 -j DROP Send 3 SYN repeatly to nstat-b: nstatuser@nstat-a:~$ for i in {1..3}; do sudo tcpreplay -i ens3 /tmp/syn_fixcsum.pcap; done Check snmp cunter on nstat-b: nstatuser@nstat-b:~$ nstat | grep -i skip TcpExtTCPACKSkippedSynRecv 1 0.0 As we expected, TcpExtTCPACKSkippedSynRecv is 1. TcpExtTCPACKSkippedPAWS¶ To trigger PAWS, we could send an old SYN. On nstat-b, let nc listen on port 9000: nstatuser@nstat-b:~$ nc -lkv 9000 Listening on [0.0.0.0] (family 0, port 9000) On nstat-a, run tcpdump to capture a SYN: nstatuser@nstat-a:~$ sudo tcpdump -w /tmp/paws_pre.pcap -c 1 port 9000 tcpdump: listening on ens3, link-type EN10MB (Ethernet), capture size 262144 bytes On nstat-a, run nc as a client to connect nstat-b: nstatuser@nstat-a:~$ nc -v nstat-b 9000 Connection to nstat-b 9000 port [tcp/*] succeeded! Now the tcpdump has captured the SYN and exit. We should fix the checksum: nstatuser@nstat-a:~$ tcprewrite --infile /tmp/paws_pre.pcap --outfile /tmp/paws.pcap --fixcsum Send the SYN packet twice: nstatuser@nstat-a:~$ for i in {1..2}; do sudo tcpreplay -i ens3 /tmp/paws.pcap; done On nstat-b, check the snmp counter: nstatuser@nstat-b:~$ nstat | grep -i skip TcpExtTCPACKSkippedPAWS 1 0.0 We sent two SYN via tcpreplay, both of them would let PAWS check failed, the nstat-b replied an ACK for the first SYN, skipped the ACK for the second SYN, and updated TcpExtTCPACKSkippedPAWS. TcpExtTCPACKSkippedSeq¶ To trigger TcpExtTCPACKSkippedSeq, we send packets which have valid timestamp (to pass PAWS check) but the sequence number is out of window. The linux TCP stack would avoid to skip if the packet has data, so we need a pure ACK packet. To generate such a packet, we could create two sockets: one on port 9000, another on port 9001. Then we capture an ACK on port 9001, change the source/destination port numbers to match the port 9000 socket. Then we could trigger TcpExtTCPACKSkippedSeq via this packet. On nstat-b, open two terminals, run two nc commands to listen on both port 9000 and port 9001: nstatuser@nstat-b:~$ nc -lkv 9000 Listening on [0.0.0.0] (family 0, port 9000) nstatuser@nstat-b:~$ nc -lkv 9001 Listening on [0.0.0.0] (family 0, port 9001) On nstat-a, run two nc clients: nstatuser@nstat-a:~$ nc -v nstat-b 9000 Connection to nstat-b 9000 port [tcp/*] succeeded! nstatuser@nstat-a:~$ nc -v nstat-b 9001 Connection to nstat-b 9001 port [tcp/*] succeeded! On nstat-a, run tcpdump to capture an ACK: nstatuser@nstat-a:~$ sudo tcpdump -w /tmp/seq_pre.pcap -c 1 dst port 9001 tcpdump: listening on ens3, link-type EN10MB (Ethernet), capture size 262144 bytes On nstat-b, send a packet via the port 9001 socket. E.g. we sent a string 'foo' in our example: nstatuser@nstat-b:~$ nc -lkv 9001 Listening on [0.0.0.0] (family 0, port 9001) Connection from nstat-a 42132 received! foo On nstat-a, the tcpdump should have caputred the ACK. We should check the source port numbers of the two nc clients: nstatuser@nstat-a:~$ ss -ta '( dport = :9000 || dport = :9001 )' | tee State Recv-Q Send-Q Local Address:Port Peer Address:Port ESTAB 0 0 192.168.122.250:50208 192.168.122.251:9000 ESTAB 0 0 192.168.122.250:42132 192.168.122.251:9001 Run tcprewrite, change port 9001 to port 9000, chagne port 42132 to port 50208: nstatuser@nstat-a:~$ tcprewrite --infile /tmp/seq_pre.pcap --outfile /tmp/seq.pcap -r 9001:9000 -r 42132:50208 --fixcsum Now the /tmp/seq.pcap is the packet we need. Send it to nstat-b: nstatuser@nstat-a:~$ for i in {1..2}; do sudo tcpreplay -i ens3 /tmp/seq.pcap; done Check TcpExtTCPACKSkippedSeq on nstat-b: nstatuser@nstat-b:~$ nstat | grep -i skip TcpExtTCPACKSkippedSeq 1 0.0
https://01.org/linuxgraphics/gfx-docs/drm/networking/snmp_counter.html
CC-MAIN-2019-51
refinedweb
9,087
65.01
Hi, I have psipred working (thanks to some posters on here) and can confirm it works for single sequences - however when I input a fasta file with multiple sequences it only gives the output for the last sequence in the file. does anyone know how to get round this? here is the runpsipred.pl script: #!/bin/tcsh # This is a simple script which will carry out all of the basic steps # required to make a PSIPRED V3 prediction using BLAST+. Note that it # assumes that the following programs are in the appropriate directories: # psiblast - PSIBLAST executable (from NCBI BLAST+) # psipred - PSIPRED V3 program # psipass2 - PSIPRED V3 program # chkparse - PSIPRED V3 program # NOTE: Experimental PSIPRED script with BLAST+ compatability (DTJ May 2010) # The name of the BLAST+ data bank set dbname = uniref90filt # Where the NCBI BLAST+ programs have been installed set ncbidir = /usr/local/bin # Where the PSIPRED V3 programs have been installed set execdir = ../bin # Where the PSIPRED V3 data files have been installed set datadir = ../data set basename = $1:r set rootname = $basename:t # Generate a "unique" temporary filename root set hostid = `hostid` set tmproot = psitmp$$$hostid \cp -f $1 $tmproot.fasta echo "Running PSI-BLAST with sequence" $1 "..." $ncbidir/psiblast -db $dbname -query $tmproot.fasta -inclusion_ethresh 0.001 -out_pssm $tmproot.chk -num_iterations 3 -num_alignments 0 >& $tmproot.blast if ($status != 0) then tail $tmproot.blast echo "FATAL: Error whilst running blastpgp - script terminated!" exit $status endif echo "Predicting secondary structure..." $execdir/chkparse $tmproot.chk > $tmproot.mtx if ($status != 0) then echo "FATAL: Error whilst running chkparse - script terminated!" exit $status endif echo Pass1 ... $execdir/psipred $tmproot.mtx $datadir/weights.dat $datadir/weights.dat2 $datadir/weights.dat3 > $rootname.ss if ($status != 0) then echo "FATAL: Error whilst running psipred - script terminated!" exit $status endif echo Pass2 ... $execdir/psipass2 $datadir/weights_p2.dat 1 1.0 1.0 $rootname.ss2 $rootname.ss > $rootname.horiz if ($status != 0) then echo "FATAL: Error whilst running psipass2 - script terminated!" exit $status endif # Remove temporary files echo Cleaning up ... \rm -f $tmproot.* error.log echo "Final output files:" $rootname.ss2 $rootname.horiz echo "Finished." can anyone see why it is not storing (or rather overwriting) n-1 outputs? if anyone can point me to where i need to change this that would be great. thanks, arron.
https://www.biostars.org/p/71086/
CC-MAIN-2018-43
refinedweb
380
60.31
Brandi Love Ranch Hand Posts: 133 posted 13 years ago I'm writing a simple program in which I want the answer to an equation to pop up in a dialog box. All I need to pop up is the value of y. Here is my attempt, and the errors. Any suggestions? //Brandi Love //Computer Science I Lab, Section 113 //Socks Problem public class Socks { public static void main(String[] args) { int x, y; x = 5 + 2; y = x + 1; JOptionPane.showMessageDialog(null,"value of y: " + y, ", "Sample", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } Stan James (instanceof Sidekick) Ranch Hand Ranch Hand Posts: 8791 posted 13 years ago Looks like just the wrong number of quote marks. The compiler points to Sample being incorrect, so the error is somewhere right before that. Look at each of your parameters ... see if one jumps out at you as missing a quote. (I'm resisting giving you the actual answer - you'll enjoy it much more if you spot it!) A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi Brandi Love Ranch Hand Posts: 133 posted 13 years ago Okay so I resolved the whole quotes problem I'm still getting an error though, with the pointer pointing to the J in JOptionPane. Any idea why? [ September 21, 2003: Message edited by: Brandi Love ] [ September 21, 2003: Message edited by: Brandi Love ]
https://coderanch.com/t/394384/java/answer-pop-dialog-box
CC-MAIN-2017-22
refinedweb
258
71.65
Sorry. The same error, This is new stuff. ----------------------------------------------------------------------------------- newtype Parser a = P { parse :: (String -> [(a,String)]) } instance Monad Parser where return v = P (\s -> [(v,s)]) p >>= f = P (\s -> case parse p s of [] -> [] [(v,str)] -> parse (f v) str) fail _ = P (\_ -> []) item :: Parser Char item = \inp -> case inp of [] -> [] (x:xs) -> [(x,xs)] p :: Parser (Char,Char) p = do { x <- item ; item ; y <- item ; return (x,y) } ----------------------------------------------------------------------------------- I got following: Prelude> :load c:\b.hs [1 of 1] Compiling Main ( C:\b.hs, interpreted ) C:\b.hs:13:7: The lambda expression `\ inp -> ...' has one argument, but its type `Parser Char' has none In the expression: \ inp -> case inp of { [] -> [] (x : xs) -> [...] } In the definition of `item': item = \ inp -> case inp of { [] -> [] (x : xs) -> ... } Failed, modules loaded: none. 2010/3/19 Stephen Tetley <stephen.tetley at gmail.com>: > On 19 March 2010 04:35, 国平张 <zhangguoping at gmail.com> wrote: >> Sorry to bother again. I just cannot figure out how it could compile. >> I got compile errors. >> Can someone point out what is right code to use a do notion to make a >> Parser works. > > It looks like the p parser may have the wrong indentation - although > this might be due to either your mail client or my client formatting > wrongly: > > p :: Parser (Char,Char) > p = do x <- item > item > y <- item > return (x,y) > > > Try - with white space all aligned to the start character /x/ of the > first statement in the do: > > p :: Parser (Char,Char) > p = do x <- item > item > y <- item > return (x,y) > > Or with braces and semis: > > p :: Parser (Char,Char) > p = do { x <- item > ; item > ; y <- item > ; return (x,y) } > > Best wishes > > Stephen > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe at haskell.org > >
http://www.haskell.org/pipermail/haskell-cafe/2010-March/074793.html
CC-MAIN-2014-35
refinedweb
293
80.21
This patchset is a revival of some of Eric Biederman's work to make audit pid-namespace-safe. In a couple of places, audit was printing PIDs in the task's pid namespace rather than relative to the audit daemon's pid namespace, which currently is init_pid_ns. It also allows processes to log audit user messages in their own pid namespaces, which was not previously permitted. Please see: Part of the cleanup here involves deprecating task->pid and task->tgid, which are error-prone duplicates of the task->pids structure The next step which I hope to add to this patchset will be to purge task->pid and task->tgid from the rest of the kernel if possible. Once that is done, task_pid_nr_init_ns() and task_tgid_nr_init_ns() that were introduced in patch 05/12 and used in patches 06/12 and 08/12 could be replaced with task_pid_nr() and task_tgid_nr(). Eric B. did take a stab at that, but checking all the subtleties will be non-trivial. Does anyone have any opinions or better yet hard data on cache line misses between pid_nr(struct pid*) and pid_nr_ns(struct pid*, &init_pid_ns)? I'd like to see pid_nr() use pid_nr_ns(struct pid*, &init_pid_ns), or pid_nr_init_ns() eliminated in favour of the original pid_nr(). pid_nr() currently accesses the first level of the pid structure without having to dereference the level number. If there is an actual speed difference, it could be worth keeping, otherwise, I'd prefer to simplify that code. Eric also had a patch to add a printk option to format a struct pid pointer which was PID namespace-aware. I don't see the point, but I'll let him explain it. Discuss. Eric W. Biederman (5): audit: Kill the unused struct audit_aux_data_capset audit: Simplify and correct audit_log_capset Richard Guy Briggs (7): audit: fix netlink portid naming and types pid: get ppid pid_t of task in init_pid_ns safely audit: convert PPIDs to the inital PID namespace. pid: get pid_t of task in init_pid_ns correctly audit: store audit_pid as a struct pid pointer audit: anchor all pid references in the initial pid namespace pid: modify task_pid_nr to work without task->pid. pid: modify task_tgid_nr to work without task->tgid. pid: rewrite task helper functions avoiding task->pid and task->tgid pid: mark struct task const in helper functions drivers/tty/tty_audit.c | 3 +- include/linux/audit.h | 8 ++-- include/linux/pid.h | 6 +++ include/linux/sched.h | 81 ++++++++++++++++++++++++---------- kernel/audit.c | 76 +++++++++++++++++++------------ kernel/audit.h | 12 +++--- kernel/auditfilter.c | 35 +++++++++++---- kernel/auditsc.c | 36 ++++++--------- kernel/capability.c | 2 +- kernel/pid.c | 4 +- security/apparmor/audit.c | 7 +-- security/integrity/integrity_audit.c | 2 +- security/lsm_audit.c | 11 +++-- security/tomoyo/audit.c | 2 +- 14 files changed, 177 insertions(+), 108 deletions(-) -- To unsubscribe from this list: send the line "unsubscribe linux-security-module" in the body of a message to [email protected] More majordomo info at
http://article.gmane.org/gmane.linux.kernel.lsm/19850
CC-MAIN-2018-17
refinedweb
479
57.47
This code is a tight little library encasing the managed DirectX AudioVideoPlayback class. It is broken into three sections, Sounds, Music and Videos. I wrote this code to simplify the process of playing multiple sounds at once, while playing background music. While I was at it, I figured I would add the Video portion just to round the class out. The video section proved to be the most challenging, as I wanted to embed the player as opposed to it opening its own window. I did a lot of searching and found many people asking a lot of the same questions, but no real answers. I also came up against the inherent issues that surround the infamous RenderToTexture() method. AudioVideoPlayback RenderToTexture() Managed DirectX SDK should be installed in order to use this library. However you don't have to know much, or anything at all really about DirectX to get it to work. The first thing you will need to do is add the AudioDX.dll to your references and add your using statement. using using AudioDX; We will start with the sound portion of the library. Simply create a new instance of the Sound class, either globally or locally. Once loaded, it can be played simply by calling its Play() function. Sound Play() Prototype: public Sound( IntPtr Handle, string Filename ) public Sound( IntPtr Handle, string Filename ) Sound m_click = new Sound( this.Handle, "gbClick.wav" ); m_click.Play(); m_click.Stop(); //if and when you need to stop the sound. Much like the Sound class, create a new instance of the Music class and call its Play() function. Alternatively, you can set AutoPlay to true and it will simply begin as soon as it has loaded. So far this class has worked for every audio file type I have tried it with. Music Play() AutoPlay true Prototype: public Music( string FileName,bool AutoRun ) public Music( string FileName,bool AutoRun ) Music m_song = new Music( "Openning.wav", false ); m_song.Play(); m_song.Pause(); //when you need to pause the song. m_song.Stop(); //when you need to stop the song. m_song.Load( "NewSong.wav" ); //Open a new song without creating a new instance. Now things start getting interesting. Using the RenderToTexture() function under certain circumstances can cause numerous errors when attempting to dispose of the object. Most commonly, an Access Violation Exception is thrown. Having done my research on this, I have learned that this is a bug they are aware of but have no intention of fixing. I fumbled upon a work around for this quite by accident. If you handle the Disposing event of the Video object and stall it indefinitely, it allows the program to complete shutting down without throwing the error. This is not something I usually recommend, but it seems to do the trick. I found this when I added a MessageBox to the disposing event handler. The program closed without error before I was able to respond to the MessageBox. This workaround is already incorporated into the library, but for all of you who have been having this problem, I hope this works for you. Disposing Video MessageBox Prototype: public Movie( IntPtr Handle, Rectangle Bounds, string FileName ) public Movie( IntPtr Handle, Rectangle Bounds, string FileName ) Movie m_movie; m_movie = new Movie( this.Handle, this.Bounds, "ws_mcchris.wmv" ); m_movie.Play(); //Stop(), Pause(). //Work around for Access Violation Exception m_video.Disposing += new EventHandler( m_video_Disposing ); void m_video_Disposing( object sender, EventArgs e ) { while( true ); }//Video Disposing The Movie class, while not my original focus, became the real gem of this library. I did not approach it in the typical manner but am happy with the results. There really isn't much to the Sound and Music classes, however bundled all together these three elements form the very basis for all of your AudioVideoPlayback needs. I stopped developing the library once it met my requirements, but there is a lot more functionality that could be added to really up the versatility of this library. I'll leave that bit up to you guys. Thanks and enjoy! Movie AudioVideoPlayback This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3) public void FrameMove() { device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0); device.BeginScene(); // draw a background imageusing Sprite.Draw2D // render all the controls foreach (DXControl ctrl in controlList ) { ctrl.Render(device); } device.EndScene(); device.Present(); } lock (objRoot) { sprite.Begin(SpriteFlags.AlphaBlend); sprite.Draw2D(texture, new Rectangle(), new SizeF(x,y), new PointF(x,y), Color.White); sprite.End(); } void video_TextureReadyToRender(object sender, TextureRenderEventArgs e) { lock (objRoot) { texture = e.Texture } } ap_wooka wrote:If loaded within a project of significant size it can sometimes cause the project to hang while trying to run the program in debug mode within the Development environment. Manager Device General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/14443/Wrapping-up-Managed-DirectX-AudioVideoPlayback
CC-MAIN-2016-36
refinedweb
824
56.45
The OpenSocial API is a set of common APIs for building social applications on many websites. There are two ways to access the OpenSocial API: client-side using the JavaScript API and server-side using RESTful data APIs. The JavaScript API lives under the opensocial.* namespace and provides access to three primary areas of functionality: Here are some of the things you can do with the JavaScript API: The JavaScript API is designed to use standard web technologies: To build an application using the OpenSocial JavaScript API, check out the Getting Started Guide or work through the OpenSocial Tutorial. The RESTful Data APIs will provide complementary functionality to the JavaScript API, so you can access people, activities, and data from your server. The RESTful data APIs are also designed to use standard web technologies:
http://code.google.com/apis/opensocial/docs/
crawl-001
refinedweb
134
57.61
General RPC conventions Status: Experimental The conventions described in this section are RPC specific. When RPC operations occur, metric events about those operations will be generated and reported to provide insight into those operations. By adding RPC properties as attributes on metric events it allows for finely tuned filtering. Metric instruments The following metric instruments MUST be used to describe RPC operations. They MUST be of the specified type and units. Note: RPC server and client metrics are split to allow correlation across client/server boundaries, e.g. Lining up an RPC method latency to determine if the server is responsible for latency the client is seeing. RPC Server Below is a table of RPC server metric instruments. RPC Client Below is a table of RPC client metric instruments. These apply to traditional RPC usage, not streaming RPCs. Attributes Below is a table of attributes that SHOULD be included on metric events and whether or not they should be on the server, client or both. [1]: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The code.namespace attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side). [2]: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The code.function attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side). Additional attribute requirements: At least one of the following sets of attributes is required: rpc.system has the following list of well-known values. If one of them applies, then the respective value MUST be used, otherwise a custom value MAY be used. To avoid high cardinality, implementations should prefer the most stable of net.peer.name or net.peer.ip, depending on expected deployment profile. For many cloud applications, this is likely net.peer.name as names can be recycled even across re-instantiation of a server with a different ip. For client-side metrics net.peer.port is required if the connection is IP-based and the port is available (it describes the server port they are connecting to). For server-side spans net.peer.port is optional (it describes the port the client is connecting from). Furthermore, setting net.transport is required for non-IP connection like named pipe bindings. Service name On the server process receiving and handling the remote procedure call, the service name provided in rpc.service does not necessarily have to match the service.name resource attribute. One process can expose multiple RPC endpoints and thus have multiple RPC service names. From a deployment perspective, as expressed by the service.* resource attributes, it will be treated as one deployed service with one service.name. gRPC conventions For remote procedure calls via gRPC, additional conventions are described in this section. rpc.system MUST be set to "grpc".
https://opentelemetry.io/docs/reference/specification/metrics/semantic_conventions/rpc/
CC-MAIN-2022-21
refinedweb
531
58.38
C Reference Manual Dennis M. Ritchie May 1, 1977 1. Introduction C is a computer language which offers a rich selection of operators and data types and the ability to impose useful structure on both control flow and data. All the basic operations and data objects are close to those actually implemented by most real computers, so that a very efficient implementation is possible, but the design is not tied to any particular machine and with a little care it is possible to write easily portable programs. This manual describes the current version of the C language as it exists on the PDP-11, the Honeywell 6000, the IBM System/370, and the Interdata 8/32. Where differences exist, it concentrates on the PDP-11, but tries to point out implementation-dependent details. With few exceptions, these dependencies follow directly from the underlying properties of the hardware; the various compilers are generally quite compatible. 2. Lexical conventions Blanks, tabs, newlines, and comments as described below are ignored except as they serve to separate tokens. Some space is required to separate otherwise adjacent identifiers, key- words,. April 13, 2015 - 2 - 2.2 Identifiers (Names) An identifier is a sequence of letters and digits; the first character must be alphabetic. The underscore `_' counts as alphabetic. Upper and lower case letters are considered dif- ferent. On the PDP-11, no more than the first eight charac- ters are significant, and only the first seven for external identifiers. 2.3 Keywords The following identifiers are reserved for use as keywords, and may not be used otherwise: int extern else char register for float typedef do double static while struct goto switch union return case long sizeof default short break entry unsigned continue auto if The entry keyword is not currently implemented by any com- piler but is reserved for future use. Some implementations also reserve the word fortran. 2.4 Constants There are several kinds of constants, as follows: 2.4.1 Integer constants An integer constant consisting of a sequence of digits is taken to be octal if it begins with 0 (digit zero), decimal otherwise. The digits 8 and 9 have octal value 10 and 11 respectively. A sequence of digits preceded by 0x or 0X (digit zero) is taken to be a hexadecimal integer. The hexa- decimal digits include a or A through f or F with values 10 through 15. A decimal constant whose value exceeds the larg- est signed machine integer (32767 on the PDP-11) is taken to be long; an octal or hex constant which exceeds the largest unsigned machine integer (0177777 or 0xFFFF on the PDP-11) is likewise taken to be long. 2.4.2 Explicit long constants A decimal, octal, or hexadecimal integer constant immedi- ately followed by l (letter ell) or L is a long constant, which, on the PDP-11, has 32 significant bits. As discussed April 13, 2015 - 3 - below, on other machines integer and long values may be con- sidered identical. 2.4.3 Character constants A character constant is a sequence of characters enclosed in single quotes `''. Within a character constant a single quote must be preceded by a backslash `\'. Certain non- graphic characters, and `\' itself, may be escaped according to the following table: BS \b NL (LF) \n CR \r HT \t FF \f char- acter NUL. If the character following a backslash is not one of those specified, the backslash vanishes. The value of a single-character constant is the numeri- cal value of the character in the machine's character set (ASCII for the PDP-11). On the PDP-11 at most two characters are permitted in a character constant and the second charac- ter of a pair is stored in the high-order byte of the integer value. Character constants with more than one char- acter are inherently machine-dependent and should be avoided. 2.4.4 Floating constants A floating constant consists of an integer part, a decimal point, a fraction part, an e or E, and an optionally signed integer exponent. The integer and fraction parts both con- sist of a sequence of digits. Either the integer part or the fraction part (not both) may be missing; either the decimal point or the e and the exponent (not both) may be missing. Every floating constant is taken to be double-precision. 2.5 Strings A string is a sequence of characters surrounded by double quotes `"'. A string has type `array of characters' and storage class `static' (see below) and is initialized with the given characters. The compiler places a null byte `\0' at the end of each string so that programs which scan the April 13, 2015 - 4 - string can find its end. In a string, the character `"' must be preceded by a `\'; in addition, the same escapes as described for character constants may be used. Finally, a `\' and an immediately following new-line are ignored. All strings, even when written identically, are dis- tinct. 3. Syntax notation In the syntax notation used in this manual, syntactic categories are indicated by italic type, and literal words and characters in sans-serif type. Alternatives are listed on separate lines. An optional terminal or non-terminal sym- bol is indicated by the subscript `opt,' so that { expressionopt } would indicate an optional expression in braces. The com- plete syntax is given in S16, in the notation of YACC. 4. What's in a Name? C bases the interpretation of an identifier upon two attri- butes of the identifier: its storage class and its type. The storage class determines the location and lifetime of the storage associated with an identifier; the type determines the meaning of the values found in the identifier's storage. There are four declarable storage classes: automatic, static, external, and register. Automatic variables are local to each invocation of a block, and are discarded upon exit from the block; static variables are local to a block, but retain their values upon reentry to a block even after control has left the block; external variables exist and retain their values throughout the execution of the entire program, and may be used for communication between func- tions, even separately compiled functions. Register vari- ables are (if possible) stored in the fast registers of the machine; like automatic variables they are local to each block and disappear on exit from the block. C supports several fundamental types of objects: Objects declared as characters (char) are large enough to store any member of the implementation's character set, and if a genuine character is stored in a character vari- able, its value is equivalent to the integer code for that character. Other quantities may be stored into character variables, but the implementation is machine-dependent. On the PDP-11, characters are stored as signed 8-bit integers, and the character set is ASCII. Up to three sizes of integer, declared short int, int, and long int are available. Longer integers provide no less April 13, 2015 - 5 - storage than shorter ones, but the implementation may make either short integers, or long integers, or both equivalent to plain integers. `Plain' integers have the natural size suggested by the host machine architecture; the other sizes are provided to meet special needs. On the PDP-11, short and plain integers are both represented in 16-bit 2's complement notation. Long integers are 32-bit 2's complement. Unsigned integers, declared unsigned, obey the laws of arithmetic modulo $2 sup n$ where $n$ is the number of bits in the representation. (16 on the PDP-11; long and short unsigned quantities are not supported.) Single precision floating point (float) quantities, on the PDP-11, have magnitude in the range approximately $10 sup { ± 38}$ or 0; their precision is 24 bits or about seven decimal digits. Double-precision floating-point (double) quantities on the PDP-11 have the same range as floats and a precision of 56 bits or about 17 decimal digits. Some implementations may make float and double synonymous. Because objects of these types can usefully be inter- preted as numbers, they will be referred to as arithmetic types. Types char and int of all sizes will collectively be called integral types. Float and double will collectively be called floating types. Besides the fundamental arithmetic types there is a conceptually infinite class of derived types constructed from the fundamental April 13, 2015 - 6 - section explains the result to be expected from such conversions. S6.6 summarizes the conversions demanded by most ordinary operators; it will be supplemented as required by the discussion of each operator. 6.1 Characters and integers A character or a short integer may be used wherever an integer may be used. In all cases the value is converted to an integer. Conversion of a short integer always involves sign extension; short integers are signed quantities. Whether or not sign-extension occurs for characters is machine dependent, but it is guaranteed that a member of the standard character set is non-negative. On the PDP-11, char- acter variables range in value from -128 to 127; a character constant specified using an octal escape also suffers sign extension and may appear negative, for example `'\214''. When a longer integer is converted to a shorter or to a char, it is truncated on the left. 6.2 Float and double All floating arithmetic in C is carried out in double- precision; whenever a float appears in an expression it is lengthened to double by zero-padding its fraction. When a double must be converted to float, for example by an assign- ment, the double is rounded before truncation to float length. 6.3 Floating and integral Conversions of floating values to integral type tend to be rather machine-dependent. On the PDP-11, truncation is towards 0. The result is undefined if the value will not fit in the space provided. Conversions of integral values to floating type are well behaved. Some loss of precision occurs if the destina- tion lacks sufficient bits. April 13, 2015 - 7 - 6.4 Pointers and integers An integer or long integer may be added to or subtracted from a pointer; in such a case the first is converted as specified in the discussion of the addition operator. Two pointers to objects of the same type may be sub- tracted; in this case the result is converted to an integer as specified in the discussion of the subtraction operator. 6.5 Unsigned Whenever an unsigned integer and a plain integer are com- bined, the plain integer is converted to unsigned and the result is unsigned. The value (on the PDP-11) is the least unsigned integer congruent to the signed integer (modulo $2 sup 16$). Because of the 2's complement notation, this conversion is conceptual and there is no actual change in the bit pattern. When an unsigned integer is converted to long, the of type float are converted to double. Then, if either operand is double, the other is con- verted to double and that is the type of the result. Otherwise, if either operand is long, the other is con- verted to long and that is the type of the result. Otherwise, if either operand is unsigned, the other is converted to unsigned and that is the type of the result. Otherwise, both operands must be int, and that is the type of the result. 7. Expressions The precedence of expression operators is the same as the order of the major subsections of this section (highest pre- cedence first). Thus the expressions referred to as the operands of + (S7.4) are those expressions defined in SS7.1-7.3. Within each subsection, the operators have the April 13, 2015 - 8 - same precedence. Left- or right-associativity is specified in each subsection for the operators discussed therein. The precedence and associativity of all the expression operators is summarized in the collected grammar. Otherwise the order of evaluation of expressions is undefined. In particular the compiler considers itself free to compute subexpressions in the order it believes most efficient, even if the subexpressions involve side effects. Expressions involving a commutative and associative operator may be rearranged arbitrarily, even in the presence of parentheses; to force a particular order of evaluation an explicit temporary must be used. 7.1 Primary expressions Primary expressions involving ., ->, subscripting, and func- tion calls group left to right. primary-expression: identifier constant string ( expression ) primary-expression [ expression ] primary-expression ( expression-listopt ) primary-lvalue . identifier primary-expression -> identifier expression-list: expression expression-list , expression An identifier is a primary expression, provided it has been suitably declared as discussed below. Its type is specified by its declaration. However, if the type of the identifier is `array of ...', then the value of the identifier- expression is a pointer to the first object in the array, and the type of the expression is `pointer to ...'. More- over, an array identifier is not an lvalue expression. Like- wise, an identifier which is declared `function returning ...', when used except in the function-name position of a call, is converted to `pointer to function returning ...'. A decimal, octal, character, or floating constant is a primary expression. Its type may be int, long, or double depending on its form. A string is a primary expression. Its type is origi- nally `array of char'; but following the same rule given above for identifiers, this is modified to `pointer to char' and the result is a pointer to the first character in the string. (There is an exception in certain initializers; see S8.6.) A parenthesized expression is a primary expression whose type and value are identical to those of the unadorned expression. The presence of parentheses does not affect whether the expression is an lvalue. April 13, 2015 - 9 - A primary expression followed by an expression in square brackets is a primary expression. The intuitive mean- ing section together with the discussions in SS 7.1, 7.2, and 7.4 on identifiers, *, and + respectively; S14.3 below summarizes the implications. A function call is a primary expression followed by parentheses containing a possibly empty, comma-separated list of expressions which constitute the actual arguments to the function. The primary expression must be of type `func- tion returning ...', and the result of the function call is of type `...'. As indicated below, a hitherto unseen iden- tifier followed immediately by a left parenthesis is contex- tually declared to represent a function returning an integer; thus in the most common case, integer-valued func- tions need not be declared. Any actual arguments of type float are converted to double before the call; any of type char or short are con- verted to int. In preparing for the call to a function, a copy is made of each actual parameter; thus, all argument-passing in C is strictly by value. A function may change the values of its formal parameters, but these changes cannot affect the values of the actual parameters. On the other hand, it is possible to pass a pointer on the understanding that the function may change the value of the object to which the pointer points. The order of evaluation of arguments is undefined by the language; take note that the various com- pilers differ. Recursive calls to any function are permitted. A primary expression followed by a dot followed by an identifier is an expression. The first expression must be an lvalue naming a structure or union, and the identifier must name a member of the structure or union. The result is an lvalue referring to the named member of the structure or union. A primary expression followed by an arrow (built from a `-' and a `>') followed by an identifier is an expression. The first expression must be a pointer to a structure or a union and the identifier must name a member of that struc- ture or union. The result is an lvalue referring to the named member of the structure or union to which the pointer expression points. April 13, 2015 - 10 - Thus the expression `E1->MOS' is the same as `(*E1).MOS'. Structures and unions are discussed in S8.5. The rules given here for the use of structures and unions are not enforced strictly, in order to allow an escape from the typing mechanism. See S14.1. sub- tracting its value from $2 sup n$, where $n$ is 16 on the PDP-11. The result of the logical negation operator ! is 1 if the value of its operand is 0, 0 if the value of its operand is non-zero. incremented. The value is the new value of the operand, but is not an lvalue. The expression `++a' is equivalent to `(a += 1)'. See the discussions of addition (S7.4) and assignment operators (S7.14) for information on conversions. The lvalue operand of prefix `--' is decremented analo- gously to the ++ operator. When postfix `++' is applied to an lvalue the result is April 13, 2015 - 11 - prefix -- operator. The type of the result is the same as the type of the lvalue expression. An expression preceded by the parenthesized name of a data type causes conversion of the value of the expression to the named type. The construction of type names is described in S8.7. The sizeof operator yields the size, in bytes, of its operand. (A byte is undefined by the language except in terms of the value of sizeof. However in all existing imple- mentations a byte is the space required to hold a char.) When applied to an array, the result is the total number of bytes in the array. The size is determined from the declara- tions of the objects in the expression. This expression is semantically an integer constant and may be used anywhere a constant is required. Its major use is in communication with routines like storage allocators and I/O systems.: expres- sion * expression expression / expression expression % expression The binary * operator indicates multiplication. The * opera- tor is associative and expressions with several multiplica- tions at the same level may be rearranged. The binary / operator indicates division. When positive integers are divided truncation is toward 0, but the form of truncation is machine-dependent if either operand is nega- tive. In all cases it is true that $(a/b) * b~+~ a%b ~ = ~ a$. On the PDP-11, the remainder has the same sign as the dividend. April 13, 2015 - 12 - The binary % operator yields the remainder from the division of the first expression by the second. The usual arithmetic conversions are performed. On the PDP-11, the remainder has the same sign as the dividend. The operands must not be floating. 7.4 Additive operators The additive operators + and - group left-to-right. The usual arithmetic conversions are performed. There are some additional, and which points to another object in the same array, appropriately offset from the original object. Thus if P is a pointer to an object in an array, the expression `P+1' is a pointer to the next object in the array. No further type combinations are allowed. The + operator is associative and expressions with several additions at the same level may be rearranged. The result of the `-' operator is the difference of the operands. The usual arithmetic conversions are performed. Additionally, a value of any integral type may be subtracted from a pointer, and then the same conversions as for addi- tion apply. If two pointers to objects of the same type are sub- tracted, the result is converted (by division by the length of the object) to an int representing the number of objects separating the pointed-to objects. This conversion will in general give unexpected results unless the pointers point to objects in the same array, since pointers, even to objects of the same type, do not necessarily differ by a multiple of the object-length. larger than the number of bits in the object. shift-expression: expression << April 13, 2015 - 13 - expression expression >> expression The value of `E1<<E2' is E1 (interpreted as a bit pattern) left-shifted E2 bits; vacated bits are 0-filled. The value of `E1>>E2' is E1 right-shifted E2 bit positions. The shift is guaranteed to be logical (0-fill) if E1 is unsigned; oth- erwise it may be (and is, on the PDP-11) arithmetic (fill by a copy of the sign bit). 7.6 Relational operators The relational operators group left-to-right, but this fact is not very useful; `a<b<c' does not mean what it seems to. performed. Two pointers may be compared, and). A pointer may be compared to an integer, but the result is machine dependent unless & expres- sion The & operator is associative and expressions involving & may be rearranged. The usual arithmetic conversions are per- formed; the result is the bit-wise `and' function of the operands. The operator applies only to integral operands. April 13, 2015 - 14 - 7.9 Bitwise exclusive or operator exclusive-or-expression: expression ^ expression The ^ operator is associative and expressions involving ^ may be rearranged. The usual arithmetic conversions are per- formed; the result is is the bit-wise `exclusive or' func- tion of the operands. The operator applies only to integral operands. 7.10 Bitwise inclusive or operator inclusive-or-expression: expression | expression The | operator is associative and expressions with | may be rearranged. The usual arithmetic conversions are performed; the result is the bit-wise `inclusive or' function of its operands. The operator applies only to integral operands. 7.11 Logical and operator logical-and-expression: expression && expression The && operator groups left-to-right. It returns 1 if both its operands are non-zero, 0 otherwise. Unlike &, && guaran- tees left-to-right evaluation; moreover the second operand is not evaluated if the first operand is 0. The operands need not have the same type, but each must have one of the fundamental types or be a pointer. The result is always int. 7.12 Logical or operator logical-or-expression: expression || expression The || operator groups left-to-right. It returns 1 if either of its operands is non-zero, and 0 otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the value of the first operand is non-zero. The operands need not have the same type, but each must have one of the fundamental types or be a pointer. The result is always int. 7.13 Conditional operator conditional-expression: expression ? April 13, 2015 - 15 - expression : expression Conditional expressions group right-to-left. The first expression is evaluated and if it is non-zero, the result is the value of the second expression, otherwise that of third expression. If possible, the usual arithmetic conversions are performed to bring the second and third expressions to a common type; otherwise, if both are pointers Notice that the representation of the compound assignment operators has changed; formerly the `=' came first and the other operator came second (without any space). The compiler continues to accept the previous notation. In the simple assignment with `=', the value of the expression replaces that of the object referred to by the lvalue. If both operands have arithmetic type, the right operand is converted to the type of the left preparatory to the assignment. converted as explained in S7.4; all right operands and all non-pointer left operands must have arithmetic type. The compiler currently allows a pointer to be assigned to an integer, an integer to a pointer, and a pointer to a pointer of another type. The assignment is a pure copy operation, with no conversion. This usage is nonportable, and may produce pointers which cause addressing exceptions April 13, 2015 - 16 - when used. However, it is guaranteed that assignment of the constant 0 to a pointer will produce a null pointer distin- guishable from a pointer to any object. 7.15 Comma operator comma-expression: expression , expression A pair of expressions separated by a comma is evaluated left-to-right and the value of the left expression is dis- carded. The type and value of the result are the type and value of the right operand. This operator groups left-to- right. In contexts where comma is given a special meaning, for example in a list of actual arguments to functions (S7.1) and lists of initializers (S8.6), the comma operator as described in this section can only appear in parentheses; for example, `f(a, (t = 3, t+2), c)' has three arguments, the second of which has the value 5. 8. Declarations Declarations are used within function definitions to specify the interpretation which C gives to each identifier; they do not necessarily reserve storage associated with the identif- ier. Declarations have the form declaration: decl-specifiers declarator-listopt ; The declarators in the declarator-list contain the identif- iers being declared. The decl-specifiers consist of a sequence of type and storage class specifiers.; it is discussed in S8.8. The meanings of the various storage classes were dis- cussed in S4. The auto, static, and register declarations also serve as definitions in that they cause an appropriate amount of storage to be reserved. In the extern case there must be an April 13, 2015 - 17 - external definition (S10) for the given identifiers some- where outside the function in which they are declared. A register declaration is best thought of as an auto declaration, together with a hint to the compiler that the variables declared will be heavily used. Only the first few (three, for the PDP-11) such declarations are effective. Moreover, only variables of certain types will be stored in registers; on the PDP-11, they are int, char, or pointer. One restriction applies to register variables: the address- of operator & cannot be applied to them. Smaller, faster programs can be expected if register declarations are used appropriately, but future developments may render them unnecessary. At most one sc-specifier may be given in a declaration. If the sc-specifier is missing from a declaration, it is taken to be auto inside a function, extern outside. Excep- tion: functions are always extern. 8.2 Type specifiers The type-specifiers are type-specifier: char short int long unsigned float double struct-or-union- specifier typedef-name The words long, short, and unsigned may be thought of as adjectives; the following combinations are acceptable (in any order). short int long int unsigned int long float The meaning of the last is the same as double. Otherwise, at most one type-specifier may be given in a declaration. If the type-specifier is missing from a declaration, it is taken to be int. Specifiers for structures and unions are discussed in S8.5; declarations with typedef names are discussed in S8.8. 8.3 Declarators The declarator-list appearing in a declaration is a comma- separated sequence of declarators, each of which may have an initializer. declarator-list: init- declarator init-declarator , declarator-list init-declarator: declarator initializeropt Initializers are discussed in S8.6. The specifiers in the declaration indicate the type and storage class of the April 13, 2015 - 18 - objects to which the declarators refer. Declarators have the syntax: identif- ier; it is this identifier that is declared. If an unadorned identifier appears as a declarator, then it has the type indicated by the specifier heading the declaration. A declarator in parentheses is identical to the una- dorned declarator, but the binding of complex declarators may be altered by parentheses. See the examples below. If a declarator has the form * D for D a declarator, then the contained identifier has the type `pointer to ...', where `...' is the type which the identifier would have had if the declarator had been simply D. If a declarator has the form D() then the contained identifier has the type `function return- ing ...', where `...' is the type which the identifier would have had if the declarator had been simply D. A declarator may have the form D[constant-expression] or D[] Such declarators make the contained identifier have type `array.' If the unadorned declarator D would specify a non- array of type `...', then the declarator `D[i]' yields a 1- dimensional array with rank i of objects of type `...'. If the unadorned declarator D would specify an n-dimensional April 13, 2015 - 19 - array with rank $i sub 1 times i sub 2 times ... times i sub n$, then the declarator $roman D [ i sub { n+1 } ]$ yields an $(n+1)$-dimensional array with rank $i sub 1 times i sub 2 times ... times i sub n times i sub { n+1}$. In the first case the constant expression is an expres- sion whose value is determinable at compile time, and whose type is int. (Constant expressions are defined precisely in S15.) The constant expression of an array declarator may be missing only for the first dimension. This notation is use- ful when the array is external and the actual declaration, which allocates storage, is given elsewhere. The constant- expression may also be omitted when the declarator is fol- lowed by initialization. In this case the size is calculated from the number of initial elements supplied. An array may be constructed from one of the basic types, from a pointer, from a structure or union, or from another array (to generate a multi-dimensional array). Not all the possibilities allowed by the syntax above are actually permitted. The restrictions are as follows: functions may not return arrays, structures or functions, although they may return pointers to such things; there are no arrays of functions, although there may be arrays of pointers to functions. Likewise a structure may not contain a function, but it may contain a pointer to a function. As an example, the declaration int i, *ip, f(), *fip(), (*pfi)(); declares an integer i, a pointer ip to an integer, a func- tion f returning an integer, a function fip returning a pointer to an integer, and a pointer pfi to a function which returns an integer. It is especially useful to compare the last two. The binding of `*fip()' is `*(fip())', so that the declaration suggests, and the same construction in an expression requires, the calling of a function fip, and then using indirection through the (pointer) result to yield an integer. In the declarator `(*pfi)()', the extra parentheses are necessary, as they are also in an expression, to indi- cate that indirection through a pointer to a function yields a function, which is then called. As another example, float fa[17], *afp[17]; declares an array of float numbers and an array of pointers to float numbers. Finally, static int x3d[3][5][7]; April 13, 2015 - 20 - declares a static three. structure is set off from the field name by a colon. struct-declarator: declarator declarator : constant-expression : constant-expression Within a structure, the objects declared have addresses which increase as their declarations are read left-to-right. Each non-field member of a structure begins on an addressing boundary appropriate to its type. On the PDP-11 the only requirement is that non-characters begin on a word boundary; therefore, there may be 1-byte, unnamed holes in a struc- ture. Field members are packed into machine integers; they do not straddle words. A field which does not fit into the space remaining in a word is put into the next word. No field may be wider than a word. On the PDP-11, fields are assigned right-to-left. April 13, 2015 - 21 - A struct-declarator with no declarator, only a colon and a width, indicates an unnamed field useful for padding to conform to externally-imposed layouts. As a special case, an unnamed field with a width of 0 specifies alignment of the next field at a word boundary. The `next field' presum- ably is a field, not an ordinary structure member, because in the latter case the alignment would have been automatic. The language does not restrict the types of things that are declared as fields, but implementations are not required to support any but integer fields. Moreover, even int fields may be considered to be unsigned. On the PDP-11, fields are not signed and have only integer values. Structure tags allow definition of self-referential struc- tures; they also permit the long part of the declaration to be given once and used several times. It is however absurd to declare a structure or union which contains an instance of itself, as distinct from a pointer to an instance of itself. The names of members and tags may be the same as ordi- nary variables. However, names of tags and members must be mutually distinct. Two structures may share a common initial sequence of members; that is, the same member may appear in two dif- ferent structures if it has the same type in both and if all previous members are the same in both. (Actually, the com- piler checks only that a name in two different structures has the same type and offset in both, but if preceding members differ the construction is nonportable.) A simple example of a structure declaration is April 13, 2015 - 22 - struct tnode { char tword[20]; int count; struct tnode *left; struct tnode *right; }; which contains an array of 20 characters, an integer, and two pointers to similar structures. Once this declaration has been given, the following declaration makes sense: struct tnode s, *sp; which declares s to be a structure of the given sort and sp to be a pointer to a structure of the given sort. With these declarations, the expression sp->count refers to the count field of the structure to which sp points; s.left refers to the left subtree pointer of the structure s. Finally, s.right->tword[0] refers to the first character of the tword member of the right subtree of s. 8.6 Initialization A declarator may specify an initial value for the identifier being declared. The initializer is preceded by `=', and con- sists of an expression or a list of values nested in braces. initializer: = expression = { initializer-list } = { initializer-list , } initializer-list: expression initializer-list , initializer-list { initializer-list } The `=' is a new addition to the syntax, intended to allevi- ate potential ambiguities. The current compiler allows it to be omitted when the rest of the initializer is a very simple expression (just a name, string, or constant) or when the rest of the initializer is enclosed in braces. All the expressions in an initializer for a static or external variable must be constant expressions, which are April 13, 2015 - 23 - described in S15, or expressions which reduce to the address of a previously declared variable, possibly offset by a con- stant expression. Automatic or register variables may be initialized by arbitrary expressions involving previously declared variables. When an initializer applies to a scalar (a pointer or an object of arithmetic type), it consists of a single expression, perhaps in braces. The initial value of the object is taken from the expression; the same conversions as for assignment are performed. When the declared variable is an aggregate (a structure or array) then 0's. It is not permitted to initialize unions or automatic aggregates. Currently, the PDP-11 compiler also forbids initializing fields in structures. Braces may be elided as follows. If the initializer begins with a left brace, then the succeding comma-separated list of initializers initialize the members of the aggre- gate; it is erroneous for there to be more initializers than members. If, however, the initializer does not begin with a left brace, then only enough elements from the list are taken to account for the members of the aggregate; any remaining members are left to initialize the next member of the aggregate of which the current aggregate is a part. A final abbreviation allows a char array to be initial- ized by a string. In this case successive members of the string initialize the members of the array. For example, int x[ ] = { 1, 3, 5 }; declares and initializes x as a 1-dimensional array which has three members, since no size was specified and there are three initializers. float y[4][3] = { { 1, 3, 5 }, { 2, 4, 6 }, { 3, 5, 7 }, }; is a completely-bracketed initialization: 1, 3, and 5 ini- tialize the first row of the array $y [ 0 ]$, namely $y [ 0 April 13, 2015 - 24 - ] [ 0 ]$, $y [ 0 ] [ 1 ]$, and $y [ 0 ] [ 2 ]$. Likewise the next two lines initialize $y [ 1 ]$ and $y [ 2 ]$. The ini- tial 3 elements from the list are used. Likewise the next three are taken successively for $y [ 1 ]$ and $y [ 2 ]$. Also, float y[4][3] = { { 1 }, { 2 }, { 3 }, { 4 } }; initializes the first column of y (regarded as a two- dimensional array) and leaves the rest 0. Finally, char msg[] = "Syntax error on line %s\n"; shows a character array whose members are initialized with a string. 8.7 Type names In two contexts (to specify type conversions explicitly,, April 13, 2015 - 25 - int int * int *[3] int (*)[3] name respectively the types `integer,' `pointer to integer,' `array of 3 pointers to integers,' and `pointer to an array of 3 integers.' As another example, int i; . . . sin( (double) i); calls the sin routine (which accepts a double argument) with an argument appropriately converted. 8.8 Typedef Declarations whose `storage class' is typedef do not define storage, but instead define identifiers which can be used later as if they were type keywords naming fundamental or derived types. Within the scope of a declaration involving typedef, each of the identifiers appearing as part of any declarators therein become syntactically equivalent to type keywords naming the type associated with the identifiers in the way described in S8.4. typedef-name: identifier. Zp is a pointer to such a structure. Typedef does not introduce brand new types, only synonyms for types which could be specified in another way. Thus in the example above distance is considered to have exactly the same type as any other int variable. 9. Statements Except as indicated, statements are executed in sequence. April 13, 2015 - 26 - 9.1 Expression statement Most statements are expression statements, which have the form expression ; Usually expression statements are assignments or function calls., at which time it resumes its force. Any initializations of auto or register variables are performed each time the block is entered at the top. It is currently possible (but a bad practice) to transfer into a block; in that case the initializations are not performed. Initializations of static variables are performed only once when the program begins execution. Inside a block, external declarations do not reserve storage so initialization is not permitted. 9.3 Conditional statement The two forms of the conditional statement are if ( expression ) statement if ( expression ) statement else statement In both cases the expression is evaluated and if it is non- zero, the first substatement is executed. In the second case the second substatement is executed if the expression is 0. As usual the `else' ambiguity is resolved by connecting an else with the last encountered elseless if. 9.4 While statement The while statement has the form while ( expression ) statement The substatement is executed repeatedly so long as the value of the expression remains non-zero. The test takes place April 13, 2015 - 27 - before each execution of the statement. 9.5 Do statement The do statement has the form do statement while ( expression ) ; The substatement is executed repeatedly until the value of the expression becomes zero. The test takes place after each execution of the statement. 9.6 For statement The for statement has the form for ( expression-1opt ; expression-2opt ; expression-3opt ) statement This statement is equivalent to expression-1; while (expression-2) { statement expression-3; } Thus the first expression specifies initialization for the loop; the second specifies a test, made before each itera- tion, such that the loop is exited when the expression becomes 0; the third expression typically specifies an incrementation which is performed after each iteration. Any or all of the expressions may be dropped. A missing expression-2 makes the implied while clause equivalent to `while(1)'; other missing expressions are simply dropped from the expansion above. 9.7 Switch statement The switch statement causes control to be transferred to one of several statements depending on the value of an expres- sion. It has the form switch ( expression ) state- ment The usual arithmetic conversion is performed on the expres- sion, but the result must be int. The statement is typically compound. Any statement within the statement may be labelled with one or more case prefixes as follows: case constant-expression : where the constant expression must be int. No two of the case constants in the same switch may have the same value. Constant expressions are precisely defined in S15. There may also be at most one statement prefix of the form default : When the switch statement is executed, its expression is evaluated and compared with each case constant If one of the case constants is equal to the value of the expression, April 13, 2015 - 28 - control is passed to the statement following the matched case prefix. If no case constant matches the expression, and if there is a default prefix, control passes to the prefixed statement. If no case matches and if there is no default then none of the statements in the switch is executed. Case and Bd default prefixes in themselves do not alter the flow of control, which continues unimpeded across such prefixes. To exit from a switch, see break, S9.8. Usually the statement that is the subject of a switch is compound. Declarations may appear at the head of this statement, initializations of automatic or register vari- ables are ineffective. 9.8 Break statement The statement break ; causes termination of the smallest enclosing while, do, for, or switch statement; control passes to the statement follow- ing the terminated statement. 9.9 Continue statement The statement continue ; causes control to pass to the loop-continuation portion of the smallest enclosing while, do, or for statement; that is to the end of the loop. More precisely, in each of the statements while (...) { do { for (...) { ... ... ... contin:; contin:; contin:; } } while (...); } a continue is equivalent to `goto contin'. (Following the `contin:' is a null statement, S9.13.) con- verted, as if by assignment, to the type of the function in which it appears. Flowing off the end of a function is equivalent to a return with no returned value. 9.11 Goto statement Control may be transferred unconditionally by means of the April 13, 2015 - 29 - statement goto identifier ; The identifier must be a label (S9.12) located in the current function. Previous versions of C had an incompletely implemented notion of label variable, which has been with- drawn. 9.12 Labelled statement Any statement may be preceded by label prefixes of the form identifier : which serve to declare the identifier as a label. The only use of a label is as a target of a goto. The scope of a label is the current function, excluding any sub-blocks in which the same identifier has been redeclared. See S11. (S8.2) may also be empty, in which case the type is taken to be int. The scope of external definitions persists to the end of the file in which they are declared just as the effect of declarations S11.2 for the distinction between them. A function declarator is similar to a declarator for a `function returning ...' except that it lists the formal parameters of the function being defined. function- declarator: declarator ( parameter-listopt ) parameter-list: identifier identifier , parameter-list April 13, 2015 - 30 - The function-body has the form function-body: declaration-list compound-statement The identifiers in the parameter list, and only those iden- tifiers, may be declared in the declaration list. Any iden- tifiers whose type is not given are taken to be int. The only storage class which may be specified is register; if it is specified, the corresponding actual parameter will be copied, if possible, parentheses in the return are not required. C converts all float actual parameters to double, so formal parameters declared float have their declaration adjusted to read double. Also, since a reference to an array in any context (in particular as an actual parameter) is taken to mean a pointer to the first element of the array, declarations of formal parameters declared `array of ...' are adjusted to read `pointer to ...'. Finally, because nei- ther structures nor functions can be passed to a function, it is useless to declare a formal parameter to be a struc- ture or function (pointers to structures or functions are of course permitted). A free return statement is supplied at the end of each function definition, so running off the end causes control, but no value, to be returned to the caller. April 13, 2015 - 31 - source text of the program may be kept in several files, and precompiled routines may be loaded from libraries. Communi- cation among the functions of a program may be carried out both through explicit calls and through manipulation of external data. Therefore, there are two kinds of scope to consider: first, what may be called the lexical scope of an identif- ier, which is essentially the region of a program during which it may be used without drawing `undefined identifier' diagnostics; and second, the scope associated with external identifiers, which is characterized by the rule that refer- ences to the same external identifier are references to the same object. 11.1 Lexical scope The lexical scope of identifiers declared in external defin- itions persists from the definition through the end of the file in which they appear. The lexical scope of identifiers which are formal parameters persists through the function with which they are associated. The lexical scope of iden- tifiers declared at the head of blocks persists until the end of the block. The lexical scope of labels is the whole of the function in which they appear. Because all references to the same external identifier refer to the same object (see S11.2) the compiler checks all declarations of the same external identifier for compatibil- ity; in effect their scope is increased to the whole file in which they appear. In all cases, however, if an identifier is explicitly declared at the head of a block, including the block consti- tuting a function, any declaration of that identifier out- side the block is suspended until the end of the block. Remember also (S8.5) that identifiers associated with ordinary variables on the one hand and those associated with structure and union members and tags on the other form two disjoint classes which do not conflict. Typedef names are in the same class as ordinary identifiers. They may be rede- clared in inner blocks, but an explicit type must be given in the inner declaration: typedef float distance; . . . { auto int distance; . . . The int must be present in the second declaration, or it would be taken to be a declaration with no declarators and type distance.* _________________________ April 13, 2015 - 32 - 11.2 Scope of externals If a function declares an identifier to be extern, then somewhere among the files or libraries constituting the com- plete program there must be an external definition for the identifier. All functions in a given program which refer to the same external identifier refer to the same object, so care must be taken that the type and extent specified in the definition are compatible with those specified by each func- tion which references the data. In PDP-11 C, compatible external definitions of the same identifier may be present in several of the separately-compiled pieces of a complete program, or even twice within the same program file, with the limitation that the identifier may be initialized in at most one of the definitions. In other operating systems, however, the com- piler must know in just which file the storage for the iden- tifier is allocated, and in which file the identifier is merely being referred to. The appearance of the extern key- word in an external definition indicates that storage for the identifiers being declared will be allocated in another file. Thus in a multi-file program, an external data defini- tion without the extern specifier must appear in exactly one of the files. Any other files which wish to give an external definition for the identifier must include the extern in the definition. The identifier can be initialized only in the declaration where storage is allocated. Identifiers declared static at the top level in exter- nal definitions are not visible in other files. 12. Compiler control lines The C compiler contains a preprocessor capable of macro sub- stitution, conditional compilation, and inclusion of named files. Lines beginning with `#' communicate with this preprocessor. These lines have syntax independent of the rest of the language; they may appear anywhere and have effect which lasts (independent of scope) until the end of the source program file. 12.1 Token replacement A compiler-control line of the form # define iden- tifier token-string (note: no trailing semicolon) causes the preprocessor to replace subsequent instances of the identifier with the given string of tokens. A line of the form # define identifier( identifier , ... , identifier ) token-string _________________________ *It is agreed that the ice is thin here. April 13, 2015 - 33 - where there is no space between the first identifier and the `(', is a macro definition with arguments. Subsequent instances of the first identifier followed by a `(', a sequence of tokens delimited by commas, and a `)' are replaced by the token string in the definition. Each occurrence of an identifier mentioned in the formal parame- ter list of the definition is replaced by the corresponding token string from the call. The actual arguments in the call are token strings separated by commas; however commas in quoted strings or protected by parentheses do not separate arguments. The number of formal and actual parameters must be the same. Text inside a string or a character constant is not subject to replacement. In both forms the replacement string is rescanned for more defined identifiers. In both forms a long definition may be continued on another line by writing `\' at the end of the line to be continued. This facility is most valuable for definition of `mani- fest constants', as in # define TABSIZE 100 ... int table[TABSIZE]; A control line of the form # undef identifier causes the identifier's preprocessor definition to be for- gotten. 12.2 File inclusion A compiler control line of the form # include "filename" causes the replacement of that line by the entire contents of the file filename. The named file is searched for first in the directory of the original source file, and then in a sequence of stan- dard places. Alternatively, a control line of the form # include <filename> searches only the standard places, and not the directory of the source file. Includes may be nested. 12.3 Conditional compilation A compiler control line of the form # if constant- expression April 13, 2015 - 34 - checks whether the constant expression (see S15) evaluates to non-zero. A control line of the form # ifdef identifier checks whether the identifier is currently defined in the preprocessor; that is, whether it has been the subject of a #define control line. A control line of the form # ifndef identifier checks whether the identifier is currently undefined in the preprocessor. All three forms are followed by an arbitrary number of lines, possibly containing a control line # else and then by a control line # endif If the checked condition is true then any lines between #else and #endif are ignored. If the checked condition is false then any lines between the test and an #else or, lack- ing an #else, the #endif, are ignored. These constructions may be nested. 12.4 Line control For the benefit of other preprocessors which generate C pro- grams, a line of the form # line constant identifier causes the compiler to believe, for purposes of error diag- nostics, that the next line number is given by the constant and the current input file is named by the identifier. If the identifier is absent the remembered file name does not change. 13. Implicit declarations It is not always necessary to specify both the storage class and the type of identifiers in a declaration. Sometimes the storage class is supplied by the context: in external defin- itions, and in declarations of formal parameters and struc- ture members. In a declaration inside a function, if a storage class but no type is given, the identifier is assumed to be int; if a type but no storage class is indi- cated, the identifier is assumed to be auto. An exception to the latter rule is made for functions, since auto functions are meaningless (C being incapable of compiling code into the stack). If the type of an identifier is `function returning ...', it is implicitly declared to be extern. In an expression, an identifier followed by ( and not currently declared is contextually declared to be `function returning int'. April 13, 2015 - 35 - 14. Types revisited This section summarizes the operations which can be per- formed on objects of certain types. 14.1 Structures and unions There are only two things that can be done with a structure or union: name one of its members (by means of the . opera- tor); or take its address (by unary &). Other operations, such as assigning from or to it or passing it as a parame- ter, draw an error message. In the future, it is expected that these operations, but not necessarily others, will be allowed. S7.1 says that in a direct or indirect structure refer- ence (with . or ->) the name on the right must be a member of the structure named or pointed to by the expression on the left. To allow an escape from the typing rules, this restriction is not firmly enforced by the compiler. In fact, any lvalue is allowed before `.', and that lvalue is then assumed to have the form of the structure of which the name on the right is a member. Also, the expression before a `->' is required only to be a pointer or an integer. If a pointer, it is assumed to point to a structure of which the name on the right is a member. If an integer, it is taken to be the absolute address, in machine storage units, of the appropriate structure. Such constructions are non-portable. 14.2 Functions There are only two things that can be done with a function: call it, or take its address. If the name of a function appears in an expression not in the function-name position of a call, a pointer to the function is generated. Thus, to pass one function to another, one might say int f(); ... g(f); Then the definition of g might read g(funcp) int (*funcp)(); { ... (*funcp)(); ... } Notice that f was declared explicitly in the calling routine April 13, 2015 - 36 - since its first appearance inter- preted opera- tion. A consistent rule is followed in the case of multi- dimensional arrays. If E is an n-dimensional array of rank $i times j times ... times k$, then E appearing in an expression is converted to a pointer to an (n-1)-dimensional array with rank $j times ... times k$. If the * operator, either explicitly or implicitly as a result of subscripting, is applied to this pointer, the result is the pointed-to (n-1)-dimensional array, which itself is immediately con- verted con- verted to a pointer as described; then i is converted to the type of x, which involves multiplying i by the length the object to which the pointer points, namely 5 integer objects. The results are added and indirection applied to yield an array (of 5 integers) which in turn is converted to a pointer to the first of the integers. If there is another subscript the same argument applies again; this time the result is an integer. It follows from all this that arrays in C are stored row-wise (last subscript varies fastest) and that the first subscript in the declaration helps determine the amount of storage consumed by an array but plays no other part in sub- script calculations. 15. Constant expressions In several places C requires expressions which evaluate to a constant: after case, as array bounds, and in initializers. In the first two cases, the expression can involve only integer constants, character constants, and sizeof April 13, 2015 - 37 - expressions, possibly connected by the binary operators + - * / % & | ^ << >> == != < > <= >= or by the unary operators - ~ or by the ternary operator ? : Parentheses can be used for grouping, but not for function calls. A bit more latitude is permitted for initializers; besides constant expressions as discussed above, one can also apply the unary & operator to external or static objects, and to external or static arrays subscripted with a constant expression. The unary & can also be applied impli- citly by appearance of unsubscripted arrays and functions. The basic rule is that initializers must evaluate either to a constant or to the address of a previously declared exter- nal or static object plus or minus a constant. April 13, 2015 - 38 - 16. Grammar revisited. This section repeats the grammar of C in notation some- what different than given before. The description below is adapted directly from a YACC grammar actually used by several compilers; thus it may (aside from possible editing errors) be regarded as authentic. The notation is pure YACC with the exception that the `|' separating alternatives for a production is omitted, since alternatives are always on separate lines; the `;' separating productions is omitted since a blank line is left between productions. The lines with `%term' name the terminal symbols, which are either commented upon or should be self-evident. The lines with `%left,' `%right,' and `%binary' indicate whether the listed terminals are left-associative, right- associative, or non-associative, and describe a precedence structure. The precedence (binding strength) increases as one reads down the page. When the construction `%prec x' appears the precedence of the rule is that of the terminal x; otherwise the precedence of the rule is that of its left- most terminal. %term NAME %term STRING %term ICON %term FCON %term PLUS %term MINUS %term MUL %term AND %term QUEST %term COLON %term ANDAND %term OROR %term ASOP /* old-style =+ etc. */ %term RELOP /* <= >= < > */ %term EQUOP /* == != */ %term DIVOP /* / % */ %term OR /* | */ %term EXOR /* ^ */ %term SHIFTOP /* << >> */ %term INCOP /* ++ -- */ %term UNOP /* ! ~ */ %term STROP /* . -> */ %term TYPE /* int, char, long, float, double, unsigned, short */ %term CLASS /* extern, register, auto, static, typedef */ %term STRUCT /* struct or union */ %term RETURN %term GOTO %term IF April 13, 2015 - 39 - %term ELSE %term SWITCH %term BREAK %term CONTINUE %term WHILE %term DO %term FOR %term DEFAULT %term CASE %term SIZEOF %term LP /* ( */ %term RP /* ) */ %term LC /* { */ %term RC /* } */ %term LB /* [ */ %term RB /* ] */ %term CM /* , */ %term SM /* ; */ %term ASSIGN /* = */ %left CM %right ASOP ASSIGN %right QUEST COLON %left OROR %left ANDAND %left OROP %left AND %binary EQUOP %binary RELOP %left SHIFTOP %left PLUS MINUS %left MUL DIVOP %right UNOP %right INCOP SIZEOF %left LB LP STROP program: ext_def_list ext_def_list: ext_def_list external_def /* empty */ external_def: optattrib SM optattrib init_dcl_list SM optattrib fdeclarator function_body function_body: dcl_list compoundstmt dcl_list: dcl_list declaration /* empty */ April 13, 2015 - 40 - declaration: specifiers declarator_list SM specifiers SM optattrib: specifiers /* empty */ specifiers: CLASS type type CLASS CLASS type type: TYPE TYPE TYPE struct_dcl struct_dcl: STRUCT NAME LC type_dcl_list RC STRUCT LC type_dcl_list RC STRUCT NAME type_dcl_list: type_declaration type_dcl_list type_declaration type_declaration: type declarator_list SM struct_dcl SM type SM declarator_list: declarator declarator_list CM declarator declarator: fdeclarator nfdeclarator nfdeclarator COLON con_e %prec CM COLON con_e %prec CM nfdeclarator: MUL nfdeclarator nfdeclarator LP RP nfdeclarator LB RB nfdeclarator LB con_e RB NAME LP nfdeclarator RP fdeclarator: MUL fdeclarator fdeclarator LP RP fdeclarator LB RB fdeclarator LB con_e RB LP fdeclarator RP NAME LP name_list RP NAME LP RP name_list: NAME name_list CM NAME init_dcl_list: init_declarator %prec CM April 13, 2015 - 41 - init_dcl_list CM init_declarator init_declarator: nfdeclarator nfdeclarator ASSIGN initializer nfdeclarator initializer fdeclarator init_list: initializer %prec CM init_list CM initializer initializer: e %prec CM LC init_list RC LC init_list CM RC compoundstmt: LC dcl_list stmt_list RC stmt_list: stmt_list statement /* empty */ statement: e SM compoundstmt IF LP e RP statement IF LP e RP statement ELSE statement WHILE LP e RP statement DO statement WHILE LP e RP SM FOR LP opt_e SM opt_e SM opt_e RP statement SWITCH LP e RP statement BREAK SM CONTINUE SM RETURN SM RETURN e SM GOTO NAME SM SM label statement label: NAME COLON CASE con_e COLON DEFAULT COLON con_e: e %prec CM opt_e: e /* empty */ elist: e %prec CM elist CM e e: e MUL e e CM e e DIVOP e e PLUS e e MINUS e e SHIFTOP e e RELOP e April 13, 2015 - 42 - e EQUOP e e AND e e OROP e e ANDAND e e OROR e e MUL ASSIGN e e DIVOP ASSIGN e e PLUS ASSIGN e e MINUS ASSIGN e e SHIFTOP ASSIGN e e AND ASSIGN e e OROP ASSIGN e e QUEST e COLON e e ASOP e e ASSIGN e term term: term INCOP MUL term AND term MINUS term UNOP term INCOP term SIZEOF term LP type_name RP term %prec STROP SIZEOF LP type_name RP %prec SIZEOF term LB e RB term LP RP term LP elist RP term STROP NAME NAME ICON FCON STRING LP e RP type_name: type abst_decl abst_decl: /* empty */ LP RP LP abst_decl RP LP RP MUL abst_decl abst_decl LB RB abst_decl LB con_e RB LP abst_decl RP.
http://www.mirbsd.org/htman/i386/manPSD/23.Cknr.htm
CC-MAIN-2015-18
refinedweb
10,296
51.38
Developing a Game Leader Board using Spring Boot + Redis in AWS Cloud I have always been excited about the world of gaming and we have hit a stage where all gamers are online and play against each other in a networked environment. So it is becoming a challenge as well as a necessity to keep track of the Game Leader Board online in realtime. Thus we are going to have a look on how to build a Game Leader Board using Spring Boot and deploy it in AWS Cloud with an Application Load Balancer and three EC2 instances connecting to an ElastiCache Redis instance. We are going to implement the above mentioned architecture in AWS Cloud. Step 1 We need to develop the Spring Boot application using Spring Data Redis and Spring Boot Actuator as main dependencies. The complete source code can be found at. Also there are releases of this project available at. The application makes use of Redis Sorted Set to maintain the leaderboard. The main classes are GameLeaderBoardService @Service public class GameLeaderBoardService { @Autowired private RedisTemplate<String, String> redisTemplate; @Resource(name = "redisTemplate") private ZSetOperations<String, String> zSetOperations; public List<Gamer> add(Gamer gamer) { zSetOperations.add("leaderboard", gamer.getName(), gamer.getRank()); return zSetOperations.rangeWithScores("leaderboard" ,0,10) .stream().map(e -> new Gamer(e.getValue(), e.getScore())) .collect(Collectors.toList()); } public void deleteAll() { zSetOperations.getOperations().delete("leaderboard"); } } and GameLeaderBoardController @RestController @RequestMapping("/gameleaderboard") public class GameLeaderBoardController { @Autowired private GameLeaderBoardService gameLeaderBoardService; @PostMapping public List<Gamer> add(@RequestBody Gamer gamer) { return gameLeaderBoardService.add(gamer); } @DeleteMapping public void deleteAll() { gameLeaderBoardService.deleteAll(); } } Step 2 We need to create ElastiCache Redis instance. This step will take some time so better to do it as soon as possible. Step 3 We need to create 3 EC2 instances and add those to a Target Group. When Creating the EC2 instances the following script needs to be used as User Data so that the EC2 instances will be created and initialized to run the latest version of the Game Leader Board Spring Boot. #!/bin/bash yum update -y sudo yum install -y java-1.8.0-openjdk wget sudo java -Dserver.port=80 -Dspring.redis.host=<ELASTIC_CACHE_REDIS_HOST> -jar spring-boot-redis-0.0.3.jar Just need to replace <ELASTIC_CACHE_REDIS_HOST> placeholder with the ElastiCache Redis Host URL created in the Step 2. Step 4 Now we need to create a Target Group and register the 3 EC2 Instances created as part of the Target Group. We can use /actuator/health URL since have added Spring Boot Actuator so that the Target Group can ping that for heart beat checks. Once the heart beats return as expected the Target Group will show all the EC2 Instances registered as healthy. Step 5 Now it is time to create the Application Load Balancer which redirects traffic to our Target Group created in Step 4. Once it is done we can copy the Load Balancer DNS Name and start sending requests. Step 6 Now if everything is done correctly we should be able to send POST requests to <ALB_DNS_NAME>/gameleaderboard URL. And subsequent requests to the same URL with different values will add to the Leaderboard in correct order. Conclusion This project showed us how we can leverage the capabilities of Spring Boot, Redis and AWS Cloud to create a scaleable realtime game leader board solution. This solution can be improved and if you have any comments or suggestions please mention them in the comments section.
https://shazinsadakath.medium.com/developing-a-game-leader-board-using-spring-boot-redis-in-aws-cloud-4a287ab1f0e2?source=read_next_recirc---------3---------------------56219642_359d_4490_88b4_5f9788be42f3-------
CC-MAIN-2022-27
refinedweb
573
54.22
для этой страницы, отображается код на другом Adding Morph Targets This article describes how to work with a morph target animation also known as blend shapes in Unigine. Usually, morph targets are used to change facial expressions of characters. The following article shows how to export the mesh with morph targets from Autodesk Maya and then add it to Unigine. Requirements# - It is supposed that you already have a 3D model with blend shapes ready to be exported. - It is supposed that you already have a world created. See Also# - Description of the ObjectMeshSkinned class functions. Step 1. Export a Mesh with Blend Shapes from Maya# This section shows the way of exporting meshes with blend shapes in the FBX format from Autodesk Maya. It contains an example mesh of a calf, which has 2 blend shapes (morph targets). To export the mesh with blend shapes, you should do the following: - In Autodesk Maya, select the mesh with blend shapes to be exported. - On the main menu, click File -> Export Selection... - In the Export Selection window, choose a folder to save the mesh and specify a name for the FBX file. In the Files of type drop-down list, choose FBX export. - In the File Type Specific Options tab with export options, specify parameters to export the mesh. - In the Deformed Models tab, check the Blend Shapes checkbox to export blend shapes. - Click Export Selection. Now you have the mesh in the FBX format that can be easily added to your project. Step 2. Add a Mesh into the World# This section shows how to add the exported mesh to the world and set up morph target animation. To add the exported mesh to the world: - Import the .fbx file with the Import Morph Targets option enabled. - Add the imported file to the scene. - Save the world. Each blend shape of the mesh is a target. You need to create morph targets for a surface of the mesh and set parameters to these targets to control the morph target animation. The following example shows, how to create morph targets and set parameters from the code: AppWorldLogic.h: #ifndef __APP_WORLD_LOGIC_H__ #define __APP_WORLD_LOGIC_H__ #include <UnigineLogic.h> #include <UnigineStreams.h> #include <UnigineObjects.h> #include <UnigineEditor.h> #include <UnigineGame.h> #include <UnigineMathLib.h> using namespace Unigine; class AppWorldLogic : public Unigine::WorldLogic { public: AppWorldLogic(); virtual ~AppWorldLogic(); virtual int init(); virtual int update(); virtual int render(); virtual int flush(); virtual int shutdown(); virtual int destroy(); virtual int save(const Unigine::StreamPtr &stream); virtual int restore(const Unigine::StreamPtr &stream); private: ObjectMeshSkinnedPtr mesh; }; #endif // __APP_WORLD_LOGIC_H__ #include "AppWorldLogic.h" int AppWorldLogic::init() { // get the node that refers to the exported FBX file and cast it to a skinned mesh mesh = ObjectMeshSkinned::cast(Editor::get()->getNodeByName("sphere_0")); // set the number of morph targets mesh->setNumTargets(5, 0); return 1; } int AppWorldLogic::update() { float time = Game::get()->getTime() * 2.0f; // calculate weights of targets float k0 = sin(time * 3.0f) + 0.75f; float k1 = cos(time * 3.0f) + 0.75f; // set targets with parameters mesh->setTarget(0, 1, 0, 1.0f, 0); mesh->setTarget(1, 1, 0, -k0, 0); mesh->setTarget(2, 1, 0, -k1, 0); mesh->setTarget(3, 1, 1, k0, 0); mesh->setTarget(4, 1, 2, k1, 0); return 1; } int AppWorldLogic::shutdown() { mesh.clear(); return 1; } The code given above gets the node that refers to the FBX file and sets parameters to morph targets. Let's clarify the essential things: - The exported mesh was obtained by casting the node that refers to the FBX asset to ObjectMeshSkinned. The node is obtained from the Editor by the name. - The setNumTargets() function sets the number of targets for the surface of the mesh. The exported mesh in the example given above has 2 targets (blend shapes). - By using the setTarget() function, all parameters for each created morph target are set in the update() function. Each target has its target weight. Weights have an influence on coordinates of the mesh: coordinates are multiplied by their weights. Thus, all enabled targets are multiplied by their weights and the new mesh is created:final_xyz = target_0_xyz * weight_0 + target_1_xyz * weight_1 + ... - Since in the code given above, sin() and cos() functions are used for animation blending of different targets, five targets are created: - Source code (C++)This target is if for the bind pose without any interpolation. mesh->setTarget(0,1,0,1.0f,0); - Source code (C++)These targets are used for interpolation of two animations blending. mesh->setTarget(1,1,0,-k0,0); mesh->setTarget(2,1,0,-k1,0); - Source code (C++)This target is used for the first animation blending, which uses the sin() function for interpolation. mesh->setTarget(3,1,1,k0,0); - Source code (C++)This target is used for the second animation blending, which uses the cos() function for interpolation. mesh->setTarget(4,1,2,k1,0); After assigning the material to the mesh, the result looks as follows:
https://developer.unigine.com/ru/docs/2.7.3/content/tutorials/morph/?rlang=cpp
CC-MAIN-2021-31
refinedweb
822
56.45
The goal of the blog entry is simple: I want to understand everything happening under the covers when you take advantage of ASP.NET AJAX inheritance. So, let’s start with a simple code sample: Listing 1 – AjaxInheritance.aspx> The JavaScript code in Listing 1 defines two objects named BaseControl and TreeViewControl. These objects might represent user interface controls that are displayed in a web page. The TreeViewControl inherits from the BaseControl object. First, the BaseControl object is defined with a constructor function named BaseControl. The constructor function initializes two fields named _propA and _propB. Next, get and set accessor methods are added to the BaseControl object’s prototype. These methods expose the private _propA and _propB fields as public properties. Finally, the BaseControl object is registered as a class by calling the ASP.NET AJAX registerClass() method. We’ll be discussing what this method call does in detail in a moment. Second, a new object named TreeViewControl is defined. Notice that the TreeViewControl constructor function includes a call to an ASP.NET AJAX method named initializeBase(). We also need to discuss what is going on with this method in a moment. Like the BaseControl, the TreeViewControl is registered as a class by calling the registerClass() method. However, the TreeViewControl class is registered as inheriting from the BaseControl class. The second parameter passed to the registerClass() method enables you to specify a base class. Finally, an instance of the TreeViewControl is created named treeView1. The get_propA() and get_propB() methods of the object are called and the results of these method calls are displayed with alert boxes in the browser. Understanding the registerClass() Method The first ASP.NET AJAX method that we need to examine in detail is the registerClass() method. This method accepts the following three parameters: · typeName – The name of the class being registered · baseType – (optional) The base class for the class being registered · interfaceTypes – (optional) The array of interfaces that the class being registered implements You can view the entire source code for the registerClass() method by examining the MicrosoftAjax.debug.js file included in the standalone Microsoft AJAX Library. You can download the standalone library from. I’ve stripped the validation code and the code related to working with interfaces from the registerClass() method and I’ve included the remaining source code in Listing 2. Listing 2 – MicrosoftAjax.debug.js registerClass() method 1: Type.prototype.registerClass = function(typeName, baseType, interfaceTypes) { 2: 3: var parsedName; 4: try { 5: parsedName = eval(typeName); 6: } 7: catch(e) { 8: throw Error.argument('typeName', Sys.Res.argumentTypeName); 9: } 10: if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); 11: if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); 12: if (baseType && !baseType.__class) throw Error.argument('baseType', Sys.Res.baseNotAClass); 13: this.prototype.constructor = this; 14: this.__typeName = typeName; 15: this.__class = true; 16: if (baseType) { 17: this.__baseType = baseType; 18: this.__basePrototypePending = true; 19: } 20: Sys.__upperCaseTypes[typeName.toUpperCase()] = this; 21: 22: Sys.__registeredTypes[typeName] = true; 23: return this; 24: } The first thing that you should notice about the code in Listing 2 is that the registerClass() method is a method of the Type object (it is defined on the Type prototype). What is the Type object? The Type object is an alias for the JavaScript Function object. The Microsoft AJAX Library creates this alias with the following line of code: window.Type = Function; Therefore, you can call the registerClass() method on any function. Typically, you would call registerClass() method on a function that acts as an object constructor. Let’s go through the source code for the registerClass() method in Listing 2 step-by-step starting with the following code: 1: var parsedName; 2: try { 3: parsedName = eval(typeName); 4: } 5: catch(e) { 6: throw Error.argument('typeName', Sys.Res.argumentTypeName); 7: } 8: if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); When you call the registerClass() method, the first parameter is a string that corresponds to the current function’s name. You call the registerClass() method for a class named TreeViewControl like this: TreeViewControl.registerClass(“TreeViewControl”); This seems redundant. Why do you need to refer to TreeViewControl twice: once as an object and once as a string? I assume that the goal was to get a string representation of the function name. The code above checks whether evaluating the string name equals the actual function. One way to avoid this redundancy would be to extract the name of the function by calling toString() on the function and matching the function name like this: this.toString().match(/( w+)/)[0] This line of code returns the name of the object that the current method is being called upon. Presumably, this approach was not used for performance reasons. The next block of code for the registerClass() method looks like this: 1: if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); 2: if (baseType && !baseType.__class) throw Error.argument('baseType', Sys.Res.baseNotAClass); The first line prevents you from registering two classes with the same class name. The second line validates whether or not the baseType parameter represents a class. The next line of code looks like this: this.prototype.constructor = this; This line of code is interesting. It fixes a problem with the constructor property in JavaScript illustrated with the code in Listing 3: Listing 3 – BadConstructor.js 1: <script type="text/javascript"> 2: 3: // Bad Constructor 4: function A() {} 5: function B() {} 6: 7: B.prototype = new A(); 8: 9: var x = new B(); 10: alert( x.constructor ); // Returns A 11: 12: 13: // Good Constructor 14: function A() {} 15: function B() {} 16: 17: B.prototype = new A(); 18: B.prototype.constructor = B; // fix constructor 19: 20: var x = new B(); 21: alert( x.constructor ); // Returns B 22: 23: 24: </script> The constructor function should return the name of the function used to construct the current object. Unfortunately, when there is a prototype chain, the constructor property returns the wrong constructor function. It returns the name of the function used to construct the top object in the prototype chain. When x.constructor is first called in Listing 3, the property returns the wrong value. When the x.constructor method is called later in the code (after fixing the constructor property), the x.constructor property returns the correct value. Here’s the next block of code from the registerClass() method: 1: this.__typeName = typeName; 2: this.__class = true; 3: if (baseType) { 4: this.__baseType = baseType; 5: this.__basePrototypePending = true; 6: } 7: Sys.__upperCaseTypes[typeName.toUpperCase()] = this; 8: 9: Sys.__registeredTypes[typeName] = true; This code adds several properties to the current constructor function: __typeName, __class, __baseType, and __basePrototypePending. These properties are used by the reflection methods and by the initializeBase() method that we discuss in the next section. Finally, notice that the name of the constructor function (the class) is registered in two arrays kept in the Sys namespace: __upperCaseTypes and __registeredTypes. The __upperCaseTypes array is used by the Type.parse() method which takes a type name and returns an instance of the type. The __registeredTypes array is used by the registerClass() method to make sure that a class is not registered more than once. One thing that you should notice about the registerClass() method is that it does not modify the prototype property. The constructor function’s prototype property is not modified until the initializeBase() method is called. We discuss initializeBase() in the next section. Understanding the initializeBase() Method You call the initializeBase() method in the constructor of a derived class. For example, in Listing 1, we called the initializeBase() method in the constructor function for the TreeViewControl class. If you don’t call this method, the derived class does not inherit anything from its super class. I’ve included a stripped down version of the initializeBase() method in Listing 4. Listing 4 – MicrosoftAjax.debug.js initializeBase() 1: Type.prototype.initializeBase = function(instance, baseArguments) { 2: if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this); 3: this.resolveInheritance(); 4: if (this.__baseType) { 5: if (!baseArguments) { 6: this.__baseType.apply(instance); 7: } 8: else { 9: this.__baseType.apply(instance, baseArguments); 10: } 11: } 12: return instance; 13: } Like the registerClass() method, the initializeBase() method is created as a method of the Function object (The Function object is aliased with the name Type). So you can call initializeBase() on any function. The intention is that you will call this method within a constructor function on the current function (or a super class of the current function). Let’s go through the code in Listing 4 line-by-line starting with the following code: if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this); This code validates whether the instance parameter passed to the initializeBase() method corresponds to the current function (or a super class of the current function). For example, the following code will throw an exception since the initializeBase() method is being called on the A function within the C function (You’ll only get these exceptions when in debug mode): Listing 5 – BadInitializeBase.js 1: <script type="text/javascript"> 2: 3: function A() {} 4: A.registerClass("A"); 5: function B() {} 6: B.registerClass("B"); 7: function C() 8: { 9: A.initializeBase(this); // throws exception 10: B.initializeBase(this); // ok 11: C.initializeBase(this); // ok 12: } 13: C.registerClass("C", B); 14: 15: var x = new C(); 16: 17: 18: </script> The next statement in the initializeBase() method is the most important statement: this.resolveInheritance(); This statement modifies the current function’s prototype by calling the resolveInheritance() method. The resolveInheritance() method (slightly edited) is contained in Listing 6. Listing 6 – MicrosoftAjax.debug.js resolveInheritance() 1: Type.prototype.resolveInheritance = function() { 2: if (this.__basePrototypePending) { 3: var baseType = this.__baseType; 4: baseType.resolveInheritance(); 5: for (var memberName in baseType.prototype) { 6: var memberValue = baseType.prototype[memberName]; 7: if (!this.prototype[memberName]) { 8: this.prototype[memberName] = memberValue; 9: } 10: } 11: delete this.__basePrototypePending; 12: } 13: } The resolveInheritance() method checks whether or not the constructor function’s __basePrototypePending property has the value true. The registerClass() method sets __basePrototypePending to the value true when you register a new class. Next, the resolveInheritance() method is called recursively for each constructor function in the inheritance chain. When the top of the chain is hit, all of the properties of the prototype of a constructor function higher in the chain are copied down. Consider the code in Listing 7 (the same code as Listing 1). Listing 7 – AjaxInheritance.js> When initializeBase() is called in the constructor for the TreeView control, the resolveInheritance() method is called. The resolveInheritance() method looks up the base type for the TreeViewControl constructor function. In this case, the base type is BaseControl. Each property from the base type’s prototype is copied to the TreeViewControl constructor’s prototype. In particular, the get_propA, set_propA, get_propB, set_propB, and constructor properties are copied from the prototype for BaseControl to the prototype for TreeViewControl. Why are the properties copied from the parent constructor function’s prototype to the current prototype? In other words, why are the prototypes flattened? Presumably, for reasons of performance. If all of the properties are copied to the lowest prototype in the prototype chain, then the prototype chain never needs to be climbed to resolve the value of any property. In Firefox, the following statement returns the value true: alert( treeView1.__proto__.hasOwnProperty("get_propB") ); // displays true The __proto__ property is a Firefox only property that represents the current object’s prototype. The hasOwnProperty() JavaScript method returns true only when a property is a local property of an object and not when a property is read from the prototype chain. This statement shows that the prototype has been flattened and the prototype chain can be ignored when reading a property. The final code executed by the initializeBase() method appears below: 1: if (this.__baseType) { 2: if (!baseArguments) { 3: this.__baseType.apply(instance); 4: } 5: else { 6: this.__baseType.apply(instance, baseArguments); 7: } 8: } This code checks whether the current constructor function has been assigned a base type in the registerClass() method. If there is a base type, the JavaScript apply() method is called to pass the object being created to the constructor function for the base type. This last bit of code is necessary to initialize any private fields from the base class for the current object. The apply() method explains how the treeView1 object gets its _propA and _propB fields. Conclusion While writing this blog entry and working through the registerClass() and initializeBase() methods, I was surprised to discover that the ASP.NET AJAX Framework flattened the prototype chain. I was under the impression that ASP.NET AJAX used strict JavaScript prototype inheritance. Presumably, as mentioned previously, the prototype chain is flattened for performance reasons. There is a lot of interesting code in the Microsoft AJAX Library. There’s a lot that can be learned from a close study of the source code. Impressive analysis. A few more things to point out. First, the inheritance resolving only happens the first time the class is instantiated. This guarantess fast library loading, and that you only pay the price for inheritance when you actually use it. Second, a great deal of what you see in the debug script is not in the release version. For example, evaluating the class name to check it against the actual constructor is something you don’t want to do in release mode because it’s so expensive. Lots of interface-related code is also absent from the release version. I still not understand about this code.. but i will learn.. thanks for sharing.. i always hate with redundant stuff……headaches! Many code here.. i still not understand.. but i will try to learn it.. Wow.. great tutorial here.. thanks for sharing this.. i’m lucky.. Stephen! You really very well described. % i prefer to use what is expert said….so thanks a lot stephen. You really very well described. Great tutorial here! 34 mkjk It looks like DataContextExtensions.cs line 45 of the Save method should pass the primaryKeyName through toC Blu-ray Ripper is Blu-ray converter, Blu-ray ripper, Blu-ray rip software to convert Blu-ray, rip blu ray to avi, DivX, MPEG, WMV, MP4, WMA, MP3 easily and quickly. blu ray dvd to mp3, blu-ray to ipod converter thank, reall a nice articles keep it up Wow.. great tutorial here..thanks for sharing this.. i’m lucky Great tutorial here!
http://stephenwalther.com/archive/2008/03/06/asp-net-ajax-in-depth-object-inheritance
CC-MAIN-2017-43
refinedweb
2,414
51.65
Internode part of TSQR. More... #include <Tsqr_DistTsqr.hpp> This class combines the ncols by ncols R factors computed by the intranode TSQR factorization on individual MPI processes. It is a model as well as the default for Tsqr's DistTsqrType template parameter. LocalOrdinal: index type for dense matrices of Scalar. Known to work with int. Scalar: value type for matrices to factor. Known to work with float, double, std::complex<float>, std::complex<double>. Definition at line 56 of file Tsqr_DistTsqr.hpp. Constructor Definition at line 69 of file Tsqr_DistTsqr.hpp. Destructor. The destructor doesn't need to do anything, thanks to smart pointers. Definition at line 86 of file Tsqr_DistTsqr.hpp. Rank of this MPI process (via MPI_Comm_rank()) Definition at line 76 of file Tsqr_DistTsqr.hpp. Total number of MPI processes in this communicator (via MPI_Comm_size()) Definition at line 80 of file Tsqr_DistTsqr.hpp. Whether or not all diagonal entries of the R factor computed by the QR factorization are guaranteed to be nonnegative. Definition at line 90 of file Tsqr_DistTsqr.hpp. Internode TSQR with explicit Q factor. Call this routine (instead of factor() and explicit_Q()) if you want to compute the QR factorization and only want the Q factor in explicit form (i.e., as a matrix). Definition at line 116 of file Tsqr_DistTsqr.hpp. Fill in the timings vector with cumulative timings from factorExplicit(). The vector gets resized to fit all the timings. Definition at line 125 of file Tsqr_DistTsqr.hpp. Fill in the labels vector with the string labels for the timings from factorExplicit(). The vector gets resized to fit all the labels. Definition at line 134 of file Tsqr_Dist 163 of file Tsqr_DistTsqr.hpp.
http://trilinos.sandia.gov/packages/docs/r10.6/packages/anasazi/doc/html/classTSQR_1_1DistTsqr.html
CC-MAIN-2013-48
refinedweb
279
60.82
!! If you’re like me, you don’t really do a lot with COM components these days. For me, I’ve been ‘lucky’ to stay in the managed world for the past 6 or 7 years. Until last week. I’m running a project to upgrade a web interface to an older COM-based application. The old web interface is all classic ASP and lots of tables, in-line styles and a bunch of other late 90’s and early 2000’s goodies. So in addition to updating the UI to be more modern looking and responsive, I decided to give the server side an update, too. So I built some COM-InterOp DLL’s (easily through VS2012’s Add Reference feature…nothing new here) and built a test console line app to make sure the COM DLL’s were actually built according to the COM spec. There’s a document management system that I’m thinking of whose COM DLLs were not proper COM DLLs and crashed and burned every time .NET tried to call them through a COM-InterOp layer. Anyway, my test app worked like a champ and I felt confident that I could build a nice façade around the COM DLL’s and wrap some functionality internally and only expose to my users/clients what they really needed. So I did this, built some tests and also built a test web app to make sure everything worked great. It did. It ran fine in IIS Express via Visual Studio 2012, and the timings were very close to the pure Classic ASP calls, so there wasn’t much overhead involved going through the COM-InterOp layer. You know where this is going, don’t you? So I deployed my test app to a DEV server running IIS 7.5. When I went to my first test page that called the COM-InterOp layer, I got this pretty message: Retrieving the COM class factory for component with CLSID {81C08CAE-1453-11D4-BEBC-00500457076D} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)). It worked as a console app and while running under IIS Express, so it must be permissions, right? I gave every account I could think of all sorts of COM+ rights and nothing, nada, zilch! Then I came across this question on Experts Exchange, and at the bottom of the page, someone mentioned that the app pool should be running to allow 32-bit apps to run. Oh yeah, my machine is 64-bit; these COM DLL’s I’m using are old and are definitely 32-bit. I didn’t check for that and didn’t even think about that. But I went ahead and looked at the app pool that my web site was running under and what did I see? Yep, select your app pool in IIS 7.x, click on Advanced Settings and check for “Enable 32-bit Applications”. I went ahead and set it to True and my test application suddenly worked. Hope this helps somebody out there from pulling out your hair.! So, first off, I’m by no means a mobile developer. I’ve played around with some samples here and there, but I have not built anything significant to date. So I’m not that familiar with the publishing process for iPhone, Android and WP7 applications. OK, with that out of the way, I will say that I am an owner of 2 WP7 devices (one for me, and one for my wife). We both like them a lot, think the UI is great and intuitive, and like how the device is laid out. Honestly, when I go back to my iPod Touch device, I find it a bit clunky compared to the WP7 devices. I have about the same number of apps on both devices – my iPod Touch has a few more financial and personal applications than my WP7 device does because of the sheer number of more apps in the App Store. But I have a good number of apps that exist on both platforms (e.g. Netflix, Amazon, IMDB, Evernote, etc.) and I think a good number of them look and perform better on the WP7 device. But what bothers me is that the activity in the App Store dwarfs the activity in the WP7 Marketplace. The apps on my iPod Touch seem to have updates every week or so – updates that provide fixes and functionality. The apps from the WP7 Marketplace are few and far between, and usually don’t provide a lot of functionality. Granted, this is not scientific – but more of an informal observation. But what this tells me is that companies aren’t investing a lot in WP7 applications. Looking through the WP7 Marketplace, while there are a large number of apps, there aren’t a lot of “professional” applications. There’s no E-Trade, Schwab or an app for my personal bank; few productivity apps that are free; and just a bunch of odd apps scattered throughout the marketplace. My guess is that a lot of developers are building apps for personal gain; but few companies are building apps. All of this makes me concerned for the future of WP7. I think it’s a great OS that has a lot of potential, but I’m afraid that it’s going to be a niche OS at best. I think Microsoft should pay attention to some of the items in this blog post about how they can get the WP7 out there. If they don’t react and try to improve the reach of WP7, I think Microsoft’s future in the mobile space is over. I had a situation where I had to deserialize a small chunk of JSON-formatted data and I didn’t want to create a class for it since it was a very specific use and I was confident there wasn’t a need to reuse it elsewhere in the application. If I did have a class defined for the JSON data, I could easily use JSON.NET’s JsonConvert.DeserializeObject method: 1: string myJson = "[{id: 10, typeID: 4},{id: 100, typeID: 3}]"; 2: MyObject obj = JsonConvert.DeserializeObject<MyObject>(myJson); 3: Console.WriteLine(obj[0].id); So this is easy to do, but I really didn’t want to define a MyObject class for a one-time use. So I thought I’d go the route of an anonymous type and use JSON.NET’s JsonConvert.DeserializeAnonymousType method. I thought it was a bit vague how to use this since it asks for a type parameter – but since my output will be an anonymous type, what would my type parameter be? Well, the best way that I came up with in a short period of time was to define a dummy anonymous type and pass it to the JsonConvert method. It’s a little bit of overhead and an extra line of code, but it does work. 2: var dummyObject = new[] { new { id = 0, typeID = 0 } }; 3: var myObjects = JsonConvert.DeserializeAnonymousType(myJson, dummyObject); 4: Console.WriteLine(myObjects[0].id); The slightly confusing part was the Intellisense provided by JSON.net: Seeing the ‘T’ type parameter makes you think you need a call to typeof() or something similar. But in the case of deserializing to an anonymous type, you just need an instance of the anonymous type. I thought I may have been missing something, but a little Bing research showed that there were similar approaches taken (see here and here). After!! I. In the project that I’m working on (let’s call it BrainCredits v2.0), I wanted to integrate a user’s Gravatar into the system (like how StackOverflow does it). To Gravatar’s credit, they make it very easy to incorporate a user’s image – just hash the user’s email address (which I have) to the end of their URL and you’ll get the image back. The email address just has to be hashed using the MD5 algorithm, and they provide examples of how to do that in PHP. Oh, it looks so easy: echo md5( "MyEmailAddress@example.com " ); It’s a one-liner in PHP – just call md5() passing in the string you want to hash and you’ll get your hash back. There must be a similar method in C#, right? As far as I can tell, there isn’t. You have to: myByte.ToString("x2").ToLower() Now you have your string. Lots of work, especially compared to PHP. Perhaps this is why so many developers go towards PHP? Anyway, I need to generate this hash, and decided to create an Extension Method for it. My full code looks like this: using System.Text; namespace System { public static class StringExtensions { public static String MD5(this String stringToHash) { var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] emailBytes = System.Text.Encoding.UTF8.GetBytes(stringToHash.ToLower()); byte[] hashedEmailBytes = md5.ComputeHash(emailBytes); System.Text.StringBuilder sb = new StringBuilder(); foreach (var b in hashedEmailBytes) { sb.Append(b.ToString("x2").ToLower()); } return sb.ToString(); } } } You would call it like this: String emailToHash = "dhoerster@gmail.com"; String hashedEmail = emailToHash.MD5(); Oh, that’s easy! And it makes sense. Well, I hope this helps someone, and maybe there will be some suggestions on how to improve this. Good luck! I have to admit that I’m a basic user when it comes to JSON serialization/deserialization. I’ve used JSON.NET and the DataContractJsonSerializer. I’ve read that JSON.NET is faster and more efficient than the built-in .NET serializer, but I haven’t had to build a system that is dependent on squeezing microseconds out of my serialization routines. That said, I do prefer JSON.NET because it is more flexible when it comes to using DataContractAttribute and DataMemberAttribute for customizing your JSON output. So I came across an interesting question on StackOverflow today, asking how a json string like: {‘one’: 1, ‘two’: 2, ‘three’: 3, ‘four’: 4, ‘blah’: 100} would have its “one” and “two” properties deserialized to an object’s One and Two properties (easy) and anything else in the json string would be dumped into a Dictionary<string,object> (hmmm…not so easy). So the resulting object would look like: Mapped mappedObj = { One = 1; Two = 2; TheRest = [{three=3}, {four=4}, {blah=100}]'; } I’ve read about custom JSON.NET converters, but had never written one. So I decided to give it a shot and discovered that it’s really not too bad. Here’s my sample code: using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Reflection; namespace JsonConverterTest1 { public class Mapped { private Dictionary<string, object> _theRest = new Dictionary<string, object>(); public int One { get; set; } public int Two { get; set; } public Dictionary<string, object> TheRest { get { return _theRest; } } } public class MappedConverter : CustomCreationConverter<Mapped> { public override Mapped Create(Type objectType) { return new Mapped(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var mappedObj = new Mapped(); //get an array of the object's props so I can check if the JSON prop s/b mapped to it var objProps = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray(); //loop through my JSON string while (reader.Read()) { //if I'm at a property... if (reader.TokenType == JsonToken.PropertyName) { //convert the property to lower case string readerValue = reader.Value.ToString().ToLower(); if (reader.Read()) //read in the prop value { //is this a mapped prop? if (objProps.Contains(readerValue)) { //get the property info and set the Mapped object's property value PropertyInfo pi = mappedObj.GetType().GetProperty(readerValue, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); var convertedValue = Convert.ChangeType(reader.Value, pi.PropertyType); pi.SetValue(mappedObj, convertedValue, null); } else { //otherwise, stuff it into the Dictionary mappedObj.TheRest.Add(readerValue, reader.Value); } } } } return mappedObj; } } public class Program { static void Main(string[] args) { //a sample JSON string to deserialize string json = "{'one':1, 'two':2, 'three':3, 'four':4}"; //call DeserializeObject, passing in my custom converter Mapped mappedObj = JsonConvert.DeserializeObject<Mapped>(json, new MappedConverter()); //output some of the properties that were stuffed into the Dictionary Console.WriteLine(mappedObj.TheRest["three"].ToString()); Console.WriteLine(mappedObj.TheRest["four"].ToString()); } } } It’s pretty simple to create a custom converter and it’s almost limitless as to what you can do with it. Of course, my sample code above is pretty simple and doesn’t take into account arrays or nested objects in the JSON string; but, that can be accounted for by using the JsonToken enumeration (which I do above in detecting a property) and checking for the start of a nested object or an array. I found this an interesting exercise and gave me an opportunity to take a tour of a feature in JSON.NET that I’ve read about but never used. I hope you find it interesting. One. RSS ATOM © David Hoerster Theme by PiyoDesign. Valid XHTML & CSS.
http://geekswithblogs.net/DavidHoerster/Default.aspx
CC-MAIN-2014-10
refinedweb
2,159
63.59
Talk:Wiki/Archive01 Contents - 1 update the mediawiki code - 2 Favicon - 3 Sub pages - 4 SVG support - 5 $wgSpamRegex blocking all divs - 6 CSS for source code - 7 Allow use of images from wikimedia commons - 8 Wiki Search. Install a search plugin? - 9 enabling email notifications - 10 ConfirmEdit Spam Captcha - 11 multilingual name spaces update the mediawiki code Its currently 1.4.14, update to latest (currently 1.6.7) -now on 1.8</s> - ...but at the current time we are now on 1.9 (Special:Version) but keeping up with latest MediaWiki code is an ongoing admin task I guess. -- Harry Wood 11:25, 17 October 2007 (BST) Favicon Put a favicon on the mediawiki [1] Sub pages Allow sub pages in the main namespace ( $wgNamespacesWithSubpages[NS_MAIN] = true;) - DONE - Added by Steve --Dean Earley 10:01, 11 Jul 2006 (UTC) SVG support SVG support to the wiki as requested by Frankie It would allow SVG files to be uploaded, and then either pre-rendered by a server-side library, or displayed inline on the page. Details on the MediaWiki support are here: $wgSpamRegex blocking all divs The wiki spam regex $wgSpamRegex is set to block any use of <div>s in the wiki. In fact the setting we have at the current time is just: $wgSpamRegex = "/<div/"; (User:TomH tells me) This gets in the way of various legit div usage. You can get around it. Some people figured out that <di<!-- -->v> works in most cases. However you can even just write <DIV> in upper case to get around it! It's a pain to make people figure this out. e.g. templates which work on wikipedia don't work here, unless you know this trick. The main thing to block against spamwise is dubious use of the overflow style within divs. May as well just paste in this large example which includes protection against this "CSS hidden spam", as well as several other anti-spam tricks. Spam isn't a big problem on this wiki (as mentioned above) -- Harry Wood 10:33, 26 February 2008 (UTC) CSS for source code There's a nice style applied to source code snippeds inside pre tags. But i didn't find a way to combine it with the source tags. Is it possible to set the CSS of the source tags to the same as the pre tags? For example, here i had to set the XML code snippets into divs with CSS attributes to make them appear in that nice gray box. --Florianschmitt 21:31, 6 September 2008 (UTC) - Syntax highlighting is done by this wiki extension which we have installed : - I just took a look at the usage examples. I notice the rendered HTML on that site comes out with <pre> tags, which is different to the way it is behaving here. And it is the CSS for <pre> tags which gives the grey dotty box style. So I imagine we might fix this if we were to re-install a later version of the extension (I'm guessing that will cause it to always wrap the code snippet in a pre tag) Might be a better solution than trying to devise a css rule for the current output. -- Harry Wood 20:19, 7 September 2008 (UTC) - You may use de:Code im Wiki darstellen. --Markus 00:21, 26 September 2008 (UTC) - Is there still an issue with the extension? The latest stable version is installed. -- Firefishy 09:52, 26 September 2008 (UTC) The issue Florian pointed out is that XML source such as the following... <!-- my comment --> <xmlroot> <myelement myattribute="Hello">World</myelement> </xmlroot > ...is not getting a grey dotty box around it. This is because our extension is not spitting out a pre tag around the output for some reason. Strangely on mediawiki.org it does. Thought it must be a later version. Hardly a major priority though :-) -- Harry Wood 13:07, 29 September 2008 (UTC) Allow use of images from wikimedia commons There's a suggested config change over at Talk:Collaboration with Wikipedia#Usage of Wikimedia Commons, which I guess would make sense. Newly available in the v1.13, it allows us to use images from wikimedia commons, and fetches description pages automatically. -- Harry Wood 12:09, 23 September 2008 (UTC) - I support this suggest. --Kolossos 17:47, 23 September 2008 (UTC) - I support this suggest. --John07 19:14, 23 September 2008 (UTC) - Yes Harry, it promise a lot of simlplification. --Markus 17:21, 27 September 2008 (UTC) - This would be awesome, enable! --Ævar Arnfjörð Bjarmason 12:37, 29 September 2008 (UTC) - [[Image:SomeImageOnCommons.jpg]] automagically gets linked, local caching is optional. --Firefishy 14:52, 29 September 2008 (UTC) - If I look on pages like Dresdner_Heide,I would say that it is useful for both projects. There are also images for city-districts[2] on commons which could be interesting for both projects. - Commons is stable enough so that the depency should be no problem. Ok there will be problems if an image will delete on commons (i.e. if the copyrights are not ok), but this also protects OSM against legal problems. And the solution doesn't mean that all images need to be saved on commons. - Commons-example-image: - --Kolossos 18:09, 29 September 2008 (UTC) Couple of reasons why we might not want this: - It means we're reliant on Wikimedia Commons. If those servers are offline or slow, then our wiki is adversely affected - It serves to make this wiki look more like wikipedia. - This wiki is not wikipedia. Some people seem to expect the same rules to apply and the same super-keenness on, for example, decisions by voting. Anything which makes this seem more like wikipedia might worsen this problem. - As a more concrete objection though, we actually have more strict rules (or community acceptance tendencies) regarding copyright free sources of maps/map data. For example wikimedia commons has a map of london boroughs. While it might be useful for us to place this on our wiki for coordinating mapping, we don't do that because we want to encourage people to build borough boundaries data without copying, hence our best equivalent is Image:London-borough-boundaries.png ...just playing devil's advocate though really. I personally don't object strongly to the idea. Then again I don't really see why so many people seem to think it will be wonderfully useful! -- Harry Wood 12:48, 1 December 2008 (UTC) - Things have moved on: Collaboration_with_Wikipedia. Wikipedians are not concerned to work with OSM at least. --Malenki 12:18, 16 April 2009 (UTC) - Hi Harry! we have thousands of pictures in Commons. When we can use it without copying to our Wiki, and without clearing all the copyright-stuff - it will be a very simple way to use more pictures in our Wiki! --Markus 23:09, 8 December 2008 (UTC) Hi Harry, did you add the code to the localSettings.php? How it works to link pictures from commons? --Markus 00:08, 28 January 2009 (UTC) - No, this has not been enabled. I personally do not like it. How long does it really take to upload a file from Wikicommons and add attribution? 30 seconds? Do we really want to "pollute" our namespace with everything in Wikicommons? I am happy to change my mind if there is a real debate, as requested earlier. -- Firefishy 00:54, 28 January 2009 (UTC) - If the images are to be properly categorized and licensed (sometimes requires version history, author(s) ...) and so on, I guess it takes at least three minutes -- which is 170 seconds too much, as documenting stuff in the wiki has to be as quick and easy as possible to ensure that people actually bother to do it. There is another problem with importing images to our wiki: Finding those images. Images on commons are easy to find, because Wikipedia articles use them, because they are usally well categorized etc. So people likely will not use our wiki to find illustrations, which will probably result in duplicates. Last but not least, images on Commons often have helpful captions in multiple languages, information about time and place of creation etc. Copying this information requires additional effort, and it will not be updated automatically when e.g. the caption is translated to additional languages on Commons. --Tordanik 11:11, 28 January 2009 (UTC) Personally, I really like the idea - it's pretty easy to add and should not cause any performance problems. While I do see possible downsides, I for myself think the positive aspects outweight them. --Avatar 06:55, 30 January 2009 (UTC) - +1 from me. --seav 09:06, 30 January 2009 (UTC) - +1 from me. Would save a lot of work --Malenki 12:18, 16 April 2009 (UTC) Hmmm "pulluting" the wiki namespace, is another downside I hadn't really thought of. What happens when a locally uploaded image has the same name as a remote image? -- Harry Wood 11:05, 30 January 2009 (UTC) - I would appreciate it if someone could test Wikimedia Commons Foreign Repos on a test wiki of theirs. Particular cases: 1) Existing same name in OSM wiki and WM Commons. 2) Upload to OSM wiki with a name that exists on WM Commons. 3) Resolving existing? conflicts. 4) Difficult one, performance impact. 5) Possibility of using a special namespace for the Wikimedia Commons items. WMC:Image:xxx unlikely, but worth a look. 6) Other?. -- Firefishy 12:13, 30 January 2009 (UTC) - First of all: Wikimedia Commons is a shared file repositorium for all, not for Wikipedia/Wikimedia projects alone. IMO it does not make sense to duplicate content it if could be used from Commons. Now your questions: - 1. The local file has priority over a file from a shared repo. Always. Same behaviour as in Wikipedia. - 2. See 1. At time of upload to OSM wiki this local file will become priority. - 3. I do not understand the question. Which conflicts? - 4. No performance impact for OSM wiki. And the Commons servers are fast enough to handle the requests of OSM wiki. And they have a lot of space: actual upgraded to 24 TB in total (5 TB used) - 5. As far as I know not possible. - You can test the function on , an independent wiki used for localization of MediaWiki, i.e.. (to clarify: I am MediaWiki developer, Wikimedia Commons sysop and Translatewiki server admin) Raymond de 15:37, 31 January 2009 (UTC) Please can somebody implement this? Thanks a lot! --Markus 07:00, 3 April 2009 (UTC) - BTW: It's not in "Test" anymore, but already in the stable. So the right version of Mediawiki and PHP is here already. All neccesary is some additional lines in the LocalSettings.php. See ---jha- 12:04, 3 April 2009 (UTC) ENABLED! - If it causes problem we will have to rethink. - Firefishy 18:08, 16 April 2009 (UTC) - Cool. I must say I was always tempted to ignore this request until somebody actually came up with some concrete examples for why it will be so useful. Kolossos is the only one who has given an example above, and that example is to bring in potentially derived map images! ([3]) - Please do not use this new feature to bring in map images, unless they meet the OpenStreetMap community's strict criteria for 'free' maps. Anything showing administrative boundaries is probably not strictly free, since it will have been created by copying off copyrighted maps (I'm not saying the wikimedia community is wrong in labelling it as a free image, just that we at OpenStreetMap do not like to derive our data from anything like this) - Of course that is not an issue with this new feature as such, but something to be very aware of if you were planning on going on a commons importing rampage. I can think of examples where this new feature will be useful. e.g. I just decorated Tag:shop=garden_centre by doing a quick search on commons. - -- Harry Wood 18:28, 16 April 2009 (UTC) - I want to say thank you, too (and agein :) ). The first page I used this new feature: DE:Tag:historic=castle --Malenki 19:05, 16 April 2009 (UTC) Interesting little problem related to this. If look at the old version of Key:crossing examples, before I fixed it, it's picking up on images from commons, where there used to be 'red link' stub references to non-existent images before. In these cases it might happen upon an image which is relevant, but in the case of Lollipop.jpg it might not be! Easy enough to fix over time though, so if you see a seemingly random irrelevant image on the wiki anywhere, this might be the cause. -- Harry Wood 14:09, 25 April 2009 (UTC) Wiki Search. Install a search plugin? In Steve's old mailing list post he suggested a wiki cleanup was needed, which cannot be denied, but he also seemed to be particularly peeved by failure to find things. This could partly be blamed on the search function itself. MediaWiki search stinks or at list it's a bit hit and miss. This comes to my attention every now and then, usually in cases where I can easily create a new handy redirect to remedy the situation for that keyword. But that's not solving the search problem overall. I've no idea why a search for 'Getting' turns up nothing. Getting The Source, Getting Involved, Getting Data, hello??. Sometimes search results come in a funny order, seemingly based partly on the order pages were created or something. Sometimes I just wish I could do more powerful google style text searches. So... The recommendation seems to be to install Lucene or Spinx plugins. -- Harry Wood 14:59, 14 May 2009 (UTC) - User:Firefishy has ENABLED lucene search plugin. - That was quick! - Working much better: search for 'Getting' - Kick ass! - -- Harry Wood 17:03, 14 May 2009 (UTC) enabling email notifications hi. i wanted to argue about enabling of e-mail notification functionality whenever somebody edits a page on user's watchlist. on wikipedia it was disabled for a long time because they cited performance concerns. if that is also the reason for osm wiki, i have some suggestions :) ;) at first i assumed that this functionality is enabled, thus i left comments on talk pages and wondered why nobody responded... so i'd like to propose enabling of this feature. and, after all, even wikipedia enabled it... --Richlv 15:11, 3 July 2009 (UTC) ConfirmEdit Spam Captcha The ConfirmEdit extension is now installed (See Special:Version) however it probably should be ugraded to a later version. The reason I say this is... I've tried to define a whitelist at MediaWiki:Captcha-addurl-whitelist. This should get picked up by the extension, meaning that we no longer get prompted when linking to openstreetmap.org URLs. This isn't happening, and my hunch is that this whitelist feature was only added to the extension code recently, so we dont have it, until a System Administrator downloads the files (two files linked here) and plonks them on to overwrite the existing ones in extensions/ConfirmEdit directory on the wiki server. -- Harry Wood 12:15, 9 January 2008 (UTC) - This feature was added to the Extension:ConfirmEdit SVN Revision @ 23122. Syntax is as follows: # * Everything from a "#" character to the end of the line is a comment # * Every non-blank line is a regex fragment which will only match hosts inside URLs -- Firefishy 16:06, 9 January 2008 (UTC) Thanks both for your help in sorting this! --Richard 17:24, 9 January 2008 (UTC) TomH did the heavy lifting. Can we Captcha-addurl-whitelist, informationfreeway.org, openstreetmap.nl, openstreetmap.de and opengeodata.org Namespace 'RU' Hi! Is it possible to create a namespace "RU"? There is certain amount of pages in Russian language already. (including Ru:Main_Page) -- Zkir 13:02, 14 April 2009 (UTC) - +1 -- Hind 20:50, 21 July 2009 (UTC) - Please add Russian namespace --vvoovv 21:35, 21 July 2009 (UTC) multilingual name spaces Language Namespaces have been implemented. Currently only: DE, FR, ES, IT and NL. Others at a later stage. Some template linking needs fixing. -- Firefishy 03:06, 3 October 2008 (UTC) - Could you briefly explain how to fix the template issue ? For instance, I cannot find the way to fix FR:About calling the template Template:Fr:HelpMenu. Pieren 15:55, 3 October 2008 (UTC) Language Namespaces are now also included in the search results for anonymous and users who have not set their search preferences. - Firefishy 03:09, 10 October 2008 (UTC) - Since the implementation of the namespaces many talk pages can't be reached using the tabs at the top anymore, probably because they have a different name (De instead of DE). Maybe someone knows how to fix this. --Driver2 00:36, 12 October 2008 (UTC)
http://wiki.openstreetmap.org/wiki/Talk:Wiki/Archive01
CC-MAIN-2017-04
refinedweb
2,831
64
Multithreading in java is a process that allows executions of multiple threads in java. It helps in the maximum utilization of the CPU. We call each part of the program as a thread so multithreading helps in the executions of multiple parts of a program at a single time. Multithreading helps to create small multiple tasks in the application where we can subdivide the operations into single threads and perform the tasks. Read Top Core Java interview questions The cycle of the thread works in the following manner: New thread() ->New -> Runnable -> Running -> Waiting -> Dead New thread() ->New -> Dead Description is as follows: New: When a new state of the cycle is formed, the new life of the thread begins. Runnable: we put a thread in the category of runnable when a new thread starts to perform action. Waiting: when a thread is already performing a task, the other thread is kept on hold or wait. Once the previous thread finishes its task, the new thread comes into play. Dead: we call a thread dead or in terminated state when it completes its task. More Recommended Post Types of Multithreading There are mainly two types of threads in Java which can perform multithreading in the program. They are user thread and daemon thread. - User thread: When we start an application, the first thread which is created is called the user thread. A program can never terminate unless the user thread present in the main() terminates. - Daemon thread: This type of thread in the application provides services for user threads. It has no life of its own and it is completely dependable on user threads for survival. Hence, it is not a high priority thread as compared to user thread. They are mostly used for extra background tasks in the application. The methods in this thread are void setDaemon() which marks the current thread as a daemon thread. Another method is isDaemon() which can be used by the user to check if the thread is Daemon or not. We can create threads for multithreading using 2 criteria, they are: - Extending the Thread class: We can create this extension in java.lang.Thread class. There’s a run method in the tread class that gets overridden during this extension process. We create a new object for a class and start() method is used to start the execution of that thread. - By implementing a run-able environment: when we extend the runnable class, it can extend other base classes. It doesn’t support inbuilt functions such as interrupt(), yield() etc. The program will simply terminate the daemon thread if the user thread is no longer in use. This is because the sole purpose of a daemon thread is to provide support for the tasks of user thread. Hence, JVM saves the space by demolishing the daemon thread when there is no user thread. Thread Class Methods - getName(): this method helps in getting the name of the thread. - getPriority(): This will get the priority of the thread. - join(): this method will help a thread to end its execution or simply terminate. - run(): a thread starts its process using run() method. - sleep(): the thread terminates its execution completely using sleep(). - isAlive(): this method is used to check if the thread is still in the execution state or if it is still running. Below is a program to understand how multithreading in Java works: package Test; public class DeveloperHelps implements Runnable { public static void main(String[] args) { Thread T1 = new Thread("Thread 1 works"); Thread T2 = new Thread("Thread 2 works"); T1.start(); T2.start(); System.out.println("Thread names are following:"); System.out.println(T1.getName()); System.out.println(T2.getName()); } @Override public void run() { } } The output of the above program will be: The names of the threads are: Thread 1 works Thread 2 works We have some advantages of multithreading: - While performing multithreading, users cannot be blocked. Threads are independent and as a result, we can perform multiple operations during one time. - If one thread stops or meets an exception, the other threads do not get affected. They can keep performing their respective tasks. - Multithreading helps in promoting better CPU utilization. - A user can design better and responsive programs due to the multithreading process in Java. - The process of multithreading helps in the fair distribution of CPU resources.
https://www.developerhelps.com/multithreading-in-java/
CC-MAIN-2021-31
refinedweb
724
62.98
Re: can't rename projects From: Dale Howard [MVP] ("Dale) Date: 02/03/04 - ] Date: Tue, 3 Feb 2004 08:39:01 -0700 Michael -- At least some of your problems are caused by the fact that you are expecting your people to use an .mpp file as an enterprise template. You should import that particular .mpp as an enterprise template using Tools - Enterprise Options - Import Project to Enterprise. On the first step of the wizard, you can select "Template" as the file type. Also, if that .mpp file contains macros, you should copy the modules into the Enterprise Global file for distribution to all project managers in your system. To change the name on Row 0, click File - Properties and change the Title. Hope a couple of answers help. -- Dale A. Howard [MVP] Enterprise Project Trainer/Consultant "We wrote the book on Project Server" "Michael" <anonymous@discussions.microsoft.com> wrote in message news:924101c3ea2f$b12d89e0$a501280a@phx.gbl... > > message > > > > > > >. > > - ]
http://www.tech-archive.net/Archive/Project/microsoft.public.project.pro_and_server/2004-02/0091.html
crawl-002
refinedweb
159
75
In this post, you’ll learn how to use Python to remove a character from a string. You’ll learn how to do this with the Python .replace() method as well as the Python .translate() method. Finally, you’ll learn how to limit how many characters get removed (say, if you only wanted to remove the first x number of instances of a character). The Quick Answer: Use string.replace() Why Remove Characters from Strings in Python? When you download data from different sources you’ll often receive very messy data. Much of your time will be spent cleaning that data and prepping it for analysis. Part of that data preparation will be cleaning your string and may involve removing certain characters. Because of this being a very common challenge, this tutorial was developed to help you in your journey towards easier data analysis! Let’s get started! Use the Replace Function to Remove Characters from a String in Python Python comes built-in with a number of string methods. One of these methods is the .replace() method that, well, lets you replace parts of your string. Let’s take a quick look at how the method is written: str.replace(old, new, count) When you append a .replace() to a string, you identify the following parameters: old=: the string that you want to replace, new=: the string you want to replace with, and count=: the number of replacements you want to make Now that you’ve learned how the .replace() method is written in Python, let’s take a look at an example. You’ll be given a string and will want to remove all of the ? mark characters in the string: old_string = 'h?ello, m?y? name? is ?nik!' new_string = old_string.replace('?', '') print(new_string) # Returns: hello, my name is nik! Let’s take a look at what we’ve done here to remove characters from a string in Python: - We applied the . replace()method to our string, old_string - We indicated we wanted to replace the ?character with an empty string - We assigned this newly modified string to the variable new_string You can see here, just how easy it is to remove characters from a string in Python! Now let’s learn how to use the Python string .translate() method to do just this. Use the Translate Function to Remove Characters from a String in Python Similar to the example above, we can use the Python string .translate() method to remove characters from a string. This method is a bit more complicated and, generally, the .replace() method is the preferred approach. The reason for this is that you need to define a translation table prior to actually being able to replace anything. Since this step can often be overkill and tedious for replacing only a single character. Because of this, we can use the ord() function to get a characters unicode value to simplify this process. Let’s see how this can be done with the same example as above: old_string = 'h?ello, m?y? name? is ?nik!' new_string = old_string.translate({ord('?'):None}) print(new_string) # Returns: hello, my name is nik! Let’s explore what we’ve done here: - We use the ord()function to return the unicode value for whatever character we want to replace - We map this to a Nonevalue to make sure it removes it You can see here that this is a bit more cumbersome than the previous method you learned. Remove Only n Number of Characters from a String in Python There may be some times that you want to only remove a certain number of characters from a string in Python. Thankfully, the Python .replace() method allows us to easily do this using the count= parameter. By passing in a non-zero number into this parameter we can specify how many characters we want to remove in Python. This can be very helpful when you receive string where you only need to remove the first iteration of a character, but others may be valid. Let’s take a look at an example: old_string = 'h?ello, my name is nik! how are you?' new_string = old_string.replace('?', '', 1) print(new_string) # Returns: hello, my name is nik! how are you? We can see here that by passing in count=1, that only the very first replacement was made. Because of this, we were able to remove only one character in our Python string. Remove Multiple Characters from a String in Python There may also be times that you want to replace multiple different characters from a string in Python. While you could simply chain the method, this is unnecessarily repetitive and is difficult to read. Let’s take a look at how we can iterate over a string of different characters to remove those characters from a string in Python. The reason we don’t need to loop over a list of strings, is that strings themselves are iterable. We could pass in a list of characters, but we don’t need to. Let’s take a look at an example where we want to replace both the ? and the ! characters from our original string: a_string = 'h?ello, my name is nik! how are you?' for character in '!?': a_string = a_string.replace(character, '') print(a_string) # hello, my name is nik how are you One thing you’ll notice here is that we are replacing the string with itself. If we didn’t do this (and, rather, replaced the string and assigned it to another variable), we’d end up only replacing a single character in the end. We can also accomplish this using the regular expression library re. We can pass in a group of characters to remove and replace them with a blank string. Let’s take a look at how we can do this: import re old_string = 'h?ello, my name is nik! how are you?' new_string = re.sub('[!?]', '', old_string) print(new_string) # Returns: hello, my name is nik how are you What we’ve done here is pass in a string that contains a character class, meaning it’ll take any character contained within the square brackets []. The re library makes it easy to pass in a number of different characters you want to replace and removes the need to run a for loop. This can be more efficient as the length of your string grows. Conclusion In this post, you learned how to remove characters from a string in Python using the string .replace() method, the string .translate() method, as well as using regular expression in re. To learn more about the regular expression .sub() method, check out the official documentation here. Hey, Nik! There are two tiny mistakes in the penultimate section of code on this page: The output of this code section (last line) should NOT contain characters of a question mark & of an exclamation point: a_string = ‘h?ello, my name is nik! how are you?’ for character in ‘!?’: a_string = a_string.replace(character, ”) print(a_string) # a_string: hello, my name is nik! how are you? PS Btw thanks for your content: the articles are great, explanations are clear. Keep going! Hi Dmitry, Thanks so much for catching that! I’ve updated the article. Thank you also for your feedback! It means a lot to me! 🙂
https://datagy.io/python-remove-character-from-string/
CC-MAIN-2022-27
refinedweb
1,212
74.49
[ ] Henri Yandell closed CLI-151. ----------------------------- Resolution: Fixed I've sat and looked at the code fresh, and I agree with the 0 as a fix here. Digging into the new failing test, I think the errors are in other code - so closing this out again. > HelpFormatter wraps incorrectly on every line beyond the first > -------------------------------------------------------------- > > Key: CLI-151 > URL: > Project: Commons CLI > Issue Type: Bug > Components: Help formatter > Reporter: Dan Armbrust > Fix For: 1.2 > > Attachments: fix-wrapping.patch > > > The method findWrapPos(...) in the HelpFormatter is a couple of bugs in the way that it deals with the "startPos" variable. This causes it to format every line beyond the first line by "startPos" to many characters, beyond the specified width. > To see this, create an option with a long description, and then use the help formatter to print it. The first line will be the correct length. The 2nd, 3rd, etc lines will all be too long. > I don't have a patch (sorry) - but here is a corrected version of the method. > I fixed it in two places - both were using "width + startPos" when they should have been using width. > {code} > protected int findWrapPos(String text, int width, int startPos) > { > int pos = -1; > // the line ends before the max wrap pos or a new line char found > if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width) > || ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width)) > { > return pos+1; > } > else if ((width) >= text.length()) > { > return -1; > } > // look for the last whitespace character before startPos+width > pos = width; > char c; > while ((pos >= startPos) && ((c = text.charAt(pos)) != ' ') > && (c != '\n') && (c != '\r')) > { > --pos; > } > // if we found it - just return > if (pos > startPos) > { > return pos; > } > > // must look for the first whitespace chearacter after startPos > // + width > pos = startPos + width; > while ((pos <= text.length()) && ((c = text.charAt(pos)) != ' ') > && (c != '\n') && (c != '\r')) > { > ++pos; > } > return (pos == text.length()) ? (-1) : pos; > } > {code} -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online.
http://mail-archives.apache.org/mod_mbox/commons-issues/200902.mbox/%3C744822415.1234934462131.JavaMail.jira@brutus%3E
CC-MAIN-2019-09
refinedweb
334
73.98
Wifi RSSI and mqtt subscribe I'm trying to change the RGB led through a simple subscribe and callback but it doesn't seem to be processing the subscribed message. I also wanted to publish the current signal strength at boot - is there a way to do this, even if its from a scan before wifi connect? Any ideas? Here is my main.py so far: from mqtt import MQTTClient from machine import Pin import machine import time from network import WLAN import pycom pycom.heartbeat(False) def trig_reset(arg): machine.reset() def sub_cb(topic, msg): print(msg) wlan = WLAN(mode=WLAN.STA) wlan.connect("SSID_Name", auth=(WLAN.WPA2, "wifipass"), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to Wifi\n") wifiaddress = ((str(wlan.ifconfig()[:1]))[2:])[:-3] client = MQTTClient("LoPy", "192.168.1.15",user="username", password="pass", port=1883) client.connect() client.set_callback(sub_cb) client.subscribe(topic="lopy/rgb") client.publish(topic="lopy/ip", msg=wifiaddress) button = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP) button.callback(Pin.IRQ_RISING, trig_reset) @this.wiederkehr Thanks, I will try that later tonight. - this.wiederkehr last edited by You have to call either client.wait_msg()or client.check_msg()in order to receive messages. The former is blocking whereas the latter is non blocking and has therefore to be called in a loop. See the comments on the mentioned methods in the following file:
https://forum.pycom.io/topic/1713/wifi-rssi-and-mqtt-subscribe
CC-MAIN-2019-13
refinedweb
233
52.66
In C# stack is a first-in, last-out data structure with methods to push an item onto the top of the stack and pop an item from the top of the stack and examine the item at the top of the stack without removing it. The stack maintains a last-in, first-out (LIFO) order. This means that the first item you add is the last item to be popped (removed from the stack). on the stack the first one to be removed. (The dish at the bottom is rarely used and will inevitably require washing before you can put any food on it—because it will be covered in grime!) Stack allows Null values and we can have duplicate vaues, to declare a stack in C#, you have following code Stack MyStack = new Stack(); As elements are added to a Stack, the capacity is automatically increased as required through reallocation. Commonly used methods in stack are: MyStack.Push(5); MyStack.Push(1); MyStack.Push(2);? MyStack.Pop(); //removes the top object from stack? MyStack.Contains(5)? MyStack.Peek(); // return the top element of stack? using System; using System.Collections; public class Program { public static void Main() { Stack MyStack = new Stack(); MyStack.Push(5); MyStack.Push(1); MyStack.Push(2); //last item to be pushed on stack ( means at top) //print stack using foreach loop Console.WriteLine("Stack After Pushing items:"); PrintStack(MyStack); Console.WriteLine(); //remove item from stack MyStack.Pop(); //now check stack again Console.WriteLine("Stack After pop: "); PrintStack(MyStack); Console.WriteLine(); //check if element exists using .Contains Console.WriteLine("5 Exists in Stack? : "+MyStack.Contains(5)); Console.WriteLine(); //check top item using Peek method Console.WriteLine("Top Item of stack is : "+MyStack.Peek()); } //print stack method public static void PrintStack(Stack MyStack) { foreach(var item in MyStack) { Console.WriteLine(item); } } } Output: Stack After Pushing items: 2 1 5 Stack After pop: 1 5 5 Exists in Stack? : True Top Item of stack is : 1
https://qawithexperts.com/tutorial/c-sharp/39/c-sharp-stack-with-example
CC-MAIN-2021-39
refinedweb
328
67.35
#include <essence.h> Inheritance diagram for GCReader: Set the default read handler. This handler receives all KLVs without a specific data handler assigned including KLVs that do not appear to be standard GC KLVs. If not default handler is set KLVs with no specific handler will be discarded. Set the filler handler. If no filler handler is set all filler KLVs are discarded Set encryption handler. This handler will receive all encrypted KLVs and after decrypting them will resubmit the decrypted version for handling using function HandleData() Set data handler for a given track number. Read from file - and specify a start location. All KLVs are dispatched to handlers Stops reading at the next partition pack unless SingleKLV is true when only one KLV is dispatched Read from file - continuing from a previous read. All KLVs are dispatched to handlers Stops reading at the next partition pack unless SingleKLV is true when only one KLV is dispatched Set the offset of the start of the next KLV within this GC stream. Generally this will only be called as a result of parsing a partition pack Stop reading even though there appears to be valid data remaining. This function can be called from a handler if it detects that the current KLV is either the last KLV in partition, or does not belong in this partition at all. If the KLV belongs to another partition, or handling should be deferred for some reason, PushBackKLV can be set to true Get the offset of the start of the current KLV within this GC stream. File from which to read. The offset of the start of the current (or next) KLV within the file. Current KLV during HandleData() and next at other times. The offset of the start of the current KLV within the data stream. True if no more KLVs should be read - set by StopReading() and ReadFromFile() with SingleKLV=true. True if StopReading() called while processing the current KLV. True if StopReading() called with PushBackKLV = true. The default handler to receive all KLVs without a specific handler. The hanlder to receive all filler KLVs. The hanlder to receive all encrypted KLVs. Map of read handlers indexed by track number.
http://freemxf.org/mxflib-docs/mxflib-1.0.0-docs/classmxflib_1_1_g_c_reader.html
CC-MAIN-2018-05
refinedweb
368
63.8
[Share] a list of rects distributed around 360 degrees This share is basically for people like me , when they hear circle they think of crop circles not pi. My point being, if you know the math, this share is useless to you. But it's just about the distribution of rects on a circular path. Personally I think it would be nice if someone could rewrite the function properly and add it to the Pythonista Tools lib. But I was able to put this together by taking parts of the AnalogClock.py example that comes with Pythonista. ''' Pythonista Forum - @Phuket2 ''' import ui, editor from math import pi, sin, cos def rects_on_circle_path(rect_path, obj_width, margin = 2, num_objs = 12): ''' rects_on_circle_path PARAMS: 1. rect_path = the bounding rect of the circle **Note the rect is inseted half of the shape_width param + the margin param. the resulting rects are centered on the bounding circle. 2. obj_width = the width of the shape/rect you are placing on the path. 3. margin = 2 , additionally insets the rect_path by this value 4. num_objects = 12. the number of objects to distribute around rect_path. set to 12 as default, a clock face. odd and even numbers are ok. RETURNS: tuple(Rect, list) 1. Rect = the adjusted rect_path after transformations in the func. 2. a list[] containing a ui.Rect's. the length of the list is equal to the num_objs param. NOTES: For some reason i can't do the math if my life depended on it. I copied the math from the AnalogClock.py pythonista example. ALSO should have a param to shift the basline of the rects, off the center line of the rect_path. the reason why i return a list of rects in the tuple is for flexibility. in the example, just drawing. but could just as easily be positioning ui.Button/ui.Label object or whatever. oh, btw i know its a bit of a mess. hard when you are not sure of the math to get it as concise as it should be. ''' rects = [] r = ui.Rect(*rect_path).inset((obj_width/2) + margin, (obj_width/2) + margin) radius = r.width / 2 for i in range(0, num_objs): a = 2 * pi * (i+1)/num_objs pos = (sin(a)*(radius*1), cos(a)*(radius*1)) r1 = ui.Rect(pos[0] , pos[1] , obj_width, obj_width) r1.x += ((r.width/2) - (obj_width/2)+r.x) r1.y += ((r.height/2) - (obj_width/2)+r.y) rects.append(r1) return (r,rects) class MyClass(ui.View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def draw(self): r = ui.Rect(*self.bounds) r, rects = rects_on_circle_path(r, 10, margin = 20 , num_objs = 36 ) s = ui.Path.oval(*r) ui.set_color('lime') s.stroke() ui.set_color('orange') for r in rects: s = ui.Path.oval(*r) s.fill() r = ui.Rect(*self.bounds) r, rects = rects_on_circle_path(r, 15, margin = 40 , num_objs = 12 ) s = ui.Path.oval(*r) ui.set_color('yellow') s.stroke() ui.set_color('purple') for r in rects: s = ui.Path.oval(*r) s.fill() r = ui.Rect(*self.bounds) r, rects = rects_on_circle_path(r, 25, margin = 80 , num_objs = 6 ) s = ui.Path.oval(*r) ui.set_color('orange') s.stroke() ui.set_color('lime') for r in rects: s = ui.Path.rect(*r) s.fill() if __name__ == '__main__': _use_theme = True w, h = 600, 600 f = (0, 0, w, h) name = 'Silly Demo' mc = MyClass(frame=f, bg_color='white', name = name) if not _use_theme: mc.present('sheet', animated=False) else: editor.present_themed(mc, theme_name='Oceanic', style='sheet', animated=False) Output @cvp , thanks the below code is working now. I can't be sure everything I reported above was correct. Is possible I had some mis matched Params 😂 I still the the code below is cool. That one function just makes it so easy to put/draw objects in a circular shape, many interfaces could require this....well maybe. I just wanted to get that function working, I didn't try to make the class generic. Maybe I am dreaming. But thanks again for your help and diagrams. I was still 14 when I left school and I was a trouble maker. So, it's difficult to understand your diagrams, just because I have no real foundation. I was also looking at wiki for radians, it has some great diagrams and animations, hmmm but still it doesn't sink in. But I am going to try to find a math tutor. But it will not be easy in Thailand. We're I live and language barrier. But again thanks.... ''' Pythonista Forum - @Phuket2 ''' import calendar import editor import math import ui # example, playing around, for 12 items its ok no math :) _range_12 = (.3, .34, .38, .42, .46, .5, .55, .6, .63, .7, .85, 1.0))] def make_button(idx, title): def button_action(sender): print('Button {} was pressed.'.format(sender.title)) #btn = ui.Button(title=calendar.month_abbr[i+1]) btn = ui.Button' ] #_list=['N', 'E' , 'S' , 'W'] #_list=['1st', '2nd', '3rd', '4th', '5th'] #_list=['0', '90', '180', '270' ] #_list= [str(d) for d in range(0, 12)] _list = [calendar.month_abbr[i] for i in range(1,12)] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cir_rect = None self.make_view() def make_view(self): for i in range(len(self._list)): self.add_subview(make_button(i, title=self._list[i])) def layout(self): r, rects = rects_on_circle_path(self.bounds, obj_width=70, margin=20, num_objs=len(self._list)) self.cir_rect = r for i, btn in enumerate(self.subviews): btn.frame = rects[i] btn.title = self._list[i] btn.corner_radius = btn.width / 2 def draw(self): s = ui.Path.oval(*self.cir_rect) with ui.GState(): ui.set_color(css_clr_to_rgba('lime', .4)) s.line_width = 1 s.stroke() if __name__ == '__main__': _use_theme = True w = h = 500 f = (0, 0, w, h) mc = MyClass(frame=f, bg_color='white', name='Silly Demo') if not _use_theme: mc.present('sheet', animated=False) else: editor.present_themed(mc, theme_name='Solarized Dark', style='sheet', animated=False) You're welcome for any mathematic/geometric question, but only if you accept an answer in a very poor English 🙄 @Phuket2 I have implemented the circulartextlayout module to support circular layout. It is a slight modification of the textlayout module. Now the rows in layout text represents circular rings. Columns represent angular positions (Columns are not used for size calculations . Only rows are used for size calculations.) I hope it is useful. There is no need to calculate positions and size. The following git repository contains the code and examples: You can do a git pull if you have already got this. In the following example, the month buttons are displayed in the outer ring and the images (imageview) are displayed in the inner ring. import circulartextlayout import ui layout_text = ''' ************ ************ bbbbbbbbbbbb ************ i*i*i*i*i*i* ************ ************ ''' image_list = [ ui.Image.named(i) for i in 'Rabbit_Face Mouse_Face Cat_Face Dog_Face Octopus Cow_Face'.split()] _range_12 = (.3, .34, .38, .42, .46, .5, .55, .6, .63, .7, .85, 1.0) def button_action(sender): print('Button {} was pressed.'.format(sender.title)) titles = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() attributes = {'b': [{'action':button_action, 'font' :('Helvetica', 20), 'bg_color':'orange', 'alpha':_range_12[i], 'border_width':.5, 'text_color':'black', 'tint_color':'black', 'title':j } for i, j in enumerate(titles)], 'i': [{'image':i, 'bg_color':'gray'} for i in image_list ] } v = circulartextlayout.BuildView(layout_text, width=600, height=600, view_name='Counter', attributes=attributes).build_view() for i in range(1, len(titles)+1): v['button'+str(i)].corner_radius = v['button'+str(i)].width*.5 for i in range(1, len(image_list)+1): v['imageview'+str(i)].corner_radius = v['imageview'+str(i)].width*.5 v.present('popover') The screeshot for this example is given below: I have also included an example (circular_directions.py) that is similar to your direction example. If you want an alpha property to your button, but independent of the list length, you can do btn = make_button(i, title=self._list[i]) btn.alpha = (1+i) * (1/len(self._list)) # will go from 1/n to 1.0, where n = Len of list self.add_subview(btn) Thus, no need of _range_12 @abcabc you're right but this code was only valuable for 12 items, not for 8, for instance in the code for N,....,E,.....,S,....W,..., or for any range Yes. You are right. I will update the code as suggested by you. Thanks for the suggestion. @abcabc , @cvp , _range_12 is ok. Just a list of 12 numbers between 0.0 and 1.0. But purposely not done linearly. That's why I put values into the list. To do it without constants you need some math. You can't start a zero or even .1 or even .2 for that matter, the resulting alpha is too faint. Also depending on what you want to do, the progression normally will look better if its not linear. @abcabc , ran your code. Works well. But you are not centered in the view. Maybe there is a param I can't see. But on my iPad Pro 12 inch I get the below. Edit: your x,y are off. Too much added somewhere Sorry a little out of sync with some of my comments. I am not sure it's just me or not, but I have had a hard time replying the last 40 mins or so. @Phuket2 There could be some problem with centering. I will look into that. Anyway I have to do some more testing. Below is a pretty nice adaptation of using the shared function here, after it's been fixed up 😱 But for use in this function or not, the get_rotated_icon function is nice or let's say functional. Simple function, code comes from help from omz on a similar subject. Probably not for 60fps stuff, but I think good for ui stuff. import editor import math import ui # this is a pretty funky function... def get_rotated_icon(named_icon_name, wh = 32, degree = 0): ''' help from @omz ''' r = ui.Rect(0, 0, wh, wh) img = ui.Image.named(named_icon_name) with ui.ImageContext(wh, wh) as ctx: ui.concat_ctm(ui.Transform.translation(*r.center())) ui.concat_ctm(ui.Transform.rotation(math.radians(degree))) ui.concat_ctm(ui.Transform.translation(*r.center() * -1)) img.draw() return ctx.get_image() def make_button(idx, title, name = None): def button_action(sender): print('Button {} was pressed.'.format(sender.name)) #btn = ui.Button(title=calendar.month_abbr[i+1]) name = name if name else title btn = ui.Button(name = name,' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cir_rect = None self.obj_list = [] self.mid_btn = None self.make_view() def make_view(self): for i in range(len(self._list)): obj = make_button(i, title=self._list[i]) obj.image = get_rotated_icon('iob:arrow_up_a_256', wh = 256, degree = i * 45) self.obj_list.append(obj) self.add_subview(obj) btn = make_button(i, title='C') self.mid_btn = btn self.add_subview(btn) def layout(self): r, rects = rects_on_circle_path(self.bounds, obj_width=70, margin=20, num_objs=len(self._list)) self.cir_rect = r for i, btn in enumerate(self.obj_list): btn.frame = rects[i] btn.title = '' btn.corner_radius = btn.width / 2 btn = self.mid_btn btn.center = r.center() btn.corner_radius = btn.width / 2 def draw(self): # just to see the path when testing... s = ui.Path.oval(*self.cir_rect) with ui.GState(): ui.set_color(css_clr_to_rgba('lime', .4)) s.line_width = 1 s.stroke() if __name__ == '__main__': _use_theme = True w=h = 600 f = (0, 0, w, h) mc = MyClass(frame=f, bg_color='white') if not _use_theme: mc.present('sheet', animated=False) else: editor.present_themed(mc, theme_name='Oceanic', style='sheet', animated=False) FWIW, is an example using ui.Transform to simulate your last imagE. Probably not as useful, but compact in this case. @JonB very nice. I have changed your code slightly to do a "semi-circular layout" which seems to be used in some of the ios applications. import ui, calendar from math import pi, sin, radians def make_button(i, v, N): def button_action(sender): print('Button {} was pressed.'.format(sender.title)) btn = ui.Button(title=calendar.month_abbr[i+1]) btn.action = button_action btn.height=btn.width=64 btn.alpha = sin(radians(15.+75.0/(N-1)*i)) btn.border_width = .5 btn.corner_radius = btn.width *.5 btn.bg_color = 'orange' btn.text_color = btn.tint_color = 'black' center_x, center_y = v.bounds.center() btn.center = (btn.width/2+5.0, center_y) #v.bounds.center() btn.transform=ui.Transform.translation(0,-(v.height/2-btn.height/2) ).concat(ui.Transform.rotation(2.*pi*i/N)) return btn v=ui.View(frame=(0,0,576,576)) v.bg_color=(1,1,1) N = 12 N1 = 7 for i in range(0,N1): v.add_subview(make_button(i, v, N)) v.present('sheet') Nice guys. As painfully as obvious as it is I have never thought of rotating the icons. After I did my compass test, I thought I would try it with arrows, could be used as a type of controller etc. then I was looking for the arrows offset by 45 degrees. Then it was like a big steel ball dropped from a great height on to my head. But also handy as you are only dealing with one image_name. I don't think speed would be ever a problem. Also simple to write out to PNG files if required. Anyway, I find it amazing how many things are sitting right under my nose I don't see @JonB , yeah your approach a lot more straight fwd. to be honest I didn't think about rotating the button. But I was also thinking about drawing into the view vrs using buttons. But in this case, no reason not just to use the buttons. Many ways to skin the cat. But I will hold on to your code also, has its own versatility 😬 For what its worth, ui.concat_ctm along lets you use ui.Transforms inside ImageContexts. This is perhaps a convolouted example, showing how you can use transforms rather than trying to do math for this sort of thing (in this case the sort of draggable lollipop hour selector). In the end, a little math is needed for the touch handling. Thanks
https://forum.omz-software.com/topic/3449/share-a-list-of-rects-distributed-around-360-degrees/23
CC-MAIN-2022-27
refinedweb
2,329
61.63
New in Chrome 83 Published on Chrome 83 is starting to roll out to stable now. Here's what you need to know: - Trusted types help prevent cross site scripting vulnerabilities. - Form elements get an important make-over. - There's a new way to detect memory leaks. - The native file system API starts a new origin trial with added functionality. - There are new cross-origin policies - We've introduced the Web Vitals program, to provide unified guidance for quality signals that, we believe, are essential to delivering a great user experience on the web. - And more. I'm Pete LePage, working and shooting from home, let's dive in and see what's new for developers in Chrome 83! App shortcuts were supposed to be landing in Chrome 83, but were delayed until Chrome 84, scheduled for July 14th. Trusted types # DOM-based cross-site scripting is one of the most common security vulnerabilities on the web. It can be easy to accidentally introduce one to your page. Trusted types can help prevent these kinds of vulnerabilities, because they require you to process the data before passing it into a potentially dangerous function. Take innerHTML for example, with trusted types turned on, if I try to pass a string, it'll fail with a TypeError because the browser doesn't know if it can trust the string. // Trusted types turned on const elem = document.getElementById('myDiv'); elem.innerHTML = `Hello, world!`; // Will throw a TypeError Instead, I need to either use a safe function, like textContent, pass in a trusted type, or create the element and use appendChild(). // Use a safe function elem.textContent = ''; // OK // Pass in a trusted type import DOMPurify from 'dompurify'; const str = `Hello, world!`; elem.innerHTML = DOMPurify.sanitize(str, {RETURN_TRUSTED_TYPE: true}); // Create an element const img = document.createElement('img'); img.src = 'xyz.jpg'; elem.appendChild(img); Before you turn on trusted types, you'll want to identify and fix any violations using a report-only CSP header. Content-Security-Policy-Report-Only: require-trusted-types-for 'script'; report-uri //example.com Then once you've got everything buttoned up, you can turn it on properly. Complete details are in Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types on web.dev. Updates to form controls # We use HTML form controls every day, and they are key to so much of the web's interactivity. They're easy to use, have built-in accessibility, and are familiar to our users. The styling of form controls can be inconsistent across browsers and operating systems. And we frequently have to ship a number of CSS rules just to get a consistent look across devices. I've been really impressed by the work Microsoft has been doing to modernize the appearance of form controls. Beyond the nicer visual style, they bring better touch support, and better accessibility, including improved keyboard support! The new form controls have already landed in Microsoft Edge, and are now available in Chrome 83. For more information, see Updates to Form Controls and Focus on the Chromium blog. Origin trials # Measure memory with measureMemory() # Starting an origin trial in Chrome 83, performance.measureMemory() is a new API that makes it possible to measure the memory usage of your page, and detect memory leaks. Memory leaks are easy to introduce: - Forgetting to unregister an event listener - Capturing objects from an iframe - Not closing a worker - Accumulating objects in arrays - and so on. Memory leaks lead to pages that appear slow, and bloated to users. if (performance.measureMemory) { try { const result = await performance.measureMemory(); console.log(result); } catch (err) { console.error(err); } } measureMemory() on web.dev for all the details of the new API. Updates to the Native File System API # The Native File System API started a new origin trial in Chrome 83 with support for writable streams, and the ability. } Writable streams make it much easier to write to a file, and because it's a stream, you can easily pipe responses from one stream to another. Saving file handles to IndexedDB allows you to store state, or remember which files a user was working on. For example keep a list of recently edited files, open the last file that the user was working on, and so on. You'll need a new origin trial token to use these features, so check out my updated article The Native File System API: Simplifying access to local files on web.dev with all the details, and how to get your new origin trial token. Other origin trials # Check </origintrials/#/trials/active> for a complete list of features in origin trial. New cross-origin policies # Some web APIs increase the risk of side-channel attacks like Spectre. To mitigate that risk, browsers offer an opt-in-based isolated environment called cross-origin isolated. The cross-origin isolated state also prevents modifications of document.domain. Being able to alter document.domain allows communication between same-site documents and has been considered a loophole in the same-origin policy. Check out Eiji's post Making your website "cross-origin isolated" using COOP and COEP for complete details. Web vitals # Measuring the quality of user experience has many facets. While some aspects of user experience are site and context specific, there is a common set of signals—"Core Web Vitals"—that is critical to all web experiences. Such core user experience needs include loading experience, interactivity, and visual stability of page content, and combined are the foundation of the 2020 Core Web Vitals. >>IMAGE layout shift of visible page content. All of these metrics capture important user-centric outcomes, are field measurable, and have supporting lab diagnostic metric equivalents and tooling. For example, while Largest Contentful Paint is the topline loading metric, it is also highly dependent on First Contentful Paint (FCP) and Time to First Byte (TTFB), which remain critical to monitor and improve. To learn more, check out Introducing Web Vitals: essential metrics for a healthy site on the Chromium Blog for complete details. And more # - Chrome now supports the Barcode Detection API, which provides the ability to detect and decode barcodes. - The new CSS @supportsfunction provides feature detection for CSS selectors. - New ARIA annotations support screen reader accessibility for comments, suggestions, and text highlights with semantic meanings (similar to <mark>). - The prefers-color-schememedia query lets authors support their own dark theme so they have full control over experiences they build. - JavaScript now supports modules in shared workers. Curious about what's coming in the future? Check out the Fugu API Tracker to see! Further reading # This covers only some of the key highlights. Check the links below for additional changes in Chrome 83. - What's new in Chrome DevTools (83) - Chrome 83 deprecations & removals - ChromeStatus.com updates for Chrome 83 - What's new in JavaScript in Chrome 83 - Chromium source repository change list Subscribe # Want to stay up to date with our videos, then subscribe to our Chrome Developers YouTube channel, and you'll get an email notification whenever we launch a new video. I'm Pete LePage, and I need a hair cut, but as soon as Chrome 84 is released, I'll be right here to tell you -- what's new in Chrome! Last updated: • Improve article
https://developer.chrome.com/blog/new-in-chrome-83/
CC-MAIN-2021-25
refinedweb
1,211
55.34
Hi,I booted the latest git today on a ppc64 box. When I pushed it intoswap I noticed both kswapd's were using 100% CPU and the soft lockupdetector suggested it was stuck in balance_pgdat:BUG: soft lockup - CPU#7 stuck for 23s! [kswapd1:359]Call Trace:[c00000000015e190] .balance_pgdat+0x150/0x940 [c00000000015eb2c] .kswapd+0x1ac/0x490[c00000000009edbc] .kthread+0xbc/0xd0[c00000000002142c] .kernel_thread+0x54/0x70I haven't had time to bisect but I did notice we were looping here:diff --git a/mm/vmscan.c b/mm/vmscan.cindex 7658fd6..c92bad2 100644--- a/mm/vmscan.c+++ b/mm/vmscan.c@@ -2945,9 +2959,11 @@ out: if (zone->all_unreclaimable && priority != DEF_PRIORITY) continue; +#if 0 /* Would compaction fail due to lack of free memory? */ if (compaction_suitable(zone, order) == COMPACT_SKIPPED) goto loop_again;+#endif /* Confirm the zone is balanced for order-0 */ if (!zone_watermark_ok(zone, 0,After commenting it out the box is happy again.Anton
http://lkml.org/lkml/2012/3/23/358
CC-MAIN-2014-52
refinedweb
150
57.67
By default in C# forms have the property TopMost and the function BringToFront(), but these just move the form forward in relation to other forms of the application. Therefore, we have to dig a bit deeper and to use the Win32 API. For above needs we need the function SetForegroundWindow(), which expects the handle of the target window. It grants the application the input focus, if the application is minimized though, it is now shown. The reason is, that minimized applications do not have a window which could be shown. To create this window we use the function ShowWindowAsync(). It expects 2 arguments, the first one is again the window handle, the second one an integer value determining how the window is shown. For an overview over all possibilities I want to refer to the MSDN, I only use SW_RESTORE, which shows the window in its original size. We now simply add a request asking whether the window is minimized, which is possible via the function IsIconic(). The following program uses the previously described functions to bring the program after elapse of the timer event to the front: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsFormsApplication1 { public partial class Form1 : Form { ; public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { if (IsIconic(this.Handle)) ShowWindowAsync(this.Handle, SW_RESTORE); SetForegroundWindow(this.Handle); } } }
http://csharp-tricks-en.blogspot.de/2012/05/bring-application-to-front.html
CC-MAIN-2018-09
refinedweb
245
50.94
Is it possible to change the "public" email address of a list (that reported in the rfc2369 headers, message footers, etc.) while maintaining a different name internally? Would there be any obvious problems I'm missing with such a feature? For our virtually hosted lists, we need independent namespaces on a per-domain basis. This isn't really something that Mailman currently handles AFAICT. So we might have: listname at lists.example.com (or listname at example.com) forwarding to listname-example.com at lists.example.com. Obviously this looks ugly, and encourages people to send to the "wrong" address; it's a simple matter, of course, to alias listname at example.com to listname-example.com at lists.example.com. This "hack" (if it worked) wouldn't be perfect, but would at least improve the virtual hosting situation for our purposes. For various reasons, it's not practical to do a unique installation of Mailman for each account or domain, and requiring unique listnames globally will also not work for our purposes. If not, consider this an RFE (I can submit one on the site if requested). If someone wanted to provide a patch for this (against 2.1.3), I might even be able to give them some money if it worked properly. -- "Since when is skepticism un-American? Dissent's not treason but they talk like it's the same..." (Sleater-Kinney - "Combat Rock")
https://mail.python.org/pipermail/mailman-users/2003-October/031962.html
CC-MAIN-2018-26
refinedweb
237
60.61