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
Windows Forms ("WinForms" for short) is a GUI class library included with the .NET Framework. It is a sophisticated object-oriented wrapper around the Win32 API, allowing the development of Windows desktop and mobile applications that target the .NET Framework. WinForms is primarily event-driven. An application consists of multiple forms (displayed as windows on the screen), which contain controls (labels, buttons, textboxes, lists, etc.) that the user interacts with directly. In response to user interaction, these controls raise events that can be handled by the program to perform tasks. Like in Windows, everything in WinForms is a control, which is itself a type of window. The base Control class provides basic functionality, including properties for setting text, location, size, and color, as well as a common set of events that can be handled. All controls derive from the Control class, adding additional features. Some controls can host other controls, either for reusability ( Form, UserControl) or layout ( TableLayoutPanel, FlowLayoutPanel). WinForms has been supported since the original version of the .NET Framework (v1.0), and is still available in modern versions (v4.5). However, it is no longer under active development, and no new features are being added. According to 9 Microsoft developers at the Build 2014 conference: Windows Forms is continuing to be supported, but in maintenance mode. They will fix bugs as they are discovered, but new functionality is off the table. The cross-platform, open-source Mono library provides a basic implementation of Windows Forms, supporting all of the features that Microsoft's implementation did as of .NET 2.0. However, WinForms is not actively developed on Mono and a complete implementation is considered impossible, given how inextricably linked the framework is with the native Windows API (which is unavailable in other platforms). This example will show you how to create a Windows Forms Application project in Visual Studio. Start Visual Studio. On the File menu, point to New, and then select Project. The New Project dialog box appears. In the Installed Templates pane, select "Visual C#" or "Visual Basic". Above the middle pane, you can select the target framework from the drop-down list. In the middle pane, select the Windows Forms Application template. In the Name text box, type a name for the project. In the Location text box, choose a folder to save the project. Click OK. The Windows Forms Designer opens and displays Form1 of the project. From the Toolbox palette, function. Type the following code: C# MessageBox.Show("Hello, World!"); VB.NET MessageBox.Show("Hello, World!") Press F5 to run the application. When your application is running, click the button to see the "Hello, World!" message. Close the form to return to Visual Studio. Open a text editor (like Notepad), and type the code below: using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace SampleApp { public class MainForm : Form { private Button btnHello; // The form's constructor: this initializes the form and its controls. public MainForm() { // Set the form's caption, which will appear in the title bar.). btnHello.Click += new EventHandler(btnHello_Click); // Add the button to the form's control collection, // so that it will appear on the form. this.Controls.Add(btnHello); } // When the button is clicked, display a message. private void btnHello_Click(object sender, EventArgs e) { MessageBox.Show("Hello, World!"); } // This is the main entry point for the application. // All C# applications have one and only one of these methods. [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } } X:\MainForm.cs. Run the C# compiler from the command line, passing the path to the code file as an argument: %WINDIR%\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:winexe "X:\MainForm.cs" Note: To use a version of the C# compiler for other .NET framework versions, take a look in the path, %WINDIR%\Microsoft.NET and modify the example above accordingly. For more information on compiling C# applications, see Compile and run your first C# program. MainForm.exewill be created in the same directory as your code file. You can run this application either from the command line or by double-clicking on it in Explorer. Open a text editor (like Notepad), and type the code below: Imports System.ComponentModel Imports System.Drawing Imports System.Windows.Forms Namespace SampleApp Public Class MainForm : Inherits Form Private btnHello As Button ' The form's constructor: this initializes the form and its controls. Public Sub New() ' Set the form's caption, which will appear in the title bar.). AddHandler btnHello.Click, New EventHandler(AddressOf btnHello_Click) ' Add the button to the form's control collection, ' so that it will appear on the form. Me.Controls.Add(btnHello) End Sub ' When the button is clicked, display a message. Private Sub btnHello_Click(sender As Object, e As EventArgs) MessageBox.Show("Hello, World!") End Sub ' This is the main entry point for the application. ' All VB.NET applications have one and only one of these methods. <STAThread> _ Public Shared Sub Main() Application.EnableVisualStyles() Application.Run(New MainForm()) End Sub End Class End Namespace X:\MainForm.vb. Run the VB.NET compiler from the command line, passing the path to the code file as an argument: %WINDIR%\Microsoft.NET\Framework64\v4.0.30319\vbc.exe /target:winexe "X:\MainForm.vb" Note: To use a version of the VB.NET compiler for other .NET framework versions, take a look in the path %WINDIR%\Microsoft.NET and modify the example above accordingly. For more information on compiling VB.NET applications, see Hello World. MainForm.exewill be created in the same directory as your code file. You can run this application either from the command line or by double-clicking on it in Explorer.
https://riptutorial.com/winforms/topic/1018/getting-started-with-winforms
CC-MAIN-2019-30
refinedweb
949
60.01
Code commented in your mother tongue occasionally leads to odd error messages from compilation. Two question marks and an exclamation ditto are replaced by one vertical bar; The seemingly strange is easier to understand with an insight in the translation phases of your compiler. The elements in the translation are defined in the C standard and are there to prepare the source code for the final code generation. This text is a brief guide to helping you avoid problems and gain advantages from knowing a little bit more about the preprocessing phases of translation. Translation according to the C standard is divided into 8 phases. The better known phases are perhaps phase 7 and 8 for parsing, code generation, and linking. Phases 1 through 6 are the preprocessing phases. This text concentrates on the aspects of preprocessing that are most important to software engineers to avoid an error or two in compilation, especially since these errors tend to be most unexpected. The first phase of preprocessing deals with trigraphs and may be the source of unexpected results during compilation. Every trigraph is replaced by its corresponding single character, wherever the three trigraph characters are placed in the code. At this early stage of preprocessing the code is treated merely as a great number of 8-bit ASCII characters. A trigraph is replaced by the single character independent of if placed in strings or comments. The C standard defines nine trigraphs. The one that most commonly causes problems is ??!. Strings and code comments aimed to be visible only to the software engineer and colleagues run the risk of including that sequence of characters as a part. printf ("This should never happen ??! (?? LINE 47 ??)") When the above line of code is preprocessed it will look like this: printf ("This should never happen | (?? LINE 47 ]") The example is perhaps irritating but not critical. The same replacement of characters in a string that are going to be displayed to an end customer using the product is another thing. The table shows the nine trigraphs and their respective corresponding single characters according to the C standard. If you really need to use the character sequence ??! in your code, there are a couple of options. Either by “escaping” the three character sequence (phase 5) or through string concatenation (phase 6). This is an illustration of escaping: printf ("What am I doing \?\?!\n"); It’s actually enough to escape only one of the question marks, like this: printf ("What am I doing ?\?!\n"); The same line of code, now using string concatenation to avoid confusion with a trigraph during preprocessing: printf ("What am I doing ??""!\n"); It’s quite common to write multi line macros using the backslash character \ as a line continuation mark. It makes the code more readable without breaking the single line syntax of macros. Extensive macros are divided into several lines in the editor, every line ending with the backslash character \ and a line break making the code easier to read. This is how it might look: #define my_assert(arg) \ ((arg) ? \ void)0 \ : \ (void) handle_assert ( #arg,__FILE__, __LINE_ ) ) The C standard supports this strategy. The backslash character and the line break are deleted from the code in phase 2 splicing physical source lines to logical ones. In relations to phase 2, a couple of characteristic problems can arise. A mistake on the computer keyboard places an invisible space character at the end of the line. The line break isn’t removed, leaving the macro incorrectly divided in two lines. It might be tempting to use the space after the backslash for code comments, but that will not work. Only the sequence ‘backslash’, ‘new-line’ will do the splicing so any comments must come before the backslash. In phase 3, code comments are deleted and replaced by a single space character. There isn’t a great deal to say about that. Phase 4 is more interesting. Preprocessing directives are executed and macro invocations are expanded. Once executed and expanded no reiteration is performed, which one may be lead to believe. Thus none of the intentions revealed in the following examples are fruitful. First example: #define MY_ASSERT_NG1 #include "my_assert.h" MY_ASSERT_NG1 Second example: #define NO_OPT_NG #pragma optimize=none Third example: #define MY_ASSERT_NG2 my_assert.h #include "MY_ASSERT_NG2" The ANSI committee has realized that there is a point to the intentions in the first and third example, so the committee has introduced the syntax #include pp-tokens. The problems above (the first and third example) are circumvented using this syntax in these lines of code: #define MY_ASSERT_OK "my_assert.h" #include MY_ASSERT_OK Preprocessing directives executed in phase 4. The combination of the two preprocessing directives #define and #pragma is worth discussing a bit more. Let’s say it’s desirable to be able to use two compilers on a single source code file. Such a desire is seen in this approach. #ifdef IAR #define NO_OPT #pragma optimize=none #else #define NO_OPT #pragma … #endif When preprocessing directives have been executed and macros expanded, #pragma will remain but without hope for a possibility of ever being executed by the preprocessor because phase 4 is already left for phase 5. This desire fortunately is possible to meet in another way. The C standard has addressed the issue through the introduction of the keyword _Pragma. The _Pragma keyword is supported in IAR compilers. So from the example above, what you can do is: #ifdef IAR #define NO_OPT _Pragma ("optimize=none") #else #define NO_OPT _Pragma ("…") #endif NO_OPT void some_func(void) { … } Until now the focus has been on pitfalls only. Phase 5 contains a couple of possibilities. Bear with me. In phase 5 you have the ‘escaping’ of character constants, e.g. : \' the character ' \" the character " \? the character ? \\ the character \ \x hexadecimal character Embedded applications need to be able to display written languages using for instance Arabic or Chinese letters to the user of the product. A typical application uses a driver to interpret Unicode strings and display the corresponding character. Editors supporting Unicode are used for writing the C code. Compilation of such an application may run into problems since the C standard only supports 8-bit ASCII characters. Without corrective actions the Unicode strings are divided into irrelevant ASCII characters. Quotation marks around the strings partly solve this problem to keep the string unaltered through to phase 5. But, to be honest, it’s also a matter of luck since the compiler is always reading the source as 8-bit ASCII characters. There will always be a risk involved in using non-ASCII code in the source. Let’s look at another example to show you what I mean. The picture shows the Japanese word for “ability”. The S-JIS editor code for this Japanese word is 945C. The code contains 0x5C, which represents backslash and runs the risk of being the last character on a line of code leading to line splicing (phase 2). If used inside e.g. a string this 0x5C will try to escape the next character (phase 5) possibly leading to some error, but in any circumstances the S-JIS interpretation will have disappeared. Using non-ASCII characters, for example in a Unicode string, can be done as shown in the example to avoid mix-ups in any of the preprocessing phases. char str[] = "\x84\xFF" \x in the string implies that the following number is hexadecimal, 84 and FF respectively in this case and the characters will be left unchanged for sure. String values can be problematic even if Unicode isn’t used. Applications that for some reason need the byte sequence 0x0D,0x0A in for example a string will suffer from a misinterpretation during phase 2 since the sequence of "0D0A" represents a line break. \x is the solution to this problem as well. "\x0D\x0A" will pass phase 2 as intended. In phase 6 adjacent string literals are concatenated. This supports the possibility to make the source code easier to read in the editor. This example shows how it’s done. char usage[] = "Usage:\n" /* Can comment here, phase 3 has already */ " MyApp [options] infile outfile\n" /* made the comments into one space */ " Options:\n" " -a all\n" " -b bald\n" " -c cold\n"; The source code is finally prepared for parsing, code generation, and linking. Hopefully, the knowledge from this article will limit the number of error messages or at least help you find out what is going on behind the scene when you get confusing error messages from the compiler. The text has been limited to describing elements from the preprocessing phases that are regarded relevant to software engineers to avoid a selection of typical errors. The complete C standard documentation is recommended for more information and details about the translation phases.
https://www.iar.com/support/resources/articles/preprocessor-directives-what-became-of-my-/
CC-MAIN-2018-09
refinedweb
1,460
54.93
Where examples are omitted you should refer to the Microsoft documentation, Enumerable Methods, although Microsoft themselves do not provide examples for every method, particularly for the more obscure, or rarely used, methods or overloads. Aggregate, All, Any, AsEnumerable, Average, Cast, Concat, Contains, Count, DefaultIfEmpty, Distinct, ElementAt, ElementAtOrDefault, Empty, Except, First, FirstOrDefault, GroupBy, GroupJoin, Intersect, Join, Last, LastOrDefault, LongCount, Max, Min, OfType, OrderBy, OrderByDescending, Range, Repeat, Reverse, Select, SelectMany, SequenceEqual, Single, SingleOrDefault, Skip, SkipWhile, Sum, Take, TakeWhile, ThenBy, ThenByDescending, ToArray, ToDictionary, ToList, ToLookup, Union, Where, Zip Even though this tutorial is presented in a dictionary format I recommended that you read it, at least initially, sequentially. This will give you a feel for LINQ and what it can achieve, and you will begin to recognise patterns in the methods. Other tutorials in this sequence: LINQ by Example 2: Enumerable Methods M-Z LINQ by Example 3: Methods Using IEqualityComparer LINQ by Example 4: Query Expression Syntax LINQ by Example 5: LINQ to XML Querying The MS documentation and examples for the methods are generally good but: - They are spread over around 100 pages - There is a lot of repetition and you have to scroll quite far down to find the examples - The examples introduce new collections each time. Creating new collections each time means that the pages are independent, but it does mean that you first have to read through and decipher the collections, before you can begin to understand the method itself. My approach is to provide examples over just a few pages and to use, in the main, the same core-data, and a code-template that you can just copy the examples into. The main advantage is that you will become familiar with the core-data and so can concentrate on understanding the methods themselves. The MS documentation is also littered with type-parameters like this: SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) This information is important but not immediately necessary to understand the methods - the type information can often be deduced from the examples. (This information initially gets in the way, in my opinion.) Similarly, I am using arrays of anonymous types for the core-data. This largely removes all this type information. It does mean, however, that I have occasionally had to use var as the type; after all, with an anonymous-type, what would you put for T in Enumerable<T>? What is LINQ? LINQ (Language-Integrated Query) :MSDN MSDN said:. Basically, LINQ allows us to perform queries against sequences of data. A query may result in a new collection, or a single (scalar) value: e.g. Min, Count. (It is also possible using LINQ to modify the collection itself.) LINQ can query any collection implementing IEnumerable<>: arrays, any collection, XML DOM, or remote data sources. A string also implements IEnumerable<>, it is a collection of characters: How to: Query for Characters in a String (LINQ) :MSDN although LINQ is not usually necessary with a string: there are many string methods, or Regex, available. There are a few versions of LINQ: LINQ to Objects LINQ to Entities LINQ to SQL LINQ to XML We will be using LINQ to Objects, querying local objects/collections. LINQ to Entities is for writing queries against the Entity Framework conceptual model. LINQ to SQL is for querying relational data as objects. That is, instead of using unfamiliar SQL statements we can use C# LINQ syntax. SQL statements are strings and don't provide any intellisense (drop-down help), LINQ does. LINQ to SQL is discouraged (by Microsoft) in favour of LINQ to Objects or LINQ to Entities. That is, instead of operating against data, a DAL (data access layer) should be created and queried. A DAL is an object model that represents the data-source. The Entity Framework provides this DAL as an ORM (object-relational map). LINQ to XML MSDN said: LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. Query Expression Syntax Query Expression Syntax for Standard Query Operators :MSDN Query expression syntax is more familiar for people who are comfortable with SQL statements: var people = from member in staff where member.salary > 20000 select member; foreach (var person in people) Console.WriteLine(person.name + " " + person.salary.ToString("C0")); These expressions are converted into calls to the Enumerable methods that we will be exploring. Note that LINQ uses lazy evaluation; that is, 'people' in the above is not evaluated until enumerated in the foreach statement. The expression syntax does not include syntax for all of the Enumerable methods, but you can generally use either. This SO topic highlights some differences. It is also possible to mix expression and method (fluent) syntax: double peopleAvg = (from member in staff where member.salary > 20000 select member).Average(x => x.salary); Console.WriteLine(peopleAvg.ToString("C0")); The nomenclature for LINQ is a little confusing. Enumerable methods are referred to as query operators but, to my mind, from..where.. are operators. Methods are methods! The methods are also referred to as fluent syntax, a term which I believe originates from the authors of the book C# in a Nutshell. Again, I think the query expressions are more suited to this 'fluent' description. Methods are methods! from..where.. is also sometimes referred to as comprehension syntax, but not often. The Template This is the Console template, and data, to use for all of the examples: using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace LINQTest { class Program { static void Main(string[] args) { int[] nos = { 34, 22, 22, 21, 40, 31, 32, 34, 40, 50, 10, 17 }; string[] rainbow = { "Rod", "Jane", "Freddy", "Bungle", "Zippy", "George" }; // Rainbow was a UK children's television series string[] extras = { "George", "Zippy", "Fred" }; // arrays of anonymously typed elements var staff = new[] { new { name = "Bob Bones", salary = 20000, deptid = 1, grade = 6 }, new { name = "Mary Muggins", salary = 22000, deptid = 2, grade = 6 }, new { name = "Liz Elbow", salary = 22500, deptid = 2, grade = 5 }, new { name = "Dave Diddly", salary = 28000, deptid = 3, grade = 4 }, new { name = "Mary Pickles", salary = 27000, deptid = 1, grade = 4 }, new { name = "Robert Piccalilli", salary = 18000, deptid = 1, grade = 6 } }; var depts = new[] { new { deptid = 1, dept = "Marketing" }, new { deptid = 2, dept = "Sales" }, new { deptid = 3, dept = "Accounts" }, new { deptid = 4, dept = "Human Resources" } }; /**************************** * TYPE YOUR EXAMPLE(S) HERE * **************************/ Console.ReadKey(); } } } Just copy examples to this template and run it. Some examples include additional, small or empty, collections, but you can still copy these examples into the template and run them. The Methods The method definitions are taken directly from the official documentation, other quotes from the docs I have placed within italics. In fact, most of the text is from the MS documentation, I have only occasionally considered it useful to add additional notes. (The examples, and comments within them are, of course, mine.) One thing in particular that you need to understand with the examples is the use of lambda expressions. In x => 2 * x x is a placeholder for the current value and '2 * x' projects this value to a result. In staff.Sum(x => x.salary) 'staff' is the collection, x represents (in turn) each member of this collection and 'x.salary' is the result (for each member) that the method uses. Note: There are some methods for which I haven't provided an example: AsEnumerable, Cast, Empty, ToLookup. This is because I cannot add anything brief and useful beyond the Microsoft documentation. Enumerable Methods :MSDN Methods can be chained together, for example: IEnumerable<int> top3sal = staff.OrderByDescending(member => member.salary).Select(x => x.salary).Take(3); although this is much easier to read like this: IEnumerable<int> top3sal = staff .OrderByDescending(member => member.salary) .Select(x => x.salary) .Take(3); Aggregate Applies an accumulator function over a sequence. To simplify common aggregation operations, the standard query operators also include a general purpose count method, Count, and four numeric aggregation methods, namely Min, Max, Sum, and Average. Quite often when you find yourself using Aggregate it just means that you haven't quite worked out how to write it in a simpler fashion, without Aggregate. Use Min, Max, etc., in preference where possible. There are three different versions of Aggregate demonstrated, and numbered, here. (I have numbered them according to the order they appear in the MSDN documentation.) If this is your first read-through of this tutorial you might skip Aggregate and move on to All. Aggregate 1: Applies an accumulator function over a sequence. string bowrain = rainbow.Aggregate((accum, next) => accum + " " + new string(next.ToCharArray().Reverse().ToArray())); Console.WriteLine(bowrain); // Rod enaJ ydderF elgnuB yppiZ egroeG string ainbow = rainbow.Aggregate((accum, next) => next.Substring(1) + " " + accum); Console.WriteLine(ainbow); // eorge ippy ungle reddy ane Rod Aggregate 2: Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value. // Count even numbers: int evens = nos.Aggregate(0, (total, next) => next % 2 == 0 ? total + 1 : total); Console.WriteLine("Evens {0}", evens); // 9 int evensCount = nos.Count(x => x % 2 == 0); Console.WriteLine("Evens by Count, {0}", evensCount); // 9 Aggregate 3: Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value. // Find names longer than "Geoff", return the longest in uppercase string longGeoff = rainbow.Aggregate("Geoff", (longest, next) => next.Length > longest.Length ? next : longest, // return the final result as uppercase member => member.ToUpper()); Console.WriteLine(longGeoff); // FREDDY (George isn't > Freddy) All Determines whether all elements of a sequence satisfy a condition. bool allGT20k = staff.All(member => member.salary > 20000); Console.WriteLine("All salaries are{0}greater than 20k.", allGT20k ? " " : " not "); Any Determines whether any element of a sequence exists or satisfies a condition. Enumerable.Any Method Any 1: Determines whether a sequence contains any elements. Console.WriteLine("There are{0}staff.", staff.Any() ? " " : " no "); Collections already have methods or properties to determine if they contain any elements, so this method isn't particularly useful. It is more useful when used in the where clause of a query expression: var owners = new[] { new { name = "Derek", pets = new[] { new { Name = "Tiddles" } } } }; // which owners have Any pets..? There can't be any anyway! IEnumerable<string> petOwners = from owner in owners where owner.pets.Any() select owner.name; foreach (string ownerName in petOwners) Console.WriteLine(ownerName); Any 2: Determines whether any element of a sequence satisfies a condition. // any grade 6 earning > 20k? bool grade620k = staff.Any(member => member.grade == 6 && member.salary > 20000); Console.WriteLine(grade620k ? "Some grade 6, > 20k" : "No grade 6, > 20k"); AsEnumerable Returns the input typed as IEnumerable<T>. The AsEnumerable<TSource>(IEnumerable<TSource>) method has no effect other than to change the compile-time type of source from a type that implements IEnumerable<T> to IEnumerable<T> itself. Enumerable.AsEnumerable<TSource> Method :MSDN Average Computes the average of a sequence of (type) values. There are 20 overloads of this method but, essentially, there are two distinct versions. There are overloads for each of the data-types Decimal, Double, Int32, Int64 and Single, and nullable versions of each of these. int? x declares a nullable integer, that can be assigned 'null': int x? = null; Average 1: Computes the average of a sequence of (type) values. Console.WriteLine("Average number is {0}", nos.Average()); If you point at the word Average in that code you will see that it returns System.Int32 by default. Average 2: Computes the average of a sequence of (type) values that are obtained by invoking a transform function on each element of the input sequence. (This also has nullable versions for each type.) Console.WriteLine("Average salary is {0}", staff.Average(member => member.salary)); Cast Casts the elements of an IEnumerable to the specified type. An example of its use is for an ArrayList, which does not implement IEnumerable<T>. By calling Cast<TResult>(IEnumerable) on the ArrayList object, the standard query operators can then be used to query the sequence. The equivalent in a query expression is from int i in objects. Enumerable.Cast<TResult> Method :MSDN Concat Concatenates two sequences. This is similar to Union but returns all elements, Union only returns unique elements. IEnumerable<string> namesAndDepts = staff.Select(member => member.name) .Concat(depts.Select(dep => dep.dept)); // IEnumerable<string> requires 'using System.Collections.Generic;' foreach (string item in namesAndDepts) { Console.WriteLine(item); } //Dave Diddly //Mary Pickles //Robert Piccalilli //Marketing //Sales //Accounts //Human Resources (would return any duplicates as well) Contains Determines whether a sequence contains a specified element. Contains 1: Determines whether a sequence contains a specified element by using the default equality comparer. bool hasBob = rainbow.Contains("Bob"); Console.WriteLine("Rainbow has Bob? {0}", hasBob ? "Yes" : "No"); Contains 2: Determines whether a sequence contains a specified element by using a specified IEqualityComparer<T>. See Part 3. Enumerable.Contains<TSource> Method (IEnumerable<TSource>, TSource, IEqualityComparer<TSource>) :MSDN Count Returns the number of elements in a sequence. Count 1: Returns the number of elements in a sequence. int totalStaff = staff.Count(); Console.WriteLine("There are {0} staff.", totalStaff); Count 2: Returns a number that represents how many elements in the specified sequence satisfy a condition. int grade6s = staff.Count(member => member.grade == 6); Console.WriteLine("There are {0} grade 6's.", grade6s); int grade6sGT18 = staff.Count(member => member.grade == 6 && member.salary > 18000); Console.WriteLine("There are {0} grade 6's earning more than 18k.", grade6sGT18); DefaultIfEmpty Returns the elements of an IEnumerable<T>, or a default valued singleton collection if the sequence is empty. These methods can be used to produce a left outer join when combined with the GroupJoin method. DefaultIfEmpty 1: Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty. (The default value for reference and nullable types is null.) List<int> nothingToSeeHere = new List<int>(); foreach (int number in nothingToSeeHere.DefaultIfEmpty()) Console.WriteLine(number); // 0, the default for int DefaultIfEmpty 2: Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty. var patsy = new { name = "P Pats", salary = 0, deptid = 1, grade = 6 }; foreach (var member in staff.DefaultIfEmpty(patsy)) { Console.WriteLine(member.name); // will print all names because staff is not empty } Distinct Returns distinct elements from a sequence. Distinct 1: Returns distinct elements from a sequence by using the default equality comparer to compare values. foreach (int item in nos.Distinct()) { Console.WriteLine(item); } // 34, 22, 21, 40, 31, 32, 50, 10, 17 Distinct 2: Returns distinct elements from a sequence by using a specified IEqualityComparer<T> to compare values. See Part 3. ElementAt Returns the element at a specified index in a sequence. Console.WriteLine("Second staff member is {0}", staff.ElementAt(1).name); // Mary Muggins ElementAtOrDefault Returns the element at a specified index in a sequence or a default value if the index is out of range. string jeff = rainbow.ElementAtOrDefault(10); Console.WriteLine(String.IsNullOrEmpty(jeff) ? "Jeffrey" : jeff); Empty Returns an empty IEnumerable(Of T) that has the specified type argument. In some cases, this method is useful for passing an empty sequence to a user-defined method that takes an IEnumerable(Of T). It can also be used to generate a neutral element for methods such as Union. Enumerable.Empty<TResult> Method :MSDN Except Produces the set difference of two sequences. The set difference is the members of the first sequence that don't appear in the second sequence. Except 1: Produces the set difference of two sequences by using the default equality comparer to compare values. foreach (string intersect in rainbow.Except(extras)) { Console.WriteLine(intersect); } // Rod, Jane, Freddy, Bungle Except 2: Produces the set difference of two sequences by using the specified IEqualityComparer<T> to compare values. See Part 3. First First 1: Returns the first element of a sequence. Console.WriteLine("First in Rainbow is {0}", rainbow.First()); // Rod First 2: Returns the first element in a sequence that satisfies a specified condition. int firstGT35 = nos.First(x => x > 35); Console.WriteLine("First number > 35 is {0}", firstGT35.ToString()); // 40 FirstOrDefault FirstOrDefault 1: Returns the first element of a sequence, or a default value if the sequence contains no elements. Console.WriteLine("First number is {0}", nos.FirstOrDefault()); // 34 int[] nos2 = { }; Console.WriteLine("First number is {0}", nos2.FirstOrDefault()); // 0 FirstOrDefault 2: Returns the first element of the sequence that satisfies a condition or a default value if no such element is found. int firstGT80 = nos.FirstOrDefault(x => x > 80); Console.WriteLine("First number > 80 is {0}", firstGT80); // 80 GroupBy Groups the elements of a sequence. There are eight overloads of this methods. I have followed the Microsoft documentation in only providing examples for two of them. Enumerable.GroupBy Method :MSDN GroupBy 3: Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function. IEnumerable<IGrouping<int, string>> byDept = staff.GroupBy(x => x.deptid, x => x.name); foreach (IGrouping<int, string> pers in byDept) { Console.WriteLine("Dept: {0}", depts.FirstOrDefault(x => x.deptid == pers.Key).dept); // pers.Key is the deptid - use this to get the dept-name foreach (string per in pers) { Console.WriteLine("\t{0}", per); } } GroupBy 4: Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. var by5Grand = staff.GroupBy( member => Math.Floor((decimal)member.salary / 5000) * 5000, (agroup, members) => new { Key = agroup, Count = members.Count(), MinGrade = members.Min(member => member.grade) }).OrderBy(x => x.Key); // OrderBy not required, but useful foreach (var group in by5Grand) { Console.WriteLine("\nFrom salary: " + group.Key.ToString("c")); Console.WriteLine("Number of staff: " + group.Count); Console.WriteLine("Minimum grade: " + group.MinGrade); } //From salary: £15,000.00 //Number of staff: 1 //Minimum grade: 6 //From salary: £20,000.00 //Number of staff: 3 //Minimum grade: 5 //From salary: £25,000.00 //Number of staff: 2 //Minimum grade: 4 GroupJoin Correlates the elements of two sequences based on key equality, and groups the results. GroupJoin has no direct equivalent in traditional relational database terms. However, this method does implement a superset of inner joins and left outer joins. GroupJoin is interesting in that, as mentioned, it has no direct equivalent in SQL. The separation of the departments in the following code is usually achieved by iterating resultsets in code, using an if-statement to display, and indent, on separate lines. GroupJoin 1: Correlates the elements of two sequences based on equality of keys and groups the results. The default equality comparer is used to compare keys. var groupDepts = depts.GroupJoin(staff, dep => dep.deptid, member => member.deptid, (dep, memberCollection) => new { Department = dep.dept, Members = memberCollection.Select(member => member.name) }); foreach (var member in groupDepts) { Console.WriteLine(member.Department); foreach (string name in member.Members) { Console.WriteLine("\t{0}", name); } } //Marketing // Bob Bones // Mary Pickles // Robert Piccalilli //Sales // Mary Muggins // Liz Elbow //Accounts // Dave Diddly //Human Resources GroupJoin 2: Correlates the elements of two sequences based on key equality and groups the results. A specified IEqualityComparer<T> is used to compare keys. See Part 3. Intersect (see also Union) Produces the set intersection of two sequences. Intersect 1: Produces the set intersection of two sequences by using the default equality comparer to compare values. IEnumerable<string> inCommon = rainbow.Intersect(extras); foreach (string item in inCommon) { Console.WriteLine(item); // Zippy and George } Intersect 2: Produces the set intersection of two sequences by using the specified IEqualityComparer<T> to compare values. See Part 3. Join Correlates the elements of two sequences based on matching keys. In relational database terms, the Join method. Join 1: Correlates the elements of two sequences based on matching keys. The default equality comparer is used to compare keys. var joining = depts.Join(staff, dep => dep.deptid, member => member.deptid, (dep, member) => new { Department = dep.dept, Name = member.name }); foreach (var item in joining) { Console.WriteLine("{0} - {1}", item.Department, item.Name); } //Marketing - Bob Bones //Marketing - Mary Pickles //Marketing - Robert Piccalilli //Sales - Mary Muggins //Sales - Liz Elbow //Accounts - Dave Diddly Join 2: Correlates the elements of two sequences based on matching keys. A specified IEqualityComparer<T> is used to compare keys. See Part 3. Last 1: Returns the last element of a sequence. Console.WriteLine("Last number: {0}", nos.Last()); // 17 Last 2: Returns the last element of a sequence that satisfies a specified condition. var lastSalary = staff.Last(x => x.salary < 25000); Console.WriteLine("Last person earning < 25000 is {0}", lastSalary.name); // Robert Piccalilli LastOrDefault LastOrDefault 1: Returns the last element of a sequence, or a default value if the sequence contains no elements. string [] nowt = {}; Console.WriteLine("The last item is {0}", nowt.LastOrDefault()); // "" LastOrDefault 2: Returns the last element of a sequence that satisfies a condition or a default value if no such element is found. string lastRain = rainbow.LastOrDefault(x => x.Length == 5); Console.WriteLine("Last rainbow-name of length 5: {0}", lastRain); // Zippy LongCount LongCount 1: Returns an Int64 that represents the total number of elements in a sequence. Use this method rather than Count when you expect the result to be greater than MaxValue. Console.WriteLine("There are {0} staff", staff.LongCount()); LongCount 2: Returns an Int64 that represents how many elements in a sequence satisfy a condition. Console.WriteLine("{0} staff earn > 20k", staff.LongCount(x => x.salary > 20000)); Enumerable Methods M-Z Methods Using IEqualityComparer Query Expression Syntax LINQ to XML Querying This post has been edited by andrewsw: 04 September 2014 - 04:11 PM
http://www.dreamincode.net/forums/topic/352580-linq-by-example-1-enumerable-methods-a-l/
CC-MAIN-2016-07
refinedweb
3,599
50.33
ColdFusion 10 - Parsing Dirty HTML Into Valid XML Documents As I blogged earlier, ColdFusion 10 now supports XPath 2.0 in the xmlSearch() and xmlTransform() functions. This might not sound like a very exciting upgrade; however, when you realize that ColdFusion 10 now enables the parsing of "dirty" HTML code into valid XML documents, suddenly, the world of XML becomes a lot more interesting. NOTE: At the time of this writing, ColdFusion 10 was in public beta. ColdFusion 10 doesn't provide a native htmlParse() method; however, ColdFusion 10 now ships with the TagSoup 1.2 library pre-installed. This means that we can now instantiate the TagSoup classes and use them to convert our HTML documents into valid XML documents. And, of course, once we do that, we can use xmlSearch() to easily extract elements from our target HTML source code. To demonstrate this functionality, I'm going to create "dirty" HTML content and then parse it into a searchable XML document. When I use the term "dirty," I simply mean that the HTML will have things like missing close-tags, missing attribute quotes, poor nesting, and upper-case element and attribute names. - <!--- - Create our "dirty" HTML document. Dirty in the sense that it - cannot be parsed as valid XML. In order to make this document - "bad", we'll have tags that don't self-close and perhaps a - missing close-tag or two. - ---> - <cfsavecontent variable="dirtyHtml"> - <!doctype html> - <html xmlns=""> - <head> - <title>Dana Linn Bailey</title> - <meta name="description" content="Strong female muscle, FTW!"> - <meta name="keywords" content="female muscle,femmuscle,sexy"> - </head> - <body> - <h1> - Dana Linn Bailey - </h1> - <h2> - Professional Bodybuilder - </h2> - <p> - <IMG - SRC="//" - ALT="Dana Linn Bailey" - HEIGHT=250> - <br> - </p> - <h3> - Professional Services - </h3> - <ul> - <li>Full Contest Preparation - <li>12-Week Weight Management Program - <li>ONE-TIME Personalized Diet Plan - <li>ONE-TIME Personalized Week Training Program - <li>Train with DLB herself!!! - </ul> - <h2> - Biography - </h2> - <p> - I grew up a jock. At age 6, I was already on the swim - team, waking up and going to practice just like the big - kids. Up until high school, I was a 6-sport athlete all - year round, playing soccer, basketball, field hockey, - softball, running track and also swim team. In high - school I continued with my 3 favorite sports, soccer, - basketball, and field hockey and excelled in all with - many awards. - <p> - <a href=>Read More</a>. - </p> - </body> - </html> - </cfsavecontent> - <!--- ----------------------------------------------------- ---> - <!--- ----------------------------------------------------- ---> - <!--- ----------------------------------------------------- ---> - <!--- ----------------------------------------------------- ---> - <cfscript> - // I take an HTML string and parse it into an XML(XHTML) - // document. This is returned as a standard ColdFusion XML - // document. - function htmlParse( htmlContent, disableNamespaces = true ){ - // Create an instance of the Xalan SAX2DOM class as the - // recipient of the TagSoup SAX (Simple API for XML) compliant - // events. TagSoup will parse the HTML and announce events as - // it encounters various HTML nodes. The SAX2DOM instance will - // listen for such events and construct a DOM tree in response. - var saxDomBuilder = createObject( "java", "com.sun.org.apache.xalan.internal.xsltc.trax.SAX2DOM" ).init(); - // Create our TagSoup parser. - var tagSoupParser = createObject( "java", "org.ccil.cowan.tagsoup.Parser" ).init(); - // Check to see if namespaces are going to be disabled in the - // parser. If so, then they will not be added to elements. - if (disableNamespaces){ - // Turn off namespaces - they are lame an nobody likes - // to perform xmlSearch() methods with them in place. - tagSoupParser.setFeature( - tagSoupParser.namespacesFeature, - javaCast( "boolean", false ) - ); - } - // Set our DOM builder to be the listener for SAX-based - // parsing events on our HTML. - tagSoupParser.setContentHandler( saxDomBuilder ); - // Create our content input. The InputSource encapsulates the - // means by which the content is read. - var inputSource = createObject( "java", "org.xml.sax.InputSource" ).init( - createObject( "java", "java.io.StringReader" ).init( htmlContent ) - ); - // Parse the HTML. This will trigger events which the SAX2DOM - // builder will translate into a DOM tree. - tagSoupParser.parse( inputSource ); - // Now that the HTML has been parsed, we have to get a - // representation that is similar to the XML document that - // ColdFusion users are used to having. Let's search for the - // ROOT document and return is. - return( - xmlSearch( saxDomBuilder.getDom(), "/node()" )[ 1 ] - ); - } - // ------------------------------------------------------ // - // ------------------------------------------------------ // - // Parse the "dirty" HTML into a valid XML document. - xhtml = htmlParse( dirtyHtml ); - // Query for the head contents. - headContents = xmlSearch( xhtml, "/html/head/*" ); - // Query for the body contents. - bodyContents = xmlSearch( xhtml, "/html/body/*" ); - // Output the two values. - writeDump( headContents ); - writeDump( bodyContents ); - </cfscript> As you can see, the HTML code is pretty sloppy. And still, we take our HTML document, run it through htmlParse(), and then search the resultant XML document for various elements. When we run the above code, we get the following page output: As you can see, the dirty HTML was successfully parsed into a valid ColdFusion XML document which we were able to search with XPath 2.0 and xmlSearch(). The TagSoup library was able to convert our element and attribute names to lowercase, handle tags that don't require closing (ie. BR and IMG), and close tags that were improperly left open. The TagSoup library, on its own, is nothing new. I tried playing around with it a few years ago, loading it into the ColdFusion context with a Groovy class loader. The difference here is that TagSoup now ships with ColdFusion 10. Of course, now that ColdFusion 10 allows per-application Java Class loading, this becomes much less of an issue. But still, pretty cool! Reader Comments @All, ColdFusion 10 also appears to ship with the NekoHTML parser as well: However, from some brief experimentation, I was getting better results with less effort from the TagSoup parser. Very cool! I love the idea of being able to reliably parse HTML pages into XML data. Really Cool! That's really useful for all your scraping needs! @Ben, This may give XHTML the biggest boost it's ever gotten! Rapid Application Development + cleanup = actual use! @Ben, "Of course, now that ColdFusion 10 allows per-application Java Class loading" What is this new witchcraft you mention ? fact that toString() gives the XML indentation and line breaks. the library. Great post! Robsltc.trax.SAX2DOM" ).init(); is incorrect for my server. How do I find out what is should be? Or what is my issue? Thanks tag. For example <table id="mytable"> will result in an error. Here is also a good article on comparisons: Thanks
https://www.bennadel.com/blog/2341-coldfusion-10---parsing-dirty-html-into-valid-xml-documents.htm
CC-MAIN-2018-22
refinedweb
1,040
65.62
0 Hey people, i was just wondering if anyone knew the code to make a tkinter button... def createExample(self): top=self.winfo_toplevel() top.rowconfigure(0, weight=1) top.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.Button = Button ( self, text=" Example", font=("Arial", 12), bg="white", fg="magenta", cursor="crosshair") self.Button.grid(row=1, column=0, sticky=N+E+S+W) ...and i wanted to know the code that you can click on that button and the value of that button can apper in an entry screen. For example if you made a button that was 1, if you click on it, it displays the number 1 in an entry screen. thanks for any help :):):)
https://www.daniweb.com/programming/software-development/threads/269569/tkinter-button-help
CC-MAIN-2016-44
refinedweb
124
54.29
Getting. Statistical analysis is performed reliably and quickly with statistical software packages. The famous multi-purpose language, Python, has a great collection of libraries and modules to do statistical analysis in a lucid way. In this article, we discuss a widely used statistical tool called ANOVA with hands-on Python codes. THE BELAMY Sign up for your weekly dose of what's up in emerging technology. ANOVA is one of the statistical tools that helps determine whether two or more data samples have significantly identical properties. Let’s assume a scenario- we have different samples collected independently from the same dataset for cross-validation. We wish to know whether the means of the collected samples are significantly the same. Another scenario- we have developed three different machine learning models. We have obtained a set of results, and we wish to know whether the models perform significantly in the same manner. Thus, there are many scenarios in practical applications where we may need to use ANOVA as part of data analytics. ANOVA is the acronym for Analysis of Variance. It analyzes variations among different groups and within those groups of a dataset (technically termed as population). However, there are some assumptions that the data must hold to use ANOVA. They are as follows: - The data follows normal distribution - The variance of data is the same for all groups. - Data among groups are independent of each other. Math concept behind ANOVA and its usage can be explored with the following hands-on Python example. Comparing Means using ANOVA Import the necessary libraries to create the environment. # import libraries import numpy as np import pandas as pd import scipy import statsmodels.api as sm from statsmodels.formula.api import ols from matplotlib import pyplot as plt import seaborn as sns Generate some normally distributed synthetic data using NumPy’s random module. While generating synthetic data, we should ensure that the standard deviation is common for all different methods. # numpy random normal arguments: (mean, std_dev, size) method_1 = np.random.normal(10,3,10) method_2 = np.random.normal(11,3,10) method_3 = np.random.normal(12,3,10) method_4 = np.random.normal(13,3,10) # build a pandas dataframe data = pd.DataFrame({'method_1':method_1, 'method_2':method_2, 'method_3':method_3, 'method_4':method_4}) data.head() Output: Before proceeding further into ANOVA, we should establish a null hypothesis. Whenever we are unable to make a solid mathematical decision, we go for hypothesis testing. ANOVA does follow hypothesis testing. Our null hypothesis (common for most ANOVA problems) can be expressed as: Means of all the four methods are the same. We know very well that the means are mathematically not the same. We set 10, 11, 12 and 13 as the means for the corresponding four methods while generating data. But from a statistical point of view, we make decisions with some level of significance. We set the most common level of significance, 0.05 (i.e. 5% of risk in rejecting the null hypothesis when it is actually true). In other words, if we set a level of significance of zero, it is a mathematical decision – we do not permit errors. In our case, we can reject the null hypothesis without any analysis, because we know that the means are different from each other. However, with many factors affecting the data, we should give some space to accept some statistically significant deviations among data. ANOVA follows F-test (We will define F-statistic shortly). If the probability of F-statistic is less than or equal to the level of significance (0.05, here), we should reject the null hypothesis. Else, we should accept the null hypothesis. Make the data frame to have a single column of values using Pandas’ melt method. df = pd.melt(data, value_vars=['method_1', 'method_2', 'method_3', 'method_4']) df.columns = [ 'treatment', 'value'] # treatment refers to the method df.sample(10) Output: Develop an Ordinary Least Squares model with the melted data. model = ols('value~C(treatment)', data=df).fit() model.summary() Output: We can jump into conclusions with this step itself. The probability score is 0.135, which is greater than 0.05. Hence, we should accept the null hypothesis. In other words, the means of all four methods are significantly the same. However, an ANOVA table can give crystal clear output for better understanding. Obtain the ANOVA table with the following code. anova = sm.stats.anova_lm(model, typ=1) anova Output: Users need to be aware that the terms groups and methods are invariably used in this example. We have come to the conclusion based on the Probability score. However, we can also arrive at the conclusion based on the F-statistic also. We can calculate the critical value of F-statistic with the following code. # arguments: f(numerator degrees of freedom, denominator degrees of freedom) # arguments: ppf(1-level of significance) scipy.stats.f(3,36).ppf(0.95) Output: If the observed F-statistic is greater than or equal to its critical value, we should reject the null hypothesis. Else, if the observed F-statistic is less than its critical value, we should accept the null hypothesis. Here the observed value 1.975314 is less than the critical value 2.86626. Therefore, we accept the null hypothesis. We can visualize the actual data to get some better understanding. sns.set_style('darkgrid') data.plot() plt.xlabel('Data points') plt.ylabel('Data value') plt.show() Output: We can see a great overlap among different data groups. This is exactly where we cannot jump into conclusions in a mathematical way. Statistical tools help take successful business decisions in these tough scenarios. How does Means vary among different groups? Let’s visualize it too. data.mean(axis=0).plot(kind='bar') plt.xlabel('Methods') plt.ylabel('Mean value') plt.show() Output: Though we see some differences in the mean values with human eyes, statistics say there are no significant differences in the mean values! A Major Limitation of ANOVA There is a big problem with the ANOVA method when we reject the null hypothesis. Let’s study that with some code examples. Increase the mean value of method_4 from 13 to 15. # Alter the mean value of method_4 method_1 = np.random.normal(10,3,10) method_2 = np.random.normal(11,3,10) method_3 = np.random.normal(12,3,10) method_4 = np.random.normal(15,3,10) data = pd.DataFrame({'method_1':method_1, 'method_2':method_2, 'method_3':method_3, 'method_4':method_4}) data.head() Output: Melt the data to have single-columned values. df = pd.melt(data, value_vars=['method_1', 'method_2', 'method_3', 'method_4']) df.columns = [ 'treatment', 'value'] df.sample(10) Output: Develop the Ordinary Least Squares model. model = ols('value~C(treatment)', data=df).fit() model.summary() Output: Obtain the ANOVA table. anova = sm.stats.anova_lm(model, typ=1) anova Output: Since the probability score is less than the level of significance, 0.05, we do reject the null hypothesis. It means that at least one mean value is different from the others. But we cannot identify the method or methods whose means are different from the others. This is where ANOVA needs some other methods to bring light upon its decisions. This issue can be tackled with the help of Post Hoc Analysis. Post Hoc Analysis Post Hoc Analysis is also known as the Tukey-Kramer method or the Tukey test or the Multi-Comparison test. Whenever we reject the null hypothesis in an ANOVA test, we explore individual comparisons among the mean values of different groups (methods) using the Post Hoc Analysis. Import the necessary module from the statsmodels library. from statsmodels.stats.multicomp import MultiComparison comparison = MultiComparison(df['value'], df['treatment']) tukey = comparison.tukeyhsd(0.05) tukey.summary() Output: This method performs ANOVA individually between every possible pair of groups. It yields individual decisions with probability scores. Here, the null hypothesis is accepted (means are significantly the same) for the pairs: method_1 and method_2 method_1 and method_3 method_2 and method_3 On the other hand, null hypothesis is rejected (means are significantly different) for the pairs: method_1 and method_4 method_2 and method_4 method_3 and method_4 Hence, we can conclude that methods 1, 2 and 3 possess significantly the same means while method 4 differs from them all. Note: We have generated data with NumPy’s random module without any seed value. Hence, the values and results in these examples are not reproducible. This Colab Notebook has the above code implementation. Wrapping up In this article, we discussed the importance of statistical tools, especially ANOVA. We discussed the concepts of ANOVA with hands-on Python codes. We also studied the limitations of ANOVA and the Post Hoc Analysis method to overcome the same. Now, it is your turn to perform ANOVA with the raw data in your hand!
https://analyticsindiamag.com/a-complete-python-guide-to-anova/
CC-MAIN-2022-33
refinedweb
1,455
51.04
Nov 23, 2016 11:01 AM|sudip_inn|LINK private void button2_Click(object sender, EventArgs e) { int i=77, j=99; // No need to initialize variable Outsample(out i, out j); } public static int Outsample(out int val1, out int val2) { val1 = 5; val2 = 10; return 0; } see the above code and it seems out and ref parameter both are same if i am right then tell me when some one will use out param and when use ref parameter. thanks All-Star 39110 Points Nov 23, 2016 05:33 PM|PatriceSc|LINK Hi, Check the doc at : "This is like the ref keyword, except that ref requires that the variable be initialized before it is passed." And so using "out" (that you must use both in the declaration and at the call site) allows to show clearly that the input value shouldn't matter at all and that the purpose of this parameter is just to receive an output value returned by this method (in addition to a possible return value). I likely use this quite rarely. Another option could be to return a single object with multiple properties... Contributor 5520 Points Nov 24, 2016 10:09 AM|Eric Du|LINK Hi sudip_inn, According to your code, I introduce the difference and relation of ref and out: 1. you pass i=77 and j=99 to Outsample(), actually, you need set i and j be initialized value in this method. In other word, in this method, can not read passed value, before out value can not pass into method. But ref could pass value into method. 2. if you use ref then pass value to method, and change value in this method, return it and you can get have changed value in Button1_Click event. protected void Button1_Click(object sender, EventArgs e) { int i = 77, j = 99; Outsample(ref i, ref j); Response.Write(i); } public static int Outsample(ref int val1, ref int val2) { int a = val1; int b = val2; return val1; } 3. Summary: ref value can pass into also can outcome. out value only outcome but can not pass into Best Regards, Eric Du All-Star 39110 Points Nov 24, 2016 11:52 AM|PatriceSc|LINK The difference is that : int a; refSample(ref a); won't compile. The compiler sees that "a" was never initialized and complains about that. You are using that because you don't care at all about the initial value of "a" which is anyway defined in the method. So instead you can use : int a; outSample(out a); which compiles fine because by using "out" you are telling to the compiler that the parameter will be changed by the method but that you don't care about the initial value. Similarly with : static void outSample(out int value) { if (value == 1) value += 1; } the compiler complains on value because you told with "out" that you don't care about the initial value and still you are testing this value inside the method body without assiging first a value to this parameter. It complains on the method name because the value must be assigned before leaving the method (and it's not always the case depending on which branch it would take). In short "out" is to mark "output" parameters which could be seen as additional return values for a function. Contributor 5520 Points Nov 24, 2016 12:22 PM|Eric Du|LINK Hi sudip_inn, This sample means that you can pass ref value into Outsample, you define ref i=77, j=99 in click event, you can read i=77 and j=99 in Outsample method. If you define out i and out j in click event, then call Call Outsample with i and j value, you can not read i=77 and j=99, you need initialize variable in this method. But ref and out all can as return value. This is two sentence meanings. protected void Button1_Click(object sender, EventArgs e) { int i = 77, j = 99; Outsample(ref i, ref j); // if you call Outsample(out i, out j;) Response.Write(i); } /*public static int Outsample(out int val1, ref out val2) { you can not get val1 and val2 value, need initialize variable } */ public static int Outsample(ref int val1, ref int val2) { int a = val1; int b = val2; return val1; } Nov 27, 2016 06:18 PM|bnarayan|LINK I agree with @PatriceSc. It is true that initial value doesn’t matter for ‘out’ and it is always intended for getting output whereas ‘ref’ is intended for passing a value as reference. That is why in C# 7 it has been introduced that if we do not need the initial value of ‘out’ parameter then we can also “omit” the declaration of out parameter outside and declare it directly while passing it in the method. C# 7 Example for out using static System.Console; class Program { static void Main(string[] args) { string s = "26-Nov-2016"; if (DateTime.TryParse(s, out DateTime date)) { WriteLine(date); } WriteLine(date); } Nov 28, 2016 08:46 AM|sudip_inn|LINK thanks for your answer. one things still not clear to me that both out and ref works same way but what is true difference in it ? why we need to initialize ref parameter before send it to function ? @Eric Du said :- what he try to said not clear to me. if u understand then please explain it easy way. ref value can pass into also can outcome. out value only outcome but can not pass into i know i am asking very basic question. if possible tell me the true difference between out and ref usage. thanks Nov 28, 2016 04:46 PM|bnarayan|LINK Ref Vs Out Let’s try to understand the same thing with example private void DoSomething(int x, int y) { } private void DoSomething _Ref(ref int x, ref int y) { } private void DoSomething_Out(out int x,out int y) { } Build the above code you will get the error for DoSomething_Out() Error CS0177 The out parameter 'x' must be assigned to before control leaves the current method Error CS0177 The out parameter 'x' must be assigned to before control leaves the current method Ignore it right now and try to build += 15; y += 15; } you will still get the error for DoSomething_Out() Use of unassigned out parameter 'x' Use of unassigned out parameter 'y' Because it is not going to access the variable value whatever has been passed from outside and you must assign those variables inside the method before using it. Now build the = 50; y = 55; x += 15; y += 15; } It will be built successfully. Now start from beginning and review it and try to understand the behavior and let me know if you have any query. 10 replies Last post Nov 29, 2016 11:20 AM by sudip_inn
https://forums.asp.net/t/2110359.aspx?Regarding+usage+of+out+ad+ref+parameter
CC-MAIN-2018-05
refinedweb
1,139
62.72
The Volta quickstart as well as Wes' blog post Volta: Redefining Web Development tier-split an application that runs entirely in the browser. The refactoring yields a distributed application comprising a browser-resident client and a service. This transformation showcases two aspects of the Volta recompiler at the same time: architectural reshaping and retargeting. However they are orthogonal. Let me focus on the former and set the latter aside. I'll do that through tier-splitting a WinForms application. In Visual Studio 2008 create a new project of type Volta Windows Forms Application (highlighted below): Then with the forms designer put together a very simple form. With a button labeled Compute Fn it should be clear where I'm headed :) Clear the value of of label2 in the properties pane; this is where the application will display the results. Next add a class Computation to the project and add a method that computes Fibonacci numbers. Yes there are smarter ways of implementing it :) namespace VoltaWindowsFormsApplication1{ public class Computation { public int Fibonacci(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return Fibonacci(n - 1) + Fibonacci(n - 2); } }} namespace VoltaWindowsFormsApplication1{ public class Computation { public int Fibonacci(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return Fibonacci(n - 1) + Fibonacci(n - 2); } }} Then add an instance variable of type Computation to the Form1 class and initialize it in the ctor: public partial class Form1 : Form{ Computation computation; public Form1() { InitializeComponent(); computation = new Computation(); }} public partial class Form1 : Form{ Computation computation; public Form1() { InitializeComponent(); computation = new Computation(); }} Finally wire the button such that clicking on it parses the input, validates it, invokes the computation, and displays the result: private void button1_Click(object sender, EventArgs e) { int n; if (int.TryParse(textBox1.Text, out n) && n >= 0) { label2.Text = string.Format("F({0})={1}", n, computation.Fibonacci(n).ToString()); } else label2.Text = "Invalid input"; }} private void button1_Click(object sender, EventArgs e) { int n; if (int.TryParse(textBox1.Text, out n) && n >= 0) { label2.Text = string.Format("F({0})={1}", n, computation.Fibonacci(n).ToString()); } else label2.Text = "Invalid input"; }} So far so good, no voltage here. Let's flip the switch and plug in the rewriter. After making sure that Enable Volta tiersplitter is checked on the project's property page, navigate or open the Computation class, right-click on the class and select Tier-split To Run At Server from the Refactor menu. The only thing that this refactoring does it to add a custom attribute aimed at the class (as well as add a few references to the project but those aren't source level changes): namespace VoltaWindowsFormsApplication1{ [RunAt("Server")] public class Computation namespace VoltaWindowsFormsApplication1{ [RunAt("Server")] public class Computation Just like the sample from the Getting Started document, this attribute marks the distribution boundary. Volta uses the marker to split the application into two parts, with one part running as a service. Hit F5 and all the needed pieces unfold under the hood. Because the rewriting operates on MSIL Volta doesn't add any new source files or components to your project or solution. This makes it easy to experiment and fine-tune what runs on either side of the fence. At this point I'd like to bring up a key point. There is an important difference between where the tier-splitting happens, and how it happens. People building distributed systems have known for many years about the fallacy of making remote calls look like local calls, and thus setting a trap for the developers. We didn't ignore or forget this insight. Rather, Volta takes over the accidental complexity so Volta developers could focus on putting the distribution boundary at the right place. It's easy to see that the tier-split WinForms application uses a service. Once the Form comes up double-click on the Volta WebServer's electric eel icon that appears in the notification area. Select the Log requests box and then compute a Fibonacci number. The POST appears on the server's log. But for someone who grew up with the Smalltalk browser the debugger provides the best way of looking under the hood. Visual Studio has a first class debugger so let's put it to work. In the Form1 class set a breakpoint in the client code, before the call to Fibonacci: Then in the Computation class set another breakpoint in the Fibonacci method: Ensure that Visual Studio is in the Debug configuration and then hit F5. Enter either 0 or 1 into the text box to avoid having the debugger pop up as the computation recurses. Then click the form's button and examine the call stack. On the first breakpoint (in the form's event handler) the call comes from the client: Resume execution and the second breakpoint (in the Fibonacci method of the Computation class) pops up the debugger. This time the call stack shows a server: At this point the Fibonacci calculator is a distributed application. The network is not involved when the application interacts with the service running in the development server. However this not the case beyond development, where the latencies and delays associated with going over the network are a fact of life. Under those circumstances synchronous method invocation becomes unsuitable. I could make asynchronous calls using delegates. But that's another bit of accidental complexity lurking in the code. So instead let me rely on Volta to generate delegates and inject the BeginInvoke and EndInvoke pair in the code. As Volta's architecture refactoring and retargeting are orthogonal asynchronous invocation is no different than explained in Step 7 in the quickstart, except one small idiosyncrasy due to to the UI thread (more on that shortly). In the Computation class add: [Async]public extern void Fibonacci(int n, Action<int> continuation); [Async]public extern void Fibonacci(int n, Action<int> continuation); If you haven't heard of CPS then think of the last argument as a callback, to be invoked with the result of the asynchronous computation upon its completion. Similar to [RunAtServer], [Async] is just a marker for the rewriter. The extern modifier makes the method visible to the IDE and C# compiler (so IntelliSense and type checking work as with the other methods) without requiring an implementation. Volta will generate this implementation and make it available in the final, rewritten program. Finally modify the event handler to use the asynchronous method. To visualize the asynchronous call the code updates label2 prior to invoking the Fibonacci method, and then updates it again when the method completes. An integer around 37 takes enough milliseconds on my machine such that the result shows up a little after the F(37)= appears. Note that the following code uses a lambda form for the continuation: (f) => { ... } so that's where the => is coming from. In addition, the update happens through the Invoke method to avoid interfering with the UI thread. The argument for the Action ctor is a second lambda form: () => label2.Text = label2.Text + f.ToString()";} Let me bring up another important point. Here Volta hides the accidental complexity associated with asynchronous method invocation, just like it does with tier-splitting. Rather than spending time with BeginInvoke and EndInvoke, you focus on deciding what calls should stay synchronous and what calls should be asynchronous. In effect, Volta provides asynchronous methods through synchronous implementations (such as the initial Fibonacci method) paired with asynchronous declarations (such as attributed method). PingBack from Antes de terminar la semana me encontré con Microsoft Volta (Es que, de vez en cuando es bueno ir por A typical Volta application comprises client and server elements. For a web application (Volta also works Listen now! On today's show we talk to Live Labs Program Manager Dragos Manolescu [ bio * ] on the basics
http://blogs.msdn.com/dragoman/archive/2007/12/07/tier-split-refactoring-winforms-applications-with-volta.aspx
crawl-002
refinedweb
1,307
52.49
Name: dbT83986 Date: 02/10/99 If I do anything vaguely low-level with Java's primitive types, I end up with some powers of two in my code. Would it not be clearer (esp. for novice programmers) to have constants such as Integer.NUMBEROFBITS rather than having to bear the actual numbers in mind? And though I can do without the above, it'd be nice to have bitmasks for IEEE floating-point, such as constants called e.g. SIGN, MANTISSA and EXPONENT in classes Float and Double (of type int and long respectively, and so accessible via floatToIntBits and doubleToLongBits). And having a constants so I don't have to remember that e.g. doubles have 53 bits precision would be nice too. (I see that the Win32 JDK has a class FloatDecimal with these constants already in: could they be moved/copied to some public classes?) (Review ID: 35635) ======================================================================
https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4210457
CC-MAIN-2019-43
refinedweb
152
74.08
JAVA Developer's Guide Chapter 12 Portable Software and the java.lang Package CONTENTS - The Object and Class Classes - The ClassLoader, SecurityManager, and Runtime Classes - The System Class - Wrapped Classes - The Math Class - The String and StringBuffer Classes - Threads and Processes - The Compiler Class - Exceptions and Errors - Summary In this you'll learn how to use the java.lang package. This package contains the core API classes of the JDK. It includes the Object class, which is the top class in the Java class hierarchy, and the Class class, which provides runtime class information for all Java objects. You'll learn about classes that control the operation of the Java runtime system and about the all-important System class. You'll also learn how "wrapped" classes are used to convert primitive data types into usable objects. By the time you have completed this , you will have been introduced to all the classes contained in the java.lang package. The Object and Class Classes Object and Class are two of the most important classes in the Java API. The Object class is at the top of the Java class hierarchy. All classes are subclasses of Object and therefore inherit its methods. The Class class is used to provide class descriptors for all objects created during Java program execution. Object The Object class does not have any variables and has only one constructor. However, it provides 11 methods that are inherited by all Java classes and that support general operations that are used with all objects. For example, the equals() and hashCode() methods are used to construct hash tables of Java objects. Hash tables are like arrays, but they are indexed by key values and dynamically grow in size. They make use of hash functions to quickly access the data that they contain. The hashCode() method creates a hash code for an object. Hash codes are used to quickly determine whether two objects are different. You learn more about hash tables in Chapter 14, "Useful Tools in the java.util Package." The clone() method creates an identical copy of an object. The object must implement the Cloneable interface. This interface is defined within the java.lang package. It contains no methods and is used only to differentiate cloneable from noncloneable classes. The getClass() method identifies the class of an object by returning an object of Class. You'll learn how to use this method in the next programming example. (See the "A Touch of Class" section.) The toString() method creates a String representation of the value of an object. This method is handy for quickly displaying the contents of an object. When an object is displayed, using print() or println(), the toString() method of its class is automatically called to convert the object into a string before printing. Classes that override the toString() method can easily provide a custom display for their objects. The finalize() method of an object is executed when an object is garbage-collected. The method performs no action, by default, and needs to be overridden by any class that requires specialized finalization processing. The Object class provides three wait() and two notify() methods that support thread control. These methods are implemented by the Object class so that they can be made available to threads that are not created from subclasses of class Thread. The wait() methods cause a thread to wait until it is notified or until a specified amount of time has elapsed. The notify() methods are used to notify waiting threads that their wait is over. Class The Class class provides eight methods that support the runtime processing of an object's class and interface information. This class does not have a constructor. Objects of this class, referred to as class descriptors, are automatically created and associated with the objects to which they refer. Despite their name, class descriptors are used for interfaces as well as classes. The getName() and toString() methods return the String containing the name of a class or interface. The toString() method differs in that it prepends the string class or interface, depending on whether the class descriptor is a class or an interface. The static forName() method is used to obtain a class descriptor for the class specified by a String object. The getSuperclass() method returns the class descriptor of the superclass of a class. The isInterface() method identifies whether a class descriptor applies to a class or an interface. The getInterface() method returns an array of Class objects that specify the interfaces of a class, if any. The newInstance() method creates an object that is a new instance of the specified class. It can be used in lieu of a class's constructor, although it is generally safer and clearer to use a constructor rather than newInstance(). The getClassLoader() method returns the class loader of a class, if one exists. Classes are not usually loaded by a class loader. However, when a class is loaded from outside the CLASSPATH, such as over a network, a class loader is used to convert the class byte stream into a class descriptor. The ClassLoader class is covered later in this . A Touch of Class In order to give you a feel for how the Object and Class methods can be used, let's create and run a small program called ClassApp. If you have not already done so, create a ch12 directory to be used for this lesson. The program's source code is shown in Listing 12.1. Listing 12.1. The source code of the ClassApp program. import java.lang.System; import java.lang.Class; import jdg.ch05.Point; import jdg.ch06.CGTextPoint; public class ClassApp { public static void main(String args[]) { CGTextPoint p = new CGTextPoint(new Point(7,11)); Object obj = new Object(); Class cl = p.getClass(); Class objcl = obj.getClass(); do { describeClass(cl); cl = cl.getSuperclass(); } while(cl!=objcl); } public static void describeClass(Class classDesc){ System.out.println("Class: "+classDesc.getName()); System.out.println("Superclass: "+classDesc.getSuperclass().getName()); Class interfaces[] = classDesc.getInterfaces(); for(int i=0;i<interfaces.length;++i) System.out.println("has interface: "+interfaces[i].getName()); System.out.println(); } } The program shows how the Object and Class methods can be used to generate runtime class and interface information about an arbitrary object. It creates an instance of class CGTextPoint by importing the classes developed in Chapters 5, "Classes and Objects," and 6, "Interfaces." It also creates a generic instance of class Object in order to obtain the class descriptor of that class. The following lines of code use the Object getClass() method to obtain the class descriptors of the CGTextPoint and Object classes: Class cl = p.getClass(); Class objcl = obj.getClass(); These class descriptors are instances of Class. They are used in a simple do loop. The loop invokes the describeClass() method for the class identified by cl and then assigns cl to its superclass. The loop repeats until cl becomes the class descriptor for Object. The describeClass() method uses the getName() method to get the name of the class and its superclass. The describeClass() method displays this information to the console. It uses the getInterfaces() method to get all interfaces implemented by a class and the getName() method to get and display the name of each interface. The program's output is as follows: Class: jdg.ch06.CGTextPoint Superclass: jdg.ch05.CGPoint has interface: jdg.ch06.CGTextEdit Class: jdg.ch05.CGPoint Superclass: jdg.ch05.CGObject Class: jdg.ch05.CGObject Superclass: java.lang.Object It steps up the class hierarchy from CGTextPoint to CGObject to display information about each class. See if you can modify the program to work with objects of other classes. You can do this by assigning the class of these objects to the cl variable in the main() method. The ClassLoader, SecurityManager, and Runtime Classes The ClassLoader, SecurityManager, and Runtime classes provide a fine level of control over the operation of the Java runtime system. However, most of the time you will not need or want to exercise this control because Java is set up to perform optimally for a variety of applications. The ClassLoader class allows you to define custom loaders for classes that you load outside of your CLASSPATH-for example, over a network. The SecurityManager class allows you to define a variety of security policies that govern the accesses that classes may make to threads, executable programs, your network, and your file system. The Runtime class provides you with the capability to control and monitor the Java runtime system. It also allows you to execute external programs. ClassLoader Classes that are loaded from outside CLASSPATH require a class loader to convert the class byte stream into a class descriptor. ClassLoader is an abstract class that is used to define class loaders. It uses the defineClass() method to convert an array of bytes into a class descriptor. The loadClass() method is used to load a class from its source, usually a network. The resolveClass() method resolves all the classes referenced by a particular class by loading and defining those classes. The findSystemClass() method is used to load classes that are located within CLASSPATH and, therefore, do not require a class loader. SecurityManager The SecurityManager class is an abstract class that works with class loaders to implement a security policy. It contains several methods that can be overridden to implement customized security policies. This class is covered in Chapter 39, "Java Security," which gets into the details of Java security. For right now, just be aware that it is in java.lang. Runtime The Runtime class provides access to the Java runtime system. It consists of a number of methods that implement system-level services. The getRuntime() method is a static method that is used to obtain access to an object of class Runtime. The exec() methods are used to execute external programs from the Java runtime system. The exec() methods provide a number of alternatives for passing parameters to the executed program. These alternatives are similar to the standard C methods for passing command-line and environment information. The exec() methods are subject to security checking to ensure that they are executed by trusted code. See Chapter 39 for more information about runtime security checking. The exit() method is used to exit the Java runtime system with an error code. It is similar to the exit function found in standard C libraries. The totalMemory(), freeMemory(), and gc() methods are used to obtain information about and control the memory used by the runtime system. The totalMemory() method identifies the total memory available to the runtime system. The freeMemory() method identifies the amount of free (unused) memory. The gc() method is used to run the garbage collector to free up memory allocated to objects that are no longer being used. In general, you should not use the gc() method, but rather let Java perform its own automated garbage collection. The getLocalizedInputStream() and getLocalizedOutputStream() methods are used to convert local (usually ASCII) input and output streams to Unicode-based streams. The load() and loadLibrary() methods are used to load dynamic link libraries. This is usually performed in conjunction with native methods, which are described in Chapter 38, "Creating Native Methods." The runFinalization() method causes the finalize() method of each object awaiting finalization to be invoked. The traceInstructions() and traceMethodCalls() methods are used to enable or disable instruction and method tracing. You will most likely never need to use any of these methods in your programs. They are used in programs such as the debugger to trace through the execution of Java methods and instructions. Using Runtime Most of the methods provided by Runtime are not typically used in application programs. However, some methods are pretty useful. The program in Listing 12.2 shows how the Runtime methods can be used to display memory status information. Listing 12.2. The source code of the RuntimeMemApp program. import java.lang.System; import java.lang.Runtime; import java.io.IOException; public class RuntimeMemApp { public static void main(String args[]) throws IOException { Runtime r = Runtime.getRuntime(); System.out.println(r.totalMemory()); System.out.println(r.freeMemory()); } } This program uses the static getRuntime() method to get an instance of Runtime that represents the current Java runtime system. The totalMemory() method is used to display the total number of bytes of runtime system memory. The freeMemory() method is used to display the number of bytes of memory that are unallocated and currently available. When you run the program, you should get results that are similar to the following: 3145720 3135888 Listing 12.3 demonstrates how to use the Runtime exec() method to execute external programs. This example assumes that you are using Windows 95. It will not work with any other Java implementation. However, it can be easily tailored to launch application programs on other operating-system platforms. Listing 12.3. The source code of the RuntimeExecApp program. import java.lang.System; import java.lang.Runtime; import java.io.IOException; public class RuntimeExecApp { public static void main(String args[]) throws IOException { Runtime r = Runtime.getRuntime(); r.exec("C:\\Windows\\Explorer.exe"); } } This program uses getRuntime() to get the current instance of the runtime system and then uses exec() to execute the Windows Explorer. The double backslashes (\\) are Java escape codes for a single backslash (\). When you run this program, it should launch a copy of the Windows Explorer. Under Windows 95, the exec() function works with true Win32 programs. It cannot be used to execute built-in DOS commands. The System Class You are no stranger to the System class because you have used it in several previous programming examples. It is one of the most important and useful classes provided by java.lang. It provides a standard interface to common system resources and functions. It implements the standard input, output, and error streams, and supplies a set of methods that provide control over the Java runtime system. Some of these methods duplicate those provided by the Runtime class. Property-Related Methods The System class provides three property-related methods. Properties are extensions of the Dictionary and Hashtable classes and are defined in the java.util package. A set of system properties is available through the System class that describes the general characteristics of the operating system and runtime system that you are using. The getProperties() method gets all of the system properties and stores them in an object of class Properties. The getProperty(String) method gets a single property, as specified by a key. The setProperties() method sets the system properties to the values of a Properties object. The sample program presented in Listing 12.4 introduces you to these system properties. Security Manager-Related Methods The getSecurityManager() and setSecurityManager() methods provide access to the security manager that is currently in effect. These methods are covered in Chapter 39. Runtime-Related Methods Several of the methods defined for the Runtime class are made available through the System class. These methods are exit(), gc(), load(), loadLibrary(), and runFinalization(). Odds and Ends The arraycopy() method is used to copy data from one array to another. This function provides the opportunity for system-specific memory-copy operations to optimize memory-to-memory copies. The currentTimeMillis() method returns the current time in milliseconds since January 1, 1970. If you want more capable date and time methods, check out the Date class in java.util. The getenv() method is used to obtain the value of an environment variable. However, this method is identified as obsolete in the Java API documentation and can no longer be used. Time and Properties The short program in Listing 12.4 illustrates a few of the methods provided by the System class. If your heyday was in the 1960s, it will allow you to keep track of the number of milliseconds that have elapsed since the good old days. It also gets and displays the System properties. Take a look through these properties to get a feel for the type of information that is provided. Finally, the exit() method is used to terminate the program, returning a status code of 13. Listing 12.4. The source code of the SystemApp program. import java.lang.System; import java.util.Properties; public class SystemApp { public static void main(String args[]) { long time = System.currentTimeMillis(); System.out.print("Milliseconds elapsed since January 1, 1970: "); System.out.println(time); Properties p=System.getProperties(); p.list(System.out); System.exit(13); } } The program generated the following output on my computer: Milliseconds elapsed since January 1, 1970: 825298554460 -- listing properties -- java.home=C:\JAVA\BIN\.. awt.toolkit=sun.awt.win32.MToolkit java.version=1.0 file.separator=\ line.separator= java.vendor=Sun Microsystems Inc. user.name=jamie os.arch=x86 os.name=Windows 95 java.vendor.url= user.dir=c:\java\jdg\ch12 java.class.path=.;c:\java;c:\java\lib\classes.zip;C:\... java.class.version=45.3 os.version=4.0 path.separator=; user.home=\home\jamie Wrapped Classes Variables that are declared using the primitive Java types are not objects and cannot be created and accessed using methods. Primitive types also cannot be subclassed. To get around the limitations of primitive types, the java.lang package defines class wrappers for these types. These class wrappers furnish methods that provide basic capabilities such as class conversion, value testing, hash codes, and equality checks. The constructors for the wrapped classes allow objects to be created and converted from primitive values and strings. Be sure to browse the API pages for each of these classes to familiarize yourself with the methods they provide. The Boolean Class The Boolean class is a wrapper for the boolean primitive type. It provides the getBoolean(), toString(), and booleanValue() methods to support type and class conversion. The toString(), equals(), and hashCode() methods override those of class Object. The Character Class The Character class is a wrapper for the char primitive type. It provides several methods that support case, type, and class testing, and conversion. Check out the API pages on these methods. We'll use some of them in the upcoming example. The Integer and Long Classes The Integer and Long classes wrap the int and long primitive types. They provide the MIN_VALUE and MAX_VALUE constants, as well as a number of type and class testing and conversion methods. The parseInt() and parseLong() methods are used to parse String objects and convert them to Integer and Long objects. The Double and Float Classes The Double and Float classes wrap the double and float primitive types. They provide the MIN_VALUE, MAX_VALUE, POSITIVE_INFINITY, and NEGATIVE_INFINITY constants, as well as the NaN (not-a-number) constant. NaN is used as a value that is not equal to any value, including itself. These classes provide a number of type and class testing and conversion methods, including methods that support conversion to and from integer bit representations. The Number Class The Number class is an abstract numeric class that is subclassed by Integer, Long, Float, and Double. It provides four methods that support conversion of objects from one class to another. All Wrapped Up The program in Listing 12.5 shows some of the methods that can be used with the primitive types when they are wrapped as objects. Look up these methods in the API pages for each class and try to figure out how they work before moving on to their explanations. Listing 12.5. The source code of the WrappedClassApp program. import java.lang.System; import java.lang.Boolean; import java.lang.Character; import java.lang.Integer; import java.lang.Long; import java.lang.Float; import java.lang.Double; public class WrappedClassApp { public static void main(String args[]) { Boolean b1 = new Boolean("TRUE"); Boolean b2 = new Boolean("FALSE"); System.out.println(b1.toString()+" or "+b2.toString()); for(int j=0;j<16;++j) System.out.print(Character.forDigit(j,16)); System.out.println(); Integer i = new Integer(Integer.parseInt("ef",16)); Long l = new Long(Long.parseLong("abcd",16)); long m=l.longValue()*i.longValue(); System.out.println(Long.toString(m,8)); System.out.println(Float.MIN_VALUE); System.out.println(Double.MAX_VALUE); } } The program examines some of the more useful methods provided by each of the wrapped classes. It creates two objects of class Boolean from string arguments passed to their constructors. It assigns these objects to b1 and b2 and then converts them back to String objects when it displays them. They are displayed in lowercase, as boolean values are traditionally represented. The program then executes a for loop that prints out the character corresponding to each of the hexadecimal digits. The static forDigit() method of the Character class is used to generate the character values of digits in a number system of a different radix. The static parseInt() and parseLong() methods are used to parse strings according to different radices. In the example, they are used to convert strings representing hexadecimal numbers into Integer and Long values. These values are then multiplied together and converted to a string that represents the resulting value in base 8. This is accomplished using an overloaded version of the toString() method. The sample program concludes by displaying the minimum float value and the maximum double value using the predefined class constants of the Float and Double classes. The program's output is as follows: true or false 0123456789abcdef 50062143 1.4013e-045 1.79769e+308 The Math Class The Math class provides an extensive set of mathematical methods in the form of a static class library. It also defines the mathematical constants E and PI. The supported methods include arithmetic, trigonometric, exponential, logarithmic, random number, and conversion routines. You should browse the API page of this class to get a feel for the methods it provides. The example in Listing 12.6 only touches on a few of these methods. Listing 12.6. The source code of the MathApp program. import java.lang.System; import java.lang.Math; public class MathApp { public static void main(String args[]) { System.out.println(Math.E); System.out.println(Math.PI); System.out.println(Math.abs(-1234)); System.out.println(Math.cos(Math.PI/4)); System.out.println(Math.sin(Math.PI/2)); System.out.println(Math.tan(Math.PI/4)); System.out.println(Math.log(1)); System.out.println(Math.exp(Math.PI)); for(int i=0;i<5;++i) System.out.print(Math.random()+" "); System.out.println(); } } This program prints the constants e and p, |-1234|, cos(p/4), sin(p/2), tan(p/4), ln(1), ep, and then five random double numbers between 0.0 and 1.1. Its output is as follows: 2.71828 3.14159 1234 0.707107 1 1 0 23.1407 0.831965 0.573099 0.0268818 0.378625 0.164485 The random numbers you generate will almost certainly differ from the ones shown here. The String and StringBuffer Classes The String and StringBuffer classes are used to support operations on strings of characters. The String class supports constant (unchanging) strings, whereas the StringBuffer class supports growable, modifiable strings. String objects are more compact than StringBuffer objects, but StringBuffer objects are more flexible. String Literals String literals are strings that are specified using double quotes. "This is a string" and "xyz" are examples of string literals. String literals are different than the literal values used with primitive types. When the javac compiler encounters a String literal, it converts it to a String constructor. For example, the following: String str = "text"; is equivalent to this: String str = new String("text"); The fact that the compiler automatically supplies String constructors allows you to use String literals everywhere that you could use objects of the String class. The + Operator and StringBuffer If String objects are constant, how can they be concatenated with the + operator and be assigned to existing String objects? In the following example, the code will result in the string "ab" being assigned to the s object: String s = ""; s = s + "a" + "b"; How can this be possible if Strings are constant? The answer lies in the fact that the Java compiler uses StringBuffer objects to accomplish the string manipulations. This code would be rendered as something similar to the following by the Java compiler: String s = ""; s = new StringBuffer("").append("a").append("b").toString(); A new object of class StringBuffer is created with the "" argument. The StringBuffer append() method is used to append the strings "a" and "b" to the new object, and then the object is converted to an object of class String via the toString() method. The toString() method creates a new object of class String before it is assigned to the s variable. In this way, the s variable always refers to a constant (although new) String object. String Constructors The String class provides seven constructors for the creation and initialization of String objects. These constructors allow strings to be created from other strings, string literals, arrays of characters, arrays of bytes, and StringBuffer objects. Browse through the API page for the String class to become familiar with these constructors. String Access Methods The String class provides a very powerful set of methods for working with String objects. These methods allow you to access individual characters and substrings; test and compare strings; copy, concatenate, and replace parts of strings; convert and create strings; and perform other useful string operations. The most important String methods are the length() method, which returns an integer value identifying the length of a string; the charAt() method, which allows the individual characters of a string to be accessed; the substring() method, which allows substrings of a string to be accessed; and the valueOf() method, which allows primitive data types to be converted into strings. In addition to these methods, the Object class provides a toString() method for converting other objects to String objects. This method is often overridden by subclasses to provide a more appropriate object-to-String conversion. Character and Substring Methods Several String methods allow you to access individual characters and substrings of a string. These include charAt(), getBytes(), getChars(), indexOf(), lastIndexOf(), and substring(). Whenever you need to perform string manipulations, be sure to check the API documentation to make sure that you don't overlook an easy-to-use, predefined String method. String Comparison and Test Methods Several String methods allow you to compare strings, substrings, byte arrays, and other objects with a given string. Some of these methods are compareTo(), endsWith(), equals(), equalsIgnoreCase(), regionMatches(), and startsWith(). Copy, Concatenation, and Replace Methods The following methods are useful for copying, concatenating, and manipulating strings: concat(), copyValueOf(), replace(), and trim(). String Conversion and Generation There are a number of string methods that support String conversion. These are intern(), toCharArray(), toLowerCase(), toString(), toUpperCase(), and valueOf(). You explore the use of some of these methods in the following example. Stringing Along The program in Listing 12.7 provides a glimpse at the operation of some of the methods identified in the previous subsections. Because strings are frequently used in application programs, learning to use the available methods is essential to being able to use the String class most effectively. Listing 12.7. The source code of the StringApp program. import java.lang.System; import java.lang.String; public class StringApp { public static void main(String args[]) { String s = " Java Developer's Guide "; System.out.println(s); System.out.println(s.toUpperCase()); System.out.println(s.toLowerCase()); System.out.println("["+s+"]"); s=s.trim(); System.out.println("["+s+"]"); s=s.replace('J','X'); s=s.replace('D','Y'); s=s.replace('G','Z'); System.out.println(s); int i1 = s.indexOf('X'); int i2 = s.indexOf('Y'); int i3 = s.indexOf('Z'); char ch[] = s.toCharArray(); ch[i1]='J'; ch[i2]='D'; ch[i3]='G'; s = new String(ch); System.out.println(s); } } This program performs several manipulations of a string s that is initially set to " Java Developer's Guide ". It prints the original string and then prints upper- and lowercase versions of it, illustrating the use of the toUpperCase() and toLowerCase() methods. It prints the string enclosed between two braces to show that it contains leading and trailing spaces. It then trims away these spaces using the trim() method and reprints the string to show that these spaces were removed. The program uses the replace() method to replace the letters 'J', 'D', and 'G' with 'X', 'Y', and 'Z' and prints out the string to show the changes. The replace() method is case sensitive. It uses the indexOf() method to get the indices of 'X', 'Y', and 'Z' within s. It uses toCharArray() to convert the string to a char array. It then uses the indices to put 'J', 'D', and 'G' back in their proper locations within the character array. The String() constructor is used to construct a new string from the character array. The new string is assigned to s and is printed. The program's output is as follows: Java Developer's Guide JAVA DEVELOPER'S GUIDE java developer's guide [ Java Developer's Guide ] [Java Developer's Guide] Xava Yeveloper's Zuide Java Developer's Guide The StringBuffer Class The StringBuffer class is the force behind the scene for most complex string manipulations. The compiler automatically declares and manipulates objects of this class to implement common string operations. The StringBuffer class provides three constructors: an empty constructor, an empty constructor with a specified initial buffer length, and a constructor that creates a StringBuffer object from a String object. In general, you will find yourself constructing StringBuffer objects from String objects, and the last constructor will be the one you use most often. The StringBuffer class provides several versions of the append() method to convert and append other objects and primitive data types to StringBuffer objects. It provides a similar set of insert() methods for inserting objects and primitive data types into StringBuffer objects. It also provides methods to access the character-buffering capacity of StringBuffer and methods for accessing the characters contained in a string. It is well worth a visit to the StringBuffer API pages to take a look at the methods that it has to offer. Strung Out The program in Listing 12.8 shows how StringBuffer objects can be manipulated using the append(), insert(), and setCharAt() methods. Listing 12.8. The source code of the StringBufferApp program. import java.lang.System; import java.lang.String; import java.lang.StringBuffer; public class StringBufferApp { public static void main(String args[]) { StringBuffer sb = new StringBuffer(" is "); sb.append("Hot"); sb.append('!'); sb.insert(0,"Java"); sb.append('\n'); sb.append("This is "); sb.append(true); sb.setCharAt(21,'T'); sb.append('\n'); sb.append("Java is #"); sb.append(1); String s = sb.toString(); System.out.println(s); } } The program creates a StringBuffer object using the string " is ". It appends the string "Hot" using the append() method and the character '!' using an overloaded version of the same method. The insert() method is used to insert the string "Java" at the beginning of the string buffer. Three appends are used to tack on a newline character (\n), the string "This is ", and the boolean value true. The append() method is overloaded to support the appending of the primitive data types as well as arbitrary Java objects. The setCharAt() method is used to replace the letter 't' at index 21 with the letter 'T'. The charAt() and setCharAt() methods allow StringBuffer objects to be treated as arrays of characters. Finally, another newline character is appended to sb, followed by the string "Java is #" and the int value 1. The StringBuffer object is then converted to a string and displayed to the console window. The output of the program is as follows: Java is Hot! This is True Java is #1 Threads and Processes Chapter 8, "Multithreading," provides a detailed description of multithreading in Java. This section briefly describes the classes of java.lang that support multithreading. It also covers the Process class, which is used to manipulate processes that are executed using the System.exec() methods. Runnable The Runnable interface provides a common approach to identifying the code to be executed as part of an active thread. It consists of a single method, run(), which is executed when a thread is activated. The Runnable interface is implemented by the Thread class and by other classes that support threaded execution. Thread The Thread class is used to construct and access individual threads of execution that are executed as part of a multithreaded program. It defines the priority constants, MIN_PRIORITY, MAX_PRIORITY, and NORM_PRIORITY, that are used to control task scheduling. It provides seven constructors for creating instances of class Thread. The four constructors with the Runnable parameters are used to construct threads for classes that do not subclass the Thread class. The other constructors are used for the construction of Thread objects from Thread subclasses. Thread supports many methods for accessing Thread objects. These methods provide the capabilities to work with a thread's group; obtain detailed information about a thread's activities; set and test a thread's properties; and cause a thread to wait, be interrupted, or be destroyed. ThreadGroup The ThreadGroup class is used to encapsulate a group of threads as a single object so that they can be accessed as a single unit. A number of access methods are provided for manipulating ThreadGroup objects. These methods keep track of the threads and thread groups contained in a thread group and perform global operations on all threads in the group. The global operations are group versions of the operations that are provided by the Thread class. Process The Process class is used to encapsulate processes that are executed with the System.exec() methods. An instance of class Process is returned by the Runtime class exec() method when it executes a process that is external to the Java runtime system. This Process object can be destroyed using the destroy() method and waited on using the waitFor() method. The exitValue() method returns the system exit value of the process. The getInputStream(), getOutputStream(), and getErrorStream() methods are used to access the standard input, output, and error streams of the process. Hello Again The simple program in Listing 12.9 actually performs some pretty complex processing. It is provided as an example of some of the powerful things that can be accomplished using the Process class. Listing 12.9. The source code of the ProcessApp program. import java.lang.System; import java.lang.Runtime; import java.lang.Process; import java.io.DataInputStream; import java.io.IOException; public class ProcessApp { public static void main(String args[]) throws IOException { Runtime r = Runtime.getRuntime(); Process p = r.exec("java jdg.ch04.HelloWorldApp"); DataInputStream inStream = new DataInputStream(p.getInputStream()); String line = inStream.readLine(); System.out.println(line); } } The program uses the static getRuntime() method to get the current instance of the Java runtime system. It then uses the exec() method to execute another separate copy of the Java interpreter with the HelloWorldApp program that was developed in Chapter 4, "First Programs: Hello World! to BlackJack." It creates a DataInputStream object, inStream, that is connected to the output stream of the HelloWorldApp program. It then uses inStream to read the output of the HelloWorldApp program and display it on the console window as follows: Hello World! The exec() methods combined with the Process class provide a powerful set of tools by which Java programs can be used to launch and control the execution of other programs. The Compiler Class The Compiler class consists of five static methods that are used to compile Java classes in the rare event that you want to compile classes directly from a program or applet. These methods allow you to build your own customized Java development environment. Exceptions and Errors The java.lang package establishes the Java exception hierarchy and declares numerous exceptions and errors. Errors are used to indicate the occurrence of abnormal and fatal events that should not be handled within application programs. (See Chapter 7, "Exceptions.") The Throwable Class The Throwable class is at the top of the Java error-and-exception hierarchy. It is extended by the Error and Exception classes and provides methods that are common to both classes. These methods consist of stack tracing methods, the getMessage() method, and the toString() method, which is an override of the method inherited from the Object class. The getMessage() method is used to retrieve any messages that are supplied in the creation of Throwable objects. The fillInStackTrace() and printStackTrace() methods are used to add information to supply and print information that is used to trace the propagation of exceptions and errors throughout a program's execution. The Error Class The Error class is used to provide a common superclass to define abnormal and fatal events that should not occur. It provides two constructors and no other methods. Four major classes of errors extend the Error class: AWTError, LinkageError, ThreadDeath, and VirtualMachineError. The AWTError class identifies fatal errors that occur in the Abstract Window Toolkit packages. It is a single identifier for all AWT errors and is not subclassed. The LinkageError class is used to define errors that occur as the result of incompatibilities between dependent classes. These incompatibilities result when a class X that another class Y depends on is changed before class Y can be recompiled. The LinkageError class is extensively subclassed to identify specific manifestations of this type of error. The ThreadDeath error class is used to indicate that a thread has been stopped. Instances of this class can be caught and then rethrown to ensure that a thread is gracefully terminated, although this is not recommended. The ThreadDeath class is not subclassed. The VirtualMachineError class is used to identify fatal errors occurring in the operation of the Java virtual machine. It has four subclasses: InternalError, OutOfMemoryError, StackOverflowError, and UnknownError. The Exception Class The Exception class provides a common superclass for the exceptions that can be defined for Java programs and applets. There are nine subclasses of exceptions that extend the Exception class. These exception subclasses are further extended by lower-level subclasses. Summary In this you have learned how to use the java.lang package. You have taken a tour of its classes and their methods and have written some sample programs that illustrate their use. In the next you'll learn to use the java.io package to perform stream-based I/O to files, memory buffers, and the console window.
http://www.webbasedprogramming.com/JAVA-Developers-Guide/ch12.htm
CC-MAIN-2018-17
refinedweb
6,404
56.86
In building out my ticket tracker application, I realized that I needed to be able to automatically run scripts at certain intervals throughout the week. I wanted my application to execute a call to Stubhub’s API and pull data on events periodically so that I didn’t have to do it myself each day. In looking on Ruby Toolbox, I came across a gem called Whenever that allows you to quickly and easily schedule tasks using a nifty tool called a cron log. Whenever serves as a wrapper for the cron job processor, which is functionality inherent to your operating system that allows for scheduling jobs to run periodically. According to Wikipedia, cron tasks are often used to automate system maintenance or administration, though it can be used for other purposes, like connecting to the Internet or downloading e-mail. Apparently you can set up cron tasks independently of Ruby or any web application; Whenever enables you to manipulate standard functionality of your machine using Ruby code. To get started with Whenever, you need to install the gem. Like any other gem, this is a pretty simple installation process: 1) Set up Whenever gem Once you have the gem installed, you need to “wheneverize” your application. You can do this by going into the root directory of your application and using the following console command: This command creates a “schedule.rb” file in your config folder, which you’ll be using to manage your application’s automated tasks. 2) Create a rake task There are several ways to set up cron tasks to run automatically using Whenever, but I found the simplest way to be to just write a rake task in your Rails app’s tasks folder. The above code takes advantage of a few rake-specific keywords, like namespace, desc and task. The namespace:task combination is how you’ll actually call your rake task - in the Rails rake task “db:migrate”, “db” is the namespace and “migrate” is the task. In this particular instance, I’m using Whenever to parse event data from Stubhub’s API and save them to a database using ActiveRecord. After writing the rake task, I am now able to call the above rake task in my console using: After I set up my rake task, I need to use Whenever to schedule my task. Thankfully, the schedule.rb that Whenever automatically creates in your config folder comes ready with in-file instructions about how to set-up cron tasks: Whenever applies a simple, intuitive domain-specific language (DSL) with a few keywords to schedule tasks (you can find a more thorough run-down in in the gem’s README file. Whenever uses a human-readable syntax that takes the form of the below: “every [x].[minute/hour/day/week/etc.], :at => [time] do” to schedule tasks. The gem has pretty good support for specialized tasks, and even supports scheduling tasks on just weekdays or weekends. In the below code, I’ve told Whenever to run my events:fetch rake task every day at 10:00 pm. I’ve also set the environment to be my development environment and I set a location in my Rails application for both an error log and a default log so that I can get feedback from Whenever just to make sure that it ran correctly. I don’t think the “set :output” line is absolutely necessary, but when I started using Whenever, I wasn’t always sure if the job was running correctly, so I made the rake task output to a log so I could follow the execution path. 3) Update the crontab After setting up the rake task, you need to run following command in the console to tell Whenever to start running your periodic tasks: You should see a result along the lines of: If you want to check that the gem correctly scheduled your cron task, you can use the command “crontab -l” to list all cron tasks. And that should be it! You can now sit back and watch Whenever automatically execute your rake tasks. When you start using Whenever, I would recommend shortening the feedback loop by writing one or two test rake tasks that just print “Hello World” to your cron log every minute. This is what I did just to confirm that the gem was working. Then, I moved progressively onward until I was able to execute large API calls. One word of caution though when using Whenever - be sure you have a general sense of how long your tasks actually take to execute. One rake task I set up took over a minute to execute on its own, and I inadvertantely scheduled the task to run every minute, so naturally a task backlog quickly built up. Even when I stopped the task and updated the crontab, the backlog caused the task to continue to run until it ran out of gas on its own. When all was said and done, I had over 2 million rows of data in my database - much of it duplicative and unwanted. Although I ended up with way too much data, at least I knew that the gem worked!
http://eewang.github.io/blog/2013/03/12/how-to-schedule-tasks-using-whenever/
CC-MAIN-2017-17
refinedweb
868
54.97
TOP 3 Artificial Intelligence advices on how to really lose weight based on knowledge from hundreds of articles (Natural Language Processing techniques with python code) . There are three parts of the article: - Part 1: summary for people interested only in findings - Part 2: technical part with python code - Part 3: theory behind algorithm OK, but what’s Natural Language Processing? In short, NLP (a subfield of AI) is about algorithms that allow to understand human language by computers. For example NLP is used to: - translate foreign languages - help with text searching - create digital assistants (like Siri or Alexa) - spell check - filter spam messages - analyse text (semantics, topics, duplicates) Part 1 Let’s just go to summary with AI findings Note (for a curious reader): the success and behaviour of AI depends on data. In general, the more and better quality data is, the better AI. Here is a list of top 3 things our AI advises to be able to have a six pack ;) Number 1. Top 1 advice Getting regular physical activity Number 2. Top 2 advice Cut back on refined carbs Number 3. Top 3 that is not a straight advice, but actually tries to engage our minds for a change by asking questions to ourselves. Am I willing to change activity habits? Am I willing to change eating habits? Extras. Below “advice” was very common in the 8- 32 positions, that’s why I put it here as extras. intermittent fasting Part 2 Technical part of the article with python code Data I collected 304 articles found via duckduckgo.com search engine by looking for titles like: “ideal diet to lose weight”, “how to lose weight” or like “natural fat reduction diet”. (here, here and here are examples of articles I’ve used). Algorithm For the algorithm I used LexRank, which is available here. Look into the Part 3 to find out more on the theory behind it. Let’s start tutorial code: Loading of data: Python looks for every file with the file extension .txt and append them into one list variable documents = [] DATA_FOLDER = 'data' documents = [] data_path = Path(os.path.join(os.getcwd(), DATA_FOLDER)) for file_path in data_path.files('*.txt'): with file_path.open(mode='rt', encoding='utf-8', errors="ignore") as fp: documents.append(fp.readlines()) Next part is to loop over sentences in every article in the documents list. This makes sure that we will have a proper structures off sentences like: all_example = [‘sentence one’, ‘sentence two’ … ‘sentence xxx’] all = [] for doc in documents: for sentence in doc: all.append(sentence) At the end we are feeding the algorithm and print the results: lxr = LexRank(documents, stopwords=STOPWORDS['en']) summary = lxr.get_summary(all, summary_size=15, threshold=.1) print(summary) If you are interested in more of NLP techniques check out this LINK where I check on how AI understand Steve Jobs legendary speeches. Part 3 Theory behind the algorithm (in short, this will be a separate article) The algorithm used in the code is an unsupervised graph based approach. The main goal is to summarize a text. Here is a very nicely detailed theory. In simple words, it calculates the importance of sentences and picks up the most critical ones. Scoring is based on the concept of eigenvector centrality in a graph representation of sentences. Where sentences x are present at the vertices and wx are weights represented on the edges. A sentence score is based on the number of words, that are most common within a given sentence. In simple words, sentences with the highest score are those with the words that are most frequent. Each sentence is represented as a bag of words vector in the form: example_word = [0, 0, 0, 1, 1, ..., 0, 1, 1] where 1 means a word is present and zero means the opposite. Finally, calculation of centrality is represented by the largest eigenvalue vector of a matrix — more details soon if anyone still read it ;) All the best and have a nice day! Appendix 1. Complete python code from lexrank import STOPWORDS, LexRank import os from path import Path DATA_FOLDER = =15, threshold=.1) print(summary)
https://maciejzalwert.medium.com/artificial-intelligence-advices-on-how-to-really-lose-weight-based-on-knowledge-from-hundreds-of-83f40085fbcd
CC-MAIN-2021-25
refinedweb
687
62.98
C# Interview Questions: Can you answer them all? So you want to land your dream job as a C# programmer? You will need to prove that you know your stuff before any organization will hire you. Here are ten of the most common interview questions that interviewers will use to test your technical knowledge and problem solving skills. Can you answer them all? 1. What are the advantages of C# over C, C++ or Java?. You can review the principles of programming in C# in this online C# .NET – Programming for Beginners course. 2. How are namespaces used in C#? Classes in the .NET framework can be organized using namespaces. The scope of a class is declared using the namespace keyword. You can then include methods from the namespace in your code by including the line “using [namespace];” at the start of your program. 3. What is a constructor? A constructor is the method of a class that is called when an object of that class is created. The constructor initializes class parameters and has the same name as the class. 4. What is a destructor? A destructor deletes an object of the class from memory. It is called when the object is explicitly deleted by the code you write, or when the object passes out of scope, which can happen when the program exits a function. The destructor has the same name as the class, but with a tilde prefix. 5. How are methods overloaded in C#? You can overload methods in C# by specifying different numbers or types of parameters in the method definition. Overloading can help to give your program the flexibility it needs to operate with different types of data input. 6. Why use encapsulation? Encapsulation – combining function definitions and data together into a class – is used to separate parts of the code from the rest of the program. This allows the private data of an object to be hidden from the rest of the program, keep code clean and easy to understand, and allows classes to be reused in other programs. You can learn about good programming technique in this online course. 7. What is the difference between a class and a struct? Whereas classes are passed by reference, structs are passed by value. Classes can be inherited, but structs cannot. Structs generally give better performance as they are stored on the stack rather than the heap. 8. What is the GAC? The acronym GAC stands for Global Assembly Cache. The GAC is where assemblies are stored so that many different applications can share these assemblies. Multiple versions of assemblies can be stored in the GAC, with applications specifying which version to use in the config file. 9. How does .NET help to manage DLLs on a system? When. 10. What types of error can occur in a C# program? The three possible types of C# error are as follows: Syntax error. This type of error, which is identified during compilation, occurs because the programmer has used syntax incorrectly or included a typo in the code. Logic error. This type of error causes the program to do something other than what the programmer intended. The program will output an unexpected result in response to tests. Runtime error. This type of error causes the program to crash or terminate incorrectly. If you can handle these questions, you stand a good chance of getting a job as a C# programmer. If you struggled with any of them, maybe you need to brush up on your C# programming skills? This online course on the fundamentals of C# programming could help. Top courses in C# C# students also learn Empower your team. Lead the industry. Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.
https://blog.udemy.com/c-sharp-interview-questions/
CC-MAIN-2020-29
refinedweb
636
66.44
Im trying to figure out how to read a file that is entered into the command line. I tried using #include <iostream> #include <fstream> #include <cstdlib> #include <string> int main(int argc, char *argv[]) { std::string a; int b, c, d; std::cout << "please enter the name of the file: " << std::endl; std::cin >> a; std::cout << argv[1] << "\n" << argv[0]; std::fstream info(argv[1], std::ios::in); info >> b >> c >> d; std::cout << b << " " << c << " " << d; system("pause"); EXIT_SUCCESS; } but it throws an out of bounds exception trying to access argv[1]. how would I access this normally? is there some trick I didnt learn? the way our teacher explained this to us was that int main(int argc,char *argv[]) read inserted commands from the command line and that argv[0] was always the filename.
https://www.daniweb.com/programming/software-development/threads/462262/homework-help
CC-MAIN-2018-30
refinedweb
139
64.04
Method Overriding happens when a method in a subclass has the same name and type signature as a method in its superclass. When an overridden method is called within a subclass, it will refer to the method defined in the subclass. The method defined by the superclass will be hidden. Consider the following: class Base { int i; Base(int a) { i = a; } void show() { System.out.println("i:" + i); } } class SubClass extends Base { int k; SubClass(int a, int c) { super(a); k = c; } void show() { System.out.println("k: " + k); } } public class Main { public static void main(String args[]) { SubClass subOb = new SubClass(1, 3); subOb.show(); } } The output produced by this program is shown here: k: 3
http://www.java2s.com/Book/Java/0040__Class/What_is_Method_Overriding.htm
CC-MAIN-2014-10
refinedweb
119
64.41
24 November 2009 22:19 [Source: ICIS news] RIBEIRAO PRETO (ICIS news)--Brazilian sugarcane and ethanol producer Pedra Agroindustrial plans to start commercial bioplastics production by late 2012, a company official said on Tuesday. The company plans to build the world`s first sugarcane-based bioplastics facility with a capacity of between 35,000-40,000 tonnes/year, said Pedra administrator Eduardo de Oliveira Brondi. The plastic, poly-3-hydroxybuyrate (PHB), which is compostable, is suited for niche applications such as throw-away products like plastic utensils, as well as cosmetics packaging and potentially medical products, he said at a media event in ?xml:namespace> The PHB plastic can also be mixed with other biopolymers, Brondi added. "We are in talks with universities and companies to develop this bioplastic and introduce it on a commercial scale in three years," he said. The cost of the plant, whose location has yet to be announced, will be "somewhat less than $300m [€201m]," Brondi said. "We are looking for a partner to help us go to market. This could mean a joint venture in operations and distribution. Right now we have no access to the European and Asian markets," he added. Pedra plans to produce the PHB bioplastic directly from sucrose, using a natural bacteria found in the sugarcane plant, and an ethanol solvent. The company currently produces ethanol from sugarcane, with ethanol capacity of 425m litres/year. "We are developing this bioplastic to deliver another value-added product and diversify," said Brond
http://www.icis.com/Articles/2009/11/24/9266890/brazil-pedra-to-build-sugarcane-bioplastics-plant-by.html
CC-MAIN-2014-35
refinedweb
250
51.48
JEP 196: Nashorn Optimistic Typing Summary Improve Nashorn performance by making assumptions about specific types used in arithmetic and array indexing operations, by being prepared to recover when those assumptions prove incorrect, and by improving the HotSpot JVM's ability to optimize non-Java bytecode. Goals Ensure, by guessing types, that bytecode generated by Nashorn contains as many primitive unboxed operations as possible and that runtime libraries in Nashorn use that fact. Ensure, by guessing types, that bytecode generated by Nashorn uses as much Java integer arithmetic as possible. The resulting performance must be stable. We cannot degrade over time or measure peak performance only. This would block Nashorn as an industrial strength product. Ensure that bytecode generated by Nashorn can revert optimistic assumptions of the above type with an continuation passing/exception throwing mechanism. This is necessary as you can't just switch out an integer instruction to, e.g., a double instruction in bytecode without causing verify errors and having to modify a method on the fly. Ensure that the built in library functions in Nashorn are optimal Java and use primitive types well. Ensure that the JVM does a much better job of optimizing "alien" (non-Java) bytecode for example from Nashorn or JRuby, which has similar problems. Non-goals This is not an effort that can be targeted by "we must be X% of the performance of a native JavaScript runtime like v8" as the areas of optimization are many an varying. The initial phase of the implementation will be considered successful if it adds no more than acceptable overhead to warmup and speeds up common JavaScript benchmarks orders of magnitude, as the technology promises, and causes no regressions on benchmarks targeting unexplored performance areas. Motivation The Nashorn JavaScript runtime needs to cooperate with the JVM to produce more highly performant code. Native JavaScript runtimes typically outperform Nashorn on many tasks, such as pure number crunching. We need to do our best to make our on-top-of-the-JVM bytecode based solution approach that performance to as large an extent as possible. This effort should take Nashorn performance closer to (but probably not past, in its first iteration) native JavaScript runtime performance. Using only Object operations ("a"-prefixed-bytecodes) and invokedynamic produces bytecode that runs too slowly on HotSpot, even though it conservatively implements JavaScript correctly. We are not sure that a world containing only boxed objects and invokedynamics will ever be fast, but there needs to be some exploration of this in the JIT as well. We need to attack this from two ways - generating bytecode that contains as much primitives as possible and being able to revert code when an assumption about primitive types fails. HotSpot also needs to get better at optimizing non-Java bytecode, mainly constructs around invokedynamic and in java.lang.invoke. Description We propose the following solution, a two-fold one, for Nashorn and the JVM respectively. Note that this is to some part speculation of what is feasible to do in the bytecode space and what the JVM will be able to optimize. Thus, there is still some research scope, both for Nashorn and the JVM in this proposal. For Nashorn We know that hardcoding explicit types at compile time gives us a significant performance boost of the resulting bytecode. An interesting thesis project would be to code up a TypeScript frontend for Nashorn to show this concept. This is something that should be done anyway in the interest of dynamic language implementations on the JVM. Creating optimistic methods We need to generate optimistic methods based on callsite types known at runtime (code for this is in place already but disabled). That is, if a method is called with integer parameters, we can generate a specialized version for that method. Gradual deoptimization We also need to generate intra-method code that is optimistic, i.e., use integer additions even when the compiler can't statically prove that we are dealing with ints, assuming that in fact we are. If we are wrong we need to be able to generate a new version of the code that no longer holds the wrong assumption (and is thus somewhat deoptimized compared to the previous one). We also need to interrupt the execution of the wrong code and continue execution from that point in the new code. For that, we need a continuation-based on-stack-code-replacement mechanism implemented purely using existing JVM capabilities (bytecode and method handles). For a detailed explanation of how optimistic types would work, please refer to Lagergren/JVMLS 2013 Rationale With JavaScript, it is more often than not impossible to precisely infer the data type of many expressions statically. Such expressions can conservatively be treated as Objects, but such treatment severely reduces the speed of execution. By starting out with the computationally fastest types and doing just-in-time gradual deoptimization to slower types, we end up with the fastest code shape that can operate on the given input. Primitive field representation Field representation in Nashorn (objects in the scope are represented as fields in Java classes) needs to be modified to be something else than just "Object". We have experimented with a pair of long/Object fields, using the long for all primitive types, and the Objects for non primitives. Microbenchmarks have shown that this gives us significant performance improvements in statically provable primitive types, but in the general case, again we have too little information for speedup. This will most likely be much, much better if we mate it with the optimistic approach, and early experiments have confirmed this. We should also, in the interest of memory overhead, investigate the earlier POC for sun.misc.TaggedArray that is a "both reference and primitive, either / or" shortcut to get around the Object constraints. Warmup is slow For warmup we might need to do lazy code generation, which is already implemented but not enabled. For some projects, like "npm" in the node.js to Java port, we have shown that lazy code generation indeed gives us significant startup performance. The JVM needs to do a lot of warmup work too, though: see below. Classic IR optimizations We can do some classic code optimizations in the byte code, because we know more than the VM. For example, in the loop var sum = 0; for (i = 0; i < 10; x++) { sum += y; } y might be a method with side effects and valueOf overridden, but if we check that before the loop we can turn the code into var sum = 0; var ytmp = y; //which will throw UnwarrantedOptimismException i y is not a nice primitive for (i = 0; i < 10; x++) { sum += ytmp; } Use def analysis We also need to superimpose a CFG on top of the AST to be able to do better use/def chains, which would enable us to get rid of assumptions like if (x) { z = y & f; operation_on_z(z) } else { z = "string"; } so that we can use z as an int in the true case statically, which we can, but right now, we conservatively assume z to be an Object due to the else case throughout the entire method. See Söderberg et al, who describe a similar methodology For the JVM Intrinsics for exact math The various java.lang.Math operations for exact arithmetic (which throw ArithmethicException on overflow) must be intrinsified. Every optimistic JavaScript addition will have to check for overflow using this mechanism, and unless it compiles to just an arithmetic operation and a jump-on-overflow instruction, the overhead will be too great. This is needed to preserve JavaScript semantics. Invoke The MethodHandle.invoke (not invokeExact) case (used to implement, e.g., apply) needs to be faster. According to John Rose, no optimization has taken place there so far, but it is very common that boxing gets in the way. The JRockit implementation of invokedynamic could turn the test method from the example: public class Test { private final static MethodHandle CALC = MethodHandles.publicLookup().findStatic(Test.class, "calc", int.class, int.class, Object.class); static int test() throws Throwable { MethodHandle mh = CALC; Object aString = "A"; int a = mh.invoke(1, aString); int b = mh.invoke(2, "B"); Integer c = mh.invoke((Integer)3, 3); return a+b+c; } static int calc(int x, Object o) { return x + o.hashCode(); } } into a simple return 140. For HotSpot to do the same, an improvement at least to the generic invoke case is required. Source: Fredrik Öhrström's talk from JavaOne 2010 Source: Fredrik Öhrström's blog java.lang.invoke and LambdaForms The LambdaForms implementation needs to be improved. They contribute to a lot of bytecode generation which makes warmup an issue (even more than just having a bootstrap method per invokedynamic, which is unavoidable). This can probably be alleviated with lambda form caching. JIT profile information must not be polluted by this, though. Lambda form interpretation overhead is another issue that we frequently bump into. Given that Nashorn reaches a steady state, there should be no more MethodHandles created and no more lambda forms interpreted. Cached lambda forms should be retrieved as their compiled versions upon trying to reinterpret them so that they never are interpreted again if they have once been compiled. Furthermore, we have to ensure that all combinators in java.lang.invoke have a fast path that avoids boxing or apply-like semantics. Currently, the catchException combinator is an example of something we commonly use that needs that required optimization. Other examples probably exist, especially in the cases that take many parameters. Better type analysis is needed Early experiments show that me miss optimization opportunities to inline virtual dispatch if type analysis is too conservative. As JavaScript uses plenty of type guards to due to its dynamic nature, this must be addressed. What we need to do in the JVM has been less explored, and we will require at least one full time compiler team resource to help us here. Testing For semantic correctness the standard Nashorn test suites will do. For performance verification existing benchmarks will do, and should be augmented with a microbenchmark suite that tests invalidations of optimistic assumptions. Any torture tests that are run for a long time by SQE should still run to ensure that no reasource leakage is introduced. Risks and Assumptions The main risk is that the JIT still won't be able to generate efficient code from our optimistic type information. A risk is that bytecode might prove to be a too narrow representation for efficient implementations of dynamic languages. We might need to be a lot more explicit with our generated code, possibly inventing a mechanism to communicate more information to HotSpot's JITs than can be done with the current bytecode format. An existing example of a system that can talk more directly with the JIT is the Truffle project at Oracle Labs that tells the Graal compiler through annotations in the Java based interpreter which assumptions to make. Experiments have shown that this indeed can produce very good peak performance. In the long run LambdaForms may have to be totally rewritten and replaced with something else. The JRockit JVM basically just generated IR for a callsite and fed it back to the JIT compiler, which enabled all its optimizations like constant propagation and unboxing removal to run transparently on the callsite. This is not as simple in C2, due to its various issues with graph splicing, platform dependencies and global dependencies. Finally, as code generation becomes optimistic, our warmup time will increase. Dependences The Hotspot JITs. HotSpot code generation improvements. Efficient MethodHandles implementation. Impact There are no compatibility problems, as far as we can tell. Given that footprint and warmup are kept down according to the above, this should be a drop in replacement for current Nashorn versions.
https://openjdk.java.net/jeps/196
CC-MAIN-2021-49
refinedweb
1,968
51.58
HoughLinesP vastly different in Python and C++ Hi all, I’ve spent some time to debug a pole detector i wanted to build on basis of the probabilistic line transform. The results i got from my python code, using Opencv 2.4.x as well as 3.0.0-beta, always looked just so bad. So i made what i hope to be a kind of self-contained example… Python #!/usr/bin/python import cv2 import numpy as np import sys src = cv2.imread(sys.argv[1], 0) dst = cv2.Canny(src, 50, 200, 3) color_dst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR) lines = cv2.HoughLinesP(dst, 1, np.pi/180, 80, 30, 10) for x1,y1,x2,y2 in lines[0]: cv2.line(color_dst, (x1,y1), (x2,y2), (0,255,0), 3, 8) cv2.imwrite("test_py.jpg", color_dst) C++ #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc/types_c.h> #include <iostream> ); std: ); } imwrite( "test_cpp.jpg", color_dst ); return 0; } Results I’ve taken the example image from the OpenCV docs for HoughLinesP, as this looked to me like a good tasting ground… Input Image C++ Result 2.4.9+3.0.0-beta (expected) Python 2.7.9 OpenCV 2.4.9 (broken?) Python 2.7.9 OpenCV 3.0.0-beta (totally broken?) As you can see, in Python with OpenCV 2.4.9 (3.0.0-beta looks worse!), the resulting lines are more, shorter, generally more clutter-y as compared with the C++ version. I’ve also checked the Canny output (visually), and it looks like it’s the same. Did i make any mistake? If not, how can this happen? I thought that python bindings are generated using an automated wrapper generator (swig?), so the code run in the background should be the same, right? Any hints or tips on this would be greatly appreciated!
https://answers.opencv.org/question/55496/houghlinesp-vastly-different-in-python-and-c/
CC-MAIN-2021-10
refinedweb
310
71.71
A callback. Add this code at the end of such file: static void __empty2() { // Empty } void tick_hook(void) __attribute__ ((weak, alias("__empty2"))); Then we need to declare our callback in Arduino.h. Look for the line void yield(void); and write after it: void tick_hook( void ); It’s supposed that our callback is going to be called in every system tick, so look for timer 0 ISR function in wiring.c: #if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) ISR(TIM0_OVF_vect) #else ISR(TIMER0_OVF_vect) #endif { and write at its end the call to our callback: tick_hook(); Finally, we need to write the body of our callback. My first attempt was to determine the tick period, so in the main source code I wrote: void tick_hook() { static bool ledState = false; // should exist a toggle function? Hope so! if( ledState ) { digitalWrite(LED_BUILTIN, HIGH); ledState = false; } else { digitalWrite(LED_BUILTIN, LOW); ledState = true; } } The result was that our callback is called every one millisecond, as seen in the next image: From here we can do whatever is required in our application using the system-tick. Just remember, any code inside an ISR should be as short and fast as possible. Update: A complete example! /*Copyright (C) * 2018 - fjrg76 at hotmail: HeartBeat //---------------------------------------------------------------------- template<const size_t Ticks, const uint8_t Pin> class HeartBeat { public: HeartBeat(); void Toggle(); private: bool pinState; size_t ticks; }; template<const size_t Ticks, const uint8_t Pin> HeartBeat<Ticks, Pin>::HeartBeat() : pinState{ false }, ticks{ Ticks } { pinMode(Pin, OUTPUT); } template<const size_t Ticks, const uint8_t Pin> void HeartBeat<Ticks, Pin>::Toggle() { --ticks; if( ticks == 0 ) { ticks = Ticks; pinState = pinState ? false : true; digitalWrite( Pin, pinState ); } } HeartBeat<500, LED_BUILTIN> heartBeat; //---------------------------------------------------------------------- // Our callback //---------------------------------------------------------------------- void tick_hook() { heartBeat.Toggle(); // the built-in led is toggled every 500 milliseconds } void setup() { // empty } void loop() { // empty } In the console write: make make upload Greetings! 4 respuestas para “System-tick for the Arduino platform”
https://arduinoforadvanceddevelopers.wordpress.com/2018/03/12/system-tick-for-the-arduino-platform/
CC-MAIN-2021-31
refinedweb
309
53.85
Tempest Coding Guide¶ - Step 1: Read the OpenStack Style Commandments - Step 2: Read on Tempest Specific Commandments¶ - [T102] Cannot import OpenStack python clients in tempest/api & - tempest/scenario tests - [T104] Scenario tests require a services decorator - [T105] Tests cannot use setUpClass/tearDownClass - [T106] vim configuration should not be kept in source files. - [T107] Check that a service tag isn't in the module path - [T108] Check no hyphen at the end of rand_name() argument - [T109] Cannot use testtools.skip decorator; instead use - decorators.skip_because from tempest.lib - [T110] Check that service client names of GET should be consistent - [T111] Check that service client names of DELETE should be consistent - [T112] Check that tempest.lib should not import local tempest code - [T113] Check that tests use data_utils.rand_uuid() instead of uuid.uuid4() - [T114] Check that tempest.lib does not use tempest config - [N322] Method's default argument shouldn't be mutable Test Data/Configuration¶ - Assume nothing about existing test data - Tests should be self contained (provide their own data) - Clean up test data at the completion of each test - Use configuration files for values that will vary by environment Exception Handling¶ According to the The Zen of Python the Errors should never pass silently. Tempest usually runs in special environment (jenkins gate jobs), in every error or failure situation we should provide as much error related information as possible, because we usually do not have the chance to investigate the situation after the issue happened. In every test case the abnormal situations must be very verbosely explained, by the exception and the log. In most cases the very first issue is the most important information. Try to avoid using try blocks in the test cases, as both the except and finally blocks could replace the original exception, when the additional operations leads to another exception. Just letting an exception to propagate, is not a bad idea in a test case, at all. Try to avoid using any exception handling construct which can hide the errors origin. If you really need to use a try block, please ensure the original exception at least logged. When the exception is logged you usually need to raise the same or a different exception anyway. Use of self.addCleanup is often a good way to avoid having to catch exceptions and still ensure resources are correctly cleaned up if the test fails part way through. Use the self.assert* methods provided by the unit test framework. This signals the failures early on. Avoid using the self.fail alone, its stack trace will signal the self.fail line as the origin of the error. Avoid constructing complex boolean expressions for assertion. The self.assertTrue or self.assertFalse without a msg argument, will just tell you the single boolean value, and you will not know anything about the values used in the formula, the msg argument might be good enough for providing more information. Most other assert method can include more information by default. For example self.assertIn can include the whole set. It is recommended to use testtools matcher for the more tricky assertions. You can implement your own specific matcher as well. If the test case fails you can see the related logs and the information carried by the exception (exception class, backtrack and exception info). This and the service logs are your only guide to finding the root cause of flaky issues. Test cases are independent¶ Every test_method must be callable individually and MUST NOT depends on, any other test_method or test_method ordering. Test cases MAY depend on commonly initialized resources/facilities, like credentials management, testresources and so on. These facilities, MUST be able to work even if just one test_method is selected for execution. Service Tagging¶ Service tagging is used to specify which services are exercised by a particular test method. You specify the services with the tempest.test.services decorator. For example: @services('compute', 'image') Valid service tag names are the same as the list of directories in tempest.api that have tests. For scenario tests having a service tag is required. For the api tests service tags are only needed if the test method makes an api call (either directly or indirectly through another service) that differs from the parent directory name. For example, any test that make an api call to a service other than nova in tempest.api.compute would require a service tag for those services, however they do not need to be tagged as compute. Test fixtures and resources¶ Test level resources should be cleaned-up after the test execution. Clean-up is best scheduled using addCleanup which ensures that the resource cleanup code is always invoked, and in reverse order with respect to the creation order. Test class level resources should be defined in the resource_setup method of the test class, except for any credential obtained from the credentials provider, which should be set-up in the setup_credentials method. The test base class BaseTestCase defines Tempest framework for class level fixtures. setUpClass and tearDownClass are defined here and cannot be overwritten by subclasses (enforced via hacking rule T105). Set-up is split in a series of steps (setup stages), which can be overwritten by test classes. Set-up stages are: - skip_checks - setup_credentials - setup_clients - resource_setup Tear-down is also split in a series of steps (teardown stages), which are stacked for execution only if the corresponding setup stage had been reached during the setup phase. Tear-down stages are: - clear_credentials (defined in the base test class) - resource_cleanup Skipping Tests¶ Skipping tests should be based on configuration only. If that is not possible, it is likely that either a configuration flag is missing, or the test should fail rather than be skipped. Using discovery for skipping tests is generally discouraged. When running a test that requires a certain "feature" in the target cloud, if that feature is missing we should fail, because either the test configuration is invalid, or the cloud is broken and the expected "feature" is not there even if the cloud was configured with it. Negative Tests¶ Error handling is an important aspect of API design and usage. Negative tests are a way to ensure that an application can gracefully handle invalid or unexpected input. However, as a black box integration test suite, Tempest is not suitable for handling all negative test cases, as the wide variety and complexity of negative tests can lead to long test runs and knowledge of internal implementation details. The bulk of negative testing should be handled with project function tests. All negative tests should be based on API-WG guideline . Such negative tests can block any changes from accurate failure code to invalid one. If facing some gray area which is not clarified on the above guideline, propose a new guideline to the API-WG. With a proposal to the API-WG we will be able to build a consensus across all OpenStack projects and improve the quality and consistency of all the APIs. In addition, we have some guidelines for additional negative tests. - About BadRequest(HTTP400) case: We can add a single negative tests of BadRequest for each resource and method(POST, PUT). Please don't implement more negative tests on the same combination of resource and method even if API request parameters are different from the existing test. - About NotFound(HTTP404) case: We can add a single negative tests of NotFound for each resource and method(GET, PUT, DELETE, HEAD). Please don't implement more negative tests on the same combination of resource and method. The above guidelines don't cover all cases and we will grow these guidelines organically over time. Patches outside of the above guidelines are left up to the reviewers' discretion and if we face some conflicts between reviewers, we will expand the guideline based on our discussion and experience. Test skips because of Known Bugs¶ If a test is broken because of a bug it is appropriate to skip the test until bug has been fixed. You should use the skip_because decorator so that Tempest's skip tracking tool can watch the bug status. Example: @skip_because(bug="980688") def test_this_and_that(self): ... Guidelines¶ - Do not submit changesets with only testcases which are skipped as they will not be merged. - Consistently check the status code of responses in testcases. The earlier a problem is detected the easier it is to debug, especially where there is complicated setup required. Parallel Test Execution¶ Tempest by default runs its tests in parallel this creates the possibility for interesting interactions between tests which can cause unexpected failures. Dynamic credentials provides protection from most of the potential race conditions between tests outside the same class. But there are still a few of things to watch out for to try to avoid issues when running your tests in parallel. - Resources outside of a project scope still have the potential to conflict. This is a larger concern for the admin tests since most resources and actions that require admin privileges are outside of projects. - Races between methods in the same class are not a problem because parallelization in tempest is at the test class level, but if there is a json and xml version of the same test class there could still be a race between methods. - The rand_name() function from tempest.common.utils.data_utils should be used anywhere a resource is created with a name. Static naming should be avoided to prevent resource conflicts. - If the execution of a set of tests is required to be serialized then locking can be used to perform this. See AggregatesAdminTest in tempest.api.compute.admin for an example of using locking. Sample Configuration File¶ The sample config file is autogenerated using a script. If any changes are made to the config variables in tempest/config.py then the sample config file must be regenerated. This can be done running: tox -egenconfig Unit Tests¶ Unit tests are a separate class of tests in tempest. They verify tempest itself, and thus have a different set of guidelines around them: - They can not require anything running externally. All you should need to run the unit tests is the git tree, python and the dependencies installed. This includes running services, a config file, etc. - The unit tests cannot use setUpClass, instead fixtures and testresources should be used for shared state between tests. Test Documentation¶ For tests being added we need to require inline documentation in the form of docstrings to explain what is being tested. In API tests for a new API a class level docstring should be added to an API reference doc. If one doesn't exist a TODO comment should be put indicating that the reference needs to be added. For individual API test cases a method level docstring should be used to explain the functionality being tested if the test name isn't descriptive enough. For example: def test_get_role_by_id(self): """Get a role by its id.""" the docstring there is superfluous and shouldn't be added. but for a method like: def test_volume_backup_create_get_detailed_list_restore_delete(self): pass a docstring would be useful because while the test title is fairly descriptive the operations being performed are complex enough that a bit more explanation will help people figure out the intent of the test. For scenario tests a class level docstring describing the steps in the scenario is required. If there is more than one test case in the class individual docstrings for the workflow in each test methods can be used instead. A good example of this would be: class TestVolumeBootPattern(manager.ScenarioTest): """ This test case attempts to reproduce the following steps: * Create in Cinder some bootable volume importing a Glance image * Boot an instance from the bootable volume * Write content to the volume * Delete an instance and Boot a new instance from the volume * Check written content in the instance * Create a volume snapshot while the instance is running * Boot an additional instance from the new snapshot based volume * Check written content in the instance booted from snapshot """ Test Identification with Idempotent ID¶ Every function that provides a test must have an idempotent_id decorator that is a unique uuid-4 instance. This ID is used to complement the fully qualified test name and track test functionality through refactoring. The format of the metadata looks like: @test.idempotent_id('585e934c-448e-43c4-acbf-d06a9b899997') def test_list_servers_with_detail(self): # The created server should be in the detailed list of all servers ... Tempest.lib includes a check-uuid tool that will test for the existence and uniqueness of idempotent_id metadata for every test. If you have tempest installed you run the tool against Tempest by calling from the tempest repo: check-uuid It can be invoked against any test suite by passing a package name: check-uuid --package <package_name> Tests without an idempotent_id can be automatically fixed by running the command with the --fix flag, which will modify the source package by inserting randomly generated uuids for every test that does not have one: check-uuid --fix The check-uuid tool is used as part of the tempest gate job to ensure that all tests have an idempotent_id decorator. Branchless Tempest Considerations¶ Starting with the OpenStack Icehouse release Tempest no longer has any stable branches. This is to better ensure API consistency between releases because the API behavior should not change between releases. This means that the stable branches are also gated by the Tempest master branch, which also means that proposed commits to Tempest must work against both the master and all the currently supported stable branches of the projects. As such there are a few special considerations that have to be accounted for when pushing new changes to tempest. 1. New Tests for new features¶ When adding tests for new features that were not in previous releases of the projects the new test has to be properly skipped with a feature flag. Whether this is just as simple as using the @test.requires_ext() decorator to check if the required extension (or discoverable optional API) is enabled or adding a new config option to the appropriate section. If there isn't a method of selecting the new feature from the config file then there won't be a mechanism to disable the test with older stable releases and the new test won't be able to merge. 2. Bug fix on core project needing Tempest changes¶ When trying to land a bug fix which changes a tested API you'll have to use the following procedure: - Propose change to the project, get a +2 on the change even with failing - Propose skip on Tempest which will only be approved after the corresponding change in the project has a +2 on change - Land project change in master and all open stable branches (if required) - Land changed test in Tempest Otherwise the bug fix won't be able to land in the project. 3. New Tests for existing features¶ If a test is being added for a feature that exists in all the current releases of the projects then the only concern is that the API behavior is the same across all the versions of the project being tested. If the behavior is not consistent the test will not be able to merge. API Stability¶ For new tests being added to Tempest the assumption is that the API being tested is considered stable and adheres to the OpenStack API stability guidelines. If an API is still considered experimental or in development then it should not be tested by Tempest until it is considered stable.
http://docs.openstack.org/developer/tempest/HACKING.html
CC-MAIN-2017-04
refinedweb
2,592
59.94
#include <Wire.h>#include <FlexiTimer2.h>#include "Rainbow.h"/. */extern unsigned char buffer[2][96]; //two buffers (backbuffer and frontbuffer)//interrupt variablesbyte g_line,g_level;//read from bufCurr, write to !bufCurr//volatile //the display is flickerling, brightness is reducedbyte g_bufCurr;//flag to blit imagevolatile byte g_swapNow;byte g_circle;//data marker#define START_OF_DATA 0x10#define END_OF_DATA 0x20//FPS#define FPS 80.0f#define BRIGHTNESS_LEVELS 16#define LED_LINES 8#define CIRCLE BRIGHTNESS_LEVELS*LED_LINESvoid setup() { DDRD=0xff; // Configure ports (see): digital pins 0-7 as OUTPUT DDRC=0xff; // analog pins 0-5 as OUTPUT DDRB=0xff; // digital pins 8-13 as OUTPUT PORTD=0; // Configure ports data register (see link above): digital pins 0-7 as READ PORTB=0; // digital pins 8-13 as READ g_level = 0; g_line = 0; g_bufCurr = 0; g_swapNow = 0; g_circle = 0; Wire.begin(I2C_DEVICE_ADDRESS); // join i2c bus as slave Wire.onReceive(receiveEvent); // define the receive function for receiving data from master // Keep in mind: // While an interrupt routine is running, all other interrupts are blocked. As a result, timers will not work // in interrupt routines and other functionality may not work as expected // -> if i2c data is receieved our led update timer WILL NOT WORK for a short time, the result // are display errors! //redraw screen 80 times/s FlexiTimer2::set(1, 1.0f/(128.f*FPS), displayNextLine); FlexiTimer2::start(); //start interrupt code}//the mainloop - try to fetch data from the i2c bus and copy it into our buffervoid loop() { if (Wire.available()>97) { byte b = Wire.receive(); if (b != START_OF_DATA) { //handle error, read remaining data until end of data marker (if available) while (Wire.available()>0 && Wire.receive()!=END_OF_DATA) {} return; } byte backbuffer = !g_bufCurr; b=0; //read image data (payload) - an image size is exactly 96 bytes while (b<96) { buffer[backbuffer][b++] = Wire.receive(); //recieve whatever is available } //read end of data marker if (Wire.receive()==END_OF_DATA) { //set the 'we need to blit' flag g_swapNow = 1; } }}//=============HANDLERS======================================//get data from master - HINT: this is a ISR call!//HINT2: do not handle stuff here!! this will NOT work//collect only data here and process it in the main loop!void receiveEvent(int numBytes) { //do nothing here}//============INTERRUPTS======================================// shift out led colors and swap buffer if needed (back buffer and front buffer) // function: draw whole image for brightness 0, then for brightness 1... this will // create the brightness effect. // so this interrupt needs to be called 128 times to draw all pixels (8 lines * 16 brightness levels) // using a 10khz resolution means, we get 10000/128 = 78.125 frames/s// TODO: try to implement an interlaced update at the same rate. void displayNextLine() { draw_next_line(); // scan the next line in LED matrix level by level. g_line+=2; // process all 8 lines of the led matrix if(g_line==LED_LINES) { g_line=1; } if(g_line>LED_LINES) { // when have scaned all LED's, back to line 0 and add the level g_line=0; g_level++; // g_level controls the brightness of a pixel. if (g_level>=BRIGHTNESS_LEVELS) { // there are 16 levels of brightness (4bit) * 3 colors = 12bit resolution g_level=0; } } g_circle++; if (g_circle==CIRCLE) { // check end of circle - swap only if we're finished drawing a full frame! if (g_swapNow==1) { g_swapNow = 0; g_bufCurr = !g_bufCurr; } g_circle = 0; }}// scan one line, open the scaning rowvoid draw_next_line() { DISABLE_OE //disable MBI5168 output (matrix output blanked) //enable_row(); //setup super source driver (trigger the VCC power lane) CLOSE_ALL_LINE //super source driver, select all outputs off open_line(g_line); LE_HIGH //enable serial input for the MBI5168 shift_24_bit(); // feed the leds LE_LOW //disable serial input for the MBI5168, latch the data ENABLE_OE //enable MBI5168 output}//open correct output pins, used to setup the "super source driver"//PB0 - VCC3, PB1 - VCC2, PB2 - VCC1//PD3 - VCC8, PD4 - VCC7, PD5 - VCC6, PD6 - VCC5, PD7 - VCC4void enable_row() { if (g_line < 3) { // Open the line and close others PORTB = (PINB & 0xF8) | 0x04 >> g_line; PORTD = PIND & 0x07; } else { PORTB = PINB & 0xF8; PORTD = (PIND & 0x07) | 0x80 >> (g_line - 3); }}// display one line by the color level in buffervoid shift_24_bit() { byte color,row,data0,data1,ofs; for (color=0;color<3;color++) { //Color format GRB ofs = color*32+g_line*4; //calculate offset, each color need 32bytes for (row=0;row<4;row++) { data1=buffer[g_bufCurr][ofs]&0x0f; //get pixel from buffer, one byte = two pixels data0=buffer[g_bufCurr][ofs]>>4; ofs++; if(data0>g_level) { //is current pixel visible for current level (=brightness) SHIFT_DATA_1 //send high to the MBI5168 serial input (SDI) } else { SHIFT_DATA_0 //send low to the MBI5168 serial input (SDI) } CLK_RISING //send notice to the MBI5168 that serial data should be processed if(data1>g_level) { SHIFT_DATA_1 //send high to the MBI5168 serial input (SDI) } else { SHIFT_DATA_0 //send low to the MBI5168 serial input (SDI) } CLK_RISING //send notice to the MBI5168 that serial data should be processed } }}void open_line(unsigned char line) { // open the scaning line switch(line) { case 0: { open_line0 break; } case 1: { open_line1 break; } case 2: { open_line2 break; } case 3: { open_line3 break; } case 4: { open_line4 break; } case 5: { open_line5 break; } case 6: { open_line6 break; } case 7: { open_line7 break; } }} Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=73833.0;prev_next=prev
CC-MAIN-2015-06
refinedweb
858
53.04
Hello, at the moment I am writing a program which needs to open, close and modify many different files at the same time (typically over 100 at a given time). Because of this requirement of the project, I decided to make a class which contains a vector of pointers to the different fstream instances for the files. That way I have a simple and 'clean' way to handle this many files. The fact that I am using vectors also means I can easily add new fstream instances (open new files) just by using the push_back method etc. For some reason, I'm having a bit of difficulty getting it to open a new file (it shouldn't be this hard). The program compiles it just doesn't do what I want it to, and I can't work out where the problem is. Code:#include <fstream> #include <vector> #include <string.h> using namespace std; class CFileManage { private: CFileManage(); virtual ~CFileManage(); vector<fstream *> m_file; static CFileManage * hcInstance; public: /* Make sure only one instance of this class is generated */ static CFileManage * GetClassInstance(); static void GenerateClassInstance(); void DeleteClassInstance(); /* Make use of the i/o filestream vectors */ bool CreateNewFileInstance(char * filename); void CreateNewFileInstance(string filename); void CloseFileInstance(unsigned int vec_idx); void CloseAllFileInstances(); unsigned int GetNumberOfFileInstances(); fstream * GetFileInstance(unsigned int vec_idx); };For some reason, the code compiles, but it doesn't work as expected when it comes to making a new file.For some reason, the code compiles, but it doesn't work as expected when it comes to making a new file.Code:bool CFileManage::CreateNewFileInstance(char * filename) { m_file.push_back( new fstream ); m_file.back()->open(filename); if( m_file.back()->is_open() ) { return false; } return true; } void CFileManage::CloseAllFileInstances() { int idx; for(idx=0; idx < m_file.size(); idx++) { m_file[idx]->close(); delete m_file[idx]; } m_file.clear(); return; } At a later date I plan to change the CreateFile Methods so that it allows support for binary files aswell as different modes, e.g. app, ate, trunc etc.
http://cboard.cprogramming.com/cplusplus-programming/118864-difficulty-program-has-open-hundreds-files-time.html
CC-MAIN-2013-20
refinedweb
330
52.7
- 13 Dec, 2011 1 commit shared_ptr is a candidates for the next STL version and Windows has already adopted it. This change removes ambiguity between the Boost and Windows versions of the class. - 12 Dec, 2011 1 commit Some compilers warn if "this" is referred to in a constructor initialization list. This change replaces such initializations with an assignment within the constructor body. - 20 Oct, 2011 1 commit - Jeremy C. Reed authored - 19 Jul, 2011 1 commit it's always NULL because it cannot be configured with TSIG keys. it should be done in a separate ticket. - 06 Jul, 2011 1 commit type matching for the shared_ptr template parameters in "?:". Note that this fix doesn't loosen the constness, so it doesn't compromise anything. - 01 Jul, 2011 2 commits I also noticed some of the comments in the tests are stale or not really correct, so I fixed them, too. typedef. RequestACL is itself a shortcut, so it doesn't make sense to define another one. - 30 Jun, 2011 1 commit framework. it now accepts "action only" rule, so the test test in that case was updated accordingly. - 29 Jun, 2011 1 commit definition of uint16_t in the boost namespace. So avoid doing 'using namespace boost'. Instead, import a specific name used in this file. additional cleanups are made: be sure to include stdint.h just in case, and remove unnecessary boost header file. - 27 Jun, 2011 1 commit - 24 Jun, 2011 3 commits the main purpose of this change is for query ACL, but it also eliminates the need for hardcoding the default listen_on setting. - 22 Jun, 2011 3 commits so that the methods have reasonable length. - 21 Jun, 2011 2 commits - 06 Jun, 2011 1 commit - 03 Jun, 2011 1 commit - 25 May, 2011 2 commits constructor. this fixes a regression report from cppcheck. - 16 May, 2011 1 commit - 13 May, 2011 1 commit - 22 Apr, 2011 1 commit - zhanglikun authored [trac598_new] Reimplement the ticket based on new branch. Implement the simplest forwarder by refactoring the code - 14 Apr, 2011 1 commit - 12 Apr, 2011 1 commit - 11 Apr, 2011 1 commit - 08 Apr, 2011 1 commit - Ocean Wang authored - 17 Mar, 2011 1 commit -) - 02 2 commits Taken out from resolver and put into the server_common library. Spaces around comma
https://gitlab.isc.org/isc-projects/kea/-/commits/f1f4ce3e3014366d4916f924655c27761327c681/src/bin/resolver/resolver.cc
CC-MAIN-2021-04
refinedweb
384
72.97
#include "llvm/ExecutionEngine/Orc/RPCUtils.h" Definition at line 1356 of file RPCUtils.h. Return type for non-blocking call primitives. Definition at line 1400 of file RPCUtils.h. Definition at line 1367 of file RPCUtils.h. Definition at line 1386 of file RPCUtils.h. Add a class-method as a handler. Definition at line 1392 of file RPCUtils.h. Add a handler for the given RPC function. This installs the given handler functor for the given RPC Function, and makes the RPC function available for negotiation/calling from the remote. Definition at line 1374 of file RPCUtils.h. Add a class-method as a handler. Definition at line 1380 of file RPCUtils.h. Call Func on Channel C. Does not block, does not call send. Returns a pair of a future result and the sequence number assigned to the result. This utility function is primarily used for single-threaded mode support, where the sequence number can be used to wait for the corresponding result. In multi-threaded mode the appendCallNB method, which does not return the sequence numeber, should be preferred. Definition at line 1410 of file RPCUtils.h. Call Func on Channel C. Blocks waiting for a result. Returns an Error for void functions or an Expected<T> for functions returning a T. This function is for use in threaded code where another thread is handling responses and incoming calls. Definition at line 1456 of file RPCUtils.h. The same as appendCallNBWithSeq, except that it calls C.send() to flush the channel after serializing the call. Definition at line 1435 of file RPCUtils.h. Handle incoming RPC calls. Definition at line 1464 of file RPCUtils.h.
http://llvm.org/doxygen/classllvm_1_1orc_1_1rpc_1_1MultiThreadedRPCEndpoint.html
CC-MAIN-2018-47
refinedweb
278
62.24
CodePlexProject Hosting for Open Source Software Hi all, Are there any tutorials anywhere that show how best to setup a master/detail scenario using foreign keys. So for example if I have the following... public class Parent : IBusinessEntity { public Parent () { } /// <summary> /// Gets or sets the Database ID. /// </summary> /// <value> /// The ID. /// </value> [PrimaryKey, AutoIncrement] public int ID { get; set; } public string Name { get; set; } public string Surname { get; set; } public List<Child> Children { } } How can I get the Child objects to auto-populate from a json requst. Will then be saving this heirachy to a SQLLite DB. I'm sure it is something simple, but I can't see the woods for the code, right now. D. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://json.codeplex.com/discussions/353683
CC-MAIN-2017-43
refinedweb
153
74.69
This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project. >>>>> "Jan" == Jan Kratochvil <jan.kratochvil@redhat.com> writes: Jan> 2013-05-01 Jan Kratochvil <jan.kratochvil@redhat.com> Jan> * cleanups.c (restore_my_cleanups): New gdb_assert for SENTINEL_CLEANUP. Thanks for doing this. I think it is a nice addition. We could do this for all cleanup-creating functions, at least when using GCC, if we didn't mind putting a declaration at the start of each such function: #if ... gcc .. #define CHECK_CLEANUP \ struct cleanup *__dummy ## __LINE__ \ __attribute__ ((cleanup (check_cleanup))) \ = get_checking_cleanup_pointer (); #endif This would call check_cleanup when the function exited normally, so we could verify that the cleanup chain was properly reset. I think it would be possible to automate adding this declaration in all needed spots. I'm curious what you think about it. Tom
http://sourceware.org/ml/gdb-patches/2013-05/msg00129.html
CC-MAIN-2016-26
refinedweb
140
69.38
This article is Day #16 in a series called 31 Days of Windows 8. Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website. Today, our focus is on context menus aka PopupMenu. These are those small little popup commands that appear from time to time in your application when you right click on something. Microsoft offers some very specific guidance on when to use these context menus vs. when to use the AppBar control instead, so we will be following those rules in this article. What Is a Context Menu? If you’ve used Windows 8 at all, you’ve likely encountered these before. Often they result from a right-click on something you couldn’t select, or on text you wanted to interact with. Here’s a quick sample of a context menu: (image from) You could also launch a context menu from an element on your page that is unselectable, like this image in my sample app: Right-clicking the image launches the context menu center right above it. (I will show you how to make this happen next.) Each of the command items will have an action assigned to it, which is executed when the item is clicked. Creating the Context Menu Creating the Context Menu that you see above is pretty straight forward. To start with, we will wire up a handler to our image element such that anytime someone right clicks on the object they will get our context menu. This looks like any other event listener, and we will listen on ‘contextmenu’ like such. document.getElementById("myImage").addEventListener("contextmenu", imageContentHandler, false); Next, we need to create our handler, which I have managed to call imageContentHandler, I know pretty awesome naming there. In our function we will simply start out by creating our PopupMenu object and adding the items we want to be shown. Each item can have its on event handler as well and in the example below I am just giving them all the same event handler of somethingHandler ( I know more awesome naming ).)); With our PopupMenu defined, now we just need to show it. We can do that by calling showAsync and passing it some x,y coordinates like you see below. contextMenu.showAsync({ x: [someCoords], y: [someCoords] }); Now how do we figure out where exactly to put it? Determining The Location You may have noticed that context menus appear directly above and centered to the element that has been selected. This doesn’t happen by magic. We’ll actually have to determine the position of the clicked element by ourselves (as well as any applicable offsets), and pass that along when we show the menu. Time to sharpen some pencils. When a user click on our image, our contextmenu event is going to fire, calling our handler, imageContentHandler. It’s going to pass some arguments that we need to kick off our fact finding. There are three critical pieces of data we’re looking for here. 1. the x and y of the click and 2. the offset of the element that was its target and 3. the width of the target object. ( target object here is the image ) . Let’s see the code, and then come back to it. function showWhereAbove(clickArgs) { var zoomFactor = document.documentElement.msContentZoomFactor; var position = { x: (clickArgs.pageX - clickArgs.offsetX - window.pageXOffset + (clickArgs.target.width / 2)) * zoomFactor, y: (clickArgs.pageY - clickArgs.offsetY - window.pageYOffset) * zoomFactor } return position; } So I have created this simple function called showWhereAbove taking something called the clickArgs. clickArgs is nothing more than the args that was passed into our contextmenu handler. To figure out both x and y are actually pretty much the same. x = ( where x click was – offset to top of target – windows x offset + ( target width /2 )) * window zoom factor Let’s continue to break that down - where x click was = the x position of the mouse at the time of click - offset to top of target = how much to the right of the elements left edge are we - window x offset = where are we in relation to the window being scrolled - target width / 2 = we need to move the PopupMenu to the middle of the object so we’re going to take the width and get middle - window zoom factor = if the screen is zoomed in put it in apply that factor Now the y axis is the same in principal as x, except we don’t have to worry about the height of the target. Since we’re working with the bottom center of the context menu, just getting our y offset is enough to put the bottom of the PopupMenu in the right position. Again remember – we’re trying to position the the bottom middle of the Popup Menu. Now that we know our position, we just need to show it. contextMenu.showAsync(showWhereAbove(args)); Here is the finished function: function imageContentHandler(args) {)); contextMenu.showAsync(showWhereAbove(args)); } Launching a Context Menu From Selected Text Actually, nearly everything about this process is the same, except for the math on where to pop the box from. Initially when setting out to solve this problem, I was hoping to add on to the existing context menu that already appears when you right-click on text: As it turns out, you can’t ( at least that we’re aware of ). So, for our example, let’s say that we want to keep all of those options, but also add a new one titled “Delete” at the bottom. To do this, we’re going to have to create our own. While we know how to do so already there are two differences: - We need to place our PopupMenu at the top of our selected text and in the middle. - Stop the default behavior. Like wire up an event handler to the contextmenu event of something like a <p> element. document.getElementById("myInputBox").addEventListener( "contextmenu", inputHandler, false); - tip – I am using a paragraph element here for demonstration. Because of that I need to make my element selectable. I did so in CSS like so p { -ms-user-select: element; } Now we need to create our handler in this case inputHandler. Remember I said that we needed to prevent the default and do our own thing. To do so, we’re going to call preventDefault AND we’re going to see if some text was in fact selected. At that point, we can then crate our PopupMenu and show it. function inputHandler(args) { args.preventDefault(); if (isTextSelected()) { //create the PopupMenu and its items } } function isTextSelected() { return (document.getSelection().toString().length > 0); } After your PopupMeu is created we need to show it, but unlike before when we called showAsync() this time we need to call showForSectinoAsync. Since we’re going to show above the selection we need to understand what exactly was selected rather than just the element itself. contextMenu.showForSelectionAsync( showForSelectionWhere( document.selection.createRange().getBoundingClientRect())); You can see I have created again a helper function called showForSelectionWhere to take care of that math. We’re going to pass into it the bounding rectangle of our selection. Lets look at the code and then come back to it. function showForSelectionWhere(boundingRect) { var zoomFactor = document.documentElement.msContentZoomFactor; var position = { x: (boundingRect.left + document.documentElement.scrollLeft - window.pageXOffset) * zoomFactor, y: (boundingRect.top + document.documentElement.scrollTop - window.pageYOffset) * zoomFactor, width: boundingRect.width * zoomFactor, height: boundingRect.height * zoomFactor } return position; } showForSelectionAsync takes an object with 4 properties; x, y, width, height. Let’s look at x quickly. - x = left edge of the bounding rect + any pixels scrolled within the container element – the window scroll offset * zoom factor - y is basically the same as x, different axis. Very similar to when we were working with the image element other than we have to figure out our position from within the element we we’re part of. The results should be as you would expect. Summary Today we looked at the art of creating inline context menus for our users. They are an excellent way to provide interactions with elements that aren’t selectable, or for commands that make more sense directly adjacent to the element being interacted with. If you would like to see the entire code sample from this article, click the icon below: Tomorrow, we will venture further into the Clipboard functionality available to us in Windows 8 development. See you then! {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/31-days-windows-8-html5-day-16
CC-MAIN-2016-22
refinedweb
1,427
62.98
Hello! This morning, i have changed the configuration of an inline extraction in props.conf. The original Extraction (this worked): props.conf [source::///var/log/containers/*.log] EXTRACT-sourcedata = (?<containers>(?<=containers\/).*?(?=_)).(?<namespace>.*(?=_)).(?<service>.*(?=-)) in source I then changed the extraction to this: [docker_json] EXTRACT-sourcedata = (?<containers>(?<=containers\/).*?(?=_)).(?<namespace>.*(?=_)).(?<service>.*(?=-)) in source because the inputs.conf file defines the sourcetype as follows ... inputs.conf [monitor:///var/log/containers/*.log] sourcetype = docker_json disabled = 0 ..., this should work. however, the change did not work. I proceeded to undo said change, yet the old extraction stopped working as well. Why is that? Does it take time for splunk to apply inline extractions? I have found the answer as to why the old extraction didn't work: despite that inputs.conf defines the input as follows: [monitor:///var/log/containers/*.log] the stanza in props.conf has to be as follows: [source::/var/log/containers/*.log] I apologise for above error also being present in the working version above. However, that does not explain why the new extraction (using the sourcetype) does not work. At risk of stating the obvious, but: - did you deploy the config in the right place (your search head(s))? - you're not rewriting the sourcetype to something else at index time? - no conflicting configs due to previous attempts? (e.g. check with btool)
https://community.splunk.com/t5/Getting-Data-In/Props-conf-EXTRACT-stopped-working-after-stanza-change/m-p/410694
CC-MAIN-2021-21
refinedweb
227
53.88
scripting functionality, feel free to download a SoapUI Pro trial from our website. SoapUI provides extensive options for scripting, using either Groovy or Javascript (since SoapUI 3.0) as its scripting language, which to use is set a the project level in the project details tab at the bottom left. The majority of the documentation available here will be for the Groovy language, as it greatly simplifies the scripting of Java APIs (you can get more information, tutorials, etc on the Groovy Web Site). An overview of how to use JavaScript instead is further down in this document. Scripts can be used at the following places in SoapUI: All scripts have access to a number of situation-specific variables, always including a log object for logging to the Groovy Log and a context object for perform context-specific PropertyExpansions or property handling if applicable. A context-specific variable is always available for directly accessing the SoapUI object model. Script editors are generally available as inspectors at the bottom of the corresponding objects editor, each having a run button, a drop-down edit menu (same as the right-click popup), an information label, and a help button; The popup-menu (as shown above) contains standard edit-related actions and will in SoapUI Pro contain a "Get Data" menu option that expands to show all properties available within the current scope. Selecting a property (or the option to create a new one) will eventually create a script to get the variable, for example def test = context.expand( '${#Project#test}' ) Which gets the Project-level "test" property. It is also possible to drag a property from the navigator tree when it is in Property Mode into the script; if the dragged property is "within scope" (i.e. can be accessed via property expansion), the corresponding access script will be created at the caret location You can have a central library of Groovy Classes that can be accessed from any script, which can be useful for centralizing common tasks and functionality and for creating extensions. The Script Library can be used as follows; Remember that the script files must be valid classes, not just arbitrary scripts. So as an example, lets setup one of these Groovy objects. First, create a directory (e.g. C:\GroovyLib). Then add a Callee.groovy file in that directory with the following content: C:\GroovyLib Callee.groovy package readyapi.demo //Callee.groovy class Callee { String hello() { return "Hello world! " } def static salute( who, log ) { log.info "Hello again $who!" } } Now let's setup SoapUI to load up your Groovy library. Set File > Preferences > SoapUI tab > Script Library. So we would set that to "C:\GroovyLib" in our example. Then we restart SoapUI to pick up the library script. Now if we create a Groovy Script Step in a TestCase, we can use the above class from the library with the following: //Caller.groovy c = new Callee() log.info c.hello() Running this from within the Groovy Editor will show the following in the Groovy Editors log: Tue MONTH 29 10:56:08 EST YEAR:INFO:Hello world! If we modify the Callee.groovy file: package readyapi.demo String hello(String who) { return "Hello $who" SoapUI will pick up the modified file (once it has been saved), which is seen in the log: Tue MONTH 29 10:56:08 EST YEAR:INFO:C:\GroovyLib\Callee.groovy is new or has changed, reloading... Tue MONTH 29 10:56:08 EST YEAR:INFO:C:\GroovyLib\Callee.groovy is new or has changed, reloading... We also change the script: //Caller.groovy c = new Callee() log.info c.hello("Mike") And we get: Tue MONTH 29 10:56:08 EST YEAR:INFO:Hello, Mike! We can also call the static salute method: readyapi.demo.Callee.salute( "Mike", log ) readyapi.demo.Callee.salute( "Mike", log ) Which will produce the following output: Tue MONTH 29 10:56:08 EST YEAR:INFO:Hello again Mike! Tue MONTH 29 10:56:08 EST YEAR:INFO:Hello again Mike! SoapUI Pro 2.5 adds rudimentary support for configurable code templates which will be activated when typing the correspondig template ID and pressing Ctrl-Space in an editor. Templates can be added/changed in the Preferences\Code Templates page, the following templates are available by default: The '|' designates the position of the caret after inserting the template. SoapUI 3.0 adds support for JavaScript as an alternative scripting language. When configured, all scripts in the containing project will be interpreted using a JavaScript engine (Rhino) instead (read more about the Rhino engine and supported features at ... ). For those of you used to JavaScript this might be an easier language to get started with. A note on the choice of Groovy: When we started to provide scripting possibilities in 2006, Groovy was the natural language of choice. Now this has changed and there are many viable alternatives to Groovy scripting API (JRuby, Jython, Javascript, etc), but since we have made our own optimizations for the Groovy ClassLoaders which would not be available for these other languages, we have opted to stick to Groovy instead of providing "sub-optimal" support for other languages.
https://www.soapui.org/docs/scripting-and-properties/scripting-and-the-script-library/
CC-MAIN-2021-04
refinedweb
861
63.59
Making reusable packages Whilst splitting your plan into several files is a good idea, you will sometimes need to create standalone packages aiming to be reusable and shared. Let's explore how to do that. Packages, modules, and Dagger projects Understanding the difference between a package, a module and a Dagger project is an important distinction, as it will help better organizing your work: - CUE Package: directory with CUE files, each including a package definition on top, making it importable (e.g, universe.dagger.io/dockeris a package, universe.dagger.io/docker/cliis another package); - CUE Module: directory with a cue.moddirectory which makes for the prefix/root of importable packages (e.g, universe.dagger.iois a module); - Dagger Project: a CUE module that includes dagger plans and dependencies for running the dagger CLI. End-to-End example Instead of splitting all of our files in the the same project with a module, we could directly make reusable components from our plan as standalone packages. For the sake of the exercise, we will use GitHub as a version control system, but it will work with any alternative. Create the base Dagger project First, let's start with a basic plan: - Create the root directory mkdir rootProject && cd rootProject - Initialize the project dagger project init - Update daggerand universedependencies dagger project update - At the root of the project, create your main.cuefile (file and package names are arbitrary): package main import ( "dagger.io/dagger" ) dagger.#Plan & { actions: { hello: #Run & { script: contents: "echo \"Hello!\"" } } } We are currently calling a #Run definition that doesn't exist yet. We will declare it in a new package right below: it will wrap the bash.#Run definition with a custom image. Create the package Let's see how to create the #Run definition in its own package: - Create a completely new directory next to rootProject: it will be a new git repository. You can directly git cloneor initialize a new one with: cd .. && mkdir personal && cd personal && git init - At the root of this new folder, create the CUE file that will contain the #Runpackage. The name of the file is not important, but the package name shall follow the name of the remote repo (best practice convention): package personal import( "universe.dagger.io/alpine" "universe.dagger.io/bash" ) #Run: { _img: alpine.#Build & { packages: bash: _ } bash.#Run & { always: true input: _img.output } } You should now have this file and directory structure: $ tree -L 2 . ├── personal │ └── main.cue └── rootProject ├── cue.mod └── main.cue 3 directories, 2 files Link package to the project - We first need to include the newly created package in the project. In order to do that, we will create a symlink similar to what dagger project updatewould create once we push the package on Github: $ ls -l total 0 drwxr-xr-x 4 home wheel 128 9 mai 16:04 personal drwxr-xr-x 4 home wheel 128 9 mai 16:01 rootProject $ mkdir -p rootProject/cue.mod/pkg/github.com/your-username/ $ ln -s "$(pwd)/personal" "$(pwd)/rootProject/cue.mod/pkg/github.com/your-username/personal" When using your package from dagger project update in the rootProject directory, the actual packager manager would copy the files from the repository in the rootProject/cue.mod/pkg/github.com/your-username/personal folder. - We then need to change the project's main.cueto call the #Rundefinition in the personalpackage that we just built: package main import ( "dagger.io/dagger" "github.com/your-username/personal" // import personal package ) dagger.#Plan & { actions: { hello: personal.#Run & { // reference #Run definition from personal package imported above script: contents: "echo \"Hello!\"" } } } Run the project Now that we have connected all the dots, let's run our plan to see if it works: $ cd rootProject $ dagger do hello --log-format plain 4:42PM INF actions.hello.script._write | computing 4:42PM INF actions.hello._img._dag."0"._op | computing 4:42PM INF actions.hello.script._write | completed duration=0s 4:42PM INF actions.hello._img._dag."0"._op | completed duration=0s 4:42PM INF actions.hello._img._dag."1"._exec | computing 4:42PM INF actions.hello._img._dag."1"._exec | completed duration=0s 4:42PM INF actions.hello._exec | computing 4:42PM INF actions.hello._exec | completed duration=200ms 4:42PM INF actions.hello._exec | #5 0.123 Hello! Push package on repository Now that we made sure we correctly built our package, we only need to push it to the repository: - Add - Commit - Tag - Push On another project, you will directly be able to retrieve your package using the dagger project update github.com/your-username/personal@<tag> command, where <tag> is a git tag in the format vX.Y.Z1 (e.g., v0.1.0). Reminder The name of the repository should follow the name of the created folder and the package name ( personal in the above example). caution Omitting @<tag> (same as using default branch for repository) or using a branch instead of a tag (e.g., @main) is not recommended because of reproducibility issues. If you do this you may get a checksum didn't match error. The reason for this is that a branch may point to different commits in time. If you use a branch as the version when you install the package, the file contents of that same "version" may change if you add commits to it by the next time you install in a clean clone ( dagger project update). The new checksum for the files won't match the one that was commited in dagger.sum previously. There's an open issue to fix this behavior by converting the branch into a pseudo-version, targetting the specific commit the branch points to at the point it was added to the project or updated. Until then, it's best to avoid using branches as versions. If you really need to, the best workaround is to vendor your module (committing in cue.mod/pkg to git and not running dagger project update in CI), and re-install with dagger project update <url>@<branch> to update. - Where X.Y.Zis a semantic version, with major, minor and patch components.↩
https://docs.dagger.io/1239/making-reusable-package/
CC-MAIN-2022-27
refinedweb
1,022
55.95
: Binder hasChanges, removeBean after readBean Hi everyone, I've a question: I've got a binder. If I read a bean and modify a field --> binder.hasChanges is true (Perfect). If I call removeBean then nothing changes on the screen and binder.hasChanges is still true. I don't understand why it should be true after removeBean. I write some code to test it: (just click on READ, modify the field, CHECK, REMOVE and CHECK) @Theme("mytheme") public class MyUI extends UI { private Window popup; private TextField value = new TextField(); private Label hasChangesLabel = new Label(""); private Binder<Pojo> binder; private Pojo p = new Pojo("test"); @Override protected void init(VaadinRequest vaadinRequest) { final VerticalLayout layout = new VerticalLayout(); if (binder == null){ binder = new Binder<Pojo>(); binder.bind(value,Pojo::getValue, Pojo::setValue); } Button checkHasChangesButton = new Button("CHECK", e -> {hasChangesLabel.setCaption(binder.hasChanges()?"CHANGES":"NO CHANGES");} ); Button removeBeanButton = new Button("REMOVE", e -> {binder.removeBean();}); Button readBeanButton = new Button("READ", e -> {binder.readBean(p);}); Button setBeanButton = new Button("SET", e -> {binder.setBean(p);}); layout.addComponents(hasChangesLabel, value, checkHasChangesButton,removeBeanButton,readBeanButton, setBeanButton); setContent(layout); } @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true) @VaadinServletConfiguration(ui = MyUI.class, productionMode = false) public static class MyUIServlet extends VaadinServlet { } } Thanks, Hi, This looks like a bug to me, at least in the documented API behavior sense - in-- it pretty clearly states that hasChanges should return false after removeBean(). I think I see why it's happening - you haven't actually bound a bean instance to the Binder in your example with that sequence of events. Note the readBean API doc: public void readBean(BEAN bean) Reads the bound property values from the given bean to the corresponding fields. The bean is not otherwise associated with this binder; in particular its property values are not bound to the field value changes. To achieve that, use #setBean(BEAN) So in your example you create a Binder, set is to the TextField and tell it to use the Bean class's getValue and setValue methods. Then you call readBean() with a bean instance, which populates the values from the instance, but doesn't bind anything. Do some changes, Binder has changed, remove the bound bean (=remove nothing -> do nothing). Binder has changed, but it's kind of in an invalid state at this point. If you don't mind, could you please create a ticket about this at? If you have an idea of how it should behave in this case, please write that in too - maybe Binder should throw an exception if you call remove when there is no bean bound? Best regards, Olli I create a new ticket: I understand that: removeBean = setBean(null) (opposite of setBean) So in my case, I should use readBean(null). (the difference between bound bean and bound properties is not so easy to understand) Especially if you read this javadoc-- public BEAN getBean() Returns the bean that has been bound with bind(com.vaadin.data.HasValue<FIELDVALUE>, com.vaadin.data.ValueProvider<BEAN, FIELDVALUE>, com.vaadin.server.Setter<BEAN, FIELDVALUE>), or null if a bean is not currently bound.Returns: the currently bound bean if any That's wrong, if I understand the difference between readBean and setBean. Hi, think of it like this: readBean() takes the values that are stored in the object instance, but otherwise it does nothing. So basically it only calls getters. In turn setBean() takes the object instance and makes it THE object in the Binder. Once you have called setBean() and make changes to the field, the setters of the object are called and the values inside it are updated. -Olli Ly Pisith Khmer: I can't clean bean after i submit form . how cam i solve my problem . thank you I don't understand if it's related to the "bug". Perhaps we can help you with a code snippet to reproduce your problem. Jean-Christophe Gueriaud: Ly Pisith Khmer: I can't clean bean after i submit form . how cam i solve my problem . thank you I don't understand if it's related to the "bug". Perhaps we can help you with a code snippet to reproduce your problem. Thank you so much guy . Now it working normaly
https://vaadin.com/forum/thread/15750727/vaadin-8-binder-haschanges-removebean-after-readbean
CC-MAIN-2021-43
refinedweb
699
55.84
File Logger Tree for Fimber A tree for the Fimber Flutter library that will write the logs to a File for each day. Getting started 1) Dependency setup First import the library to your project in your pubspec.yaml: - 1.1.x uses intl0.16+ - 1.0.x uses intl0.15.x flutter_fimber_filelogger: ^1.1.0 # or flutter_fimber_filelogger: ^1.0.2 2) Import the library in your Dart code import 'package:flutter_fimber_filelogger/flutter_fimber_filelogger.dart'; 3) Plant the tree Fimber.plantTree(FileLoggerTree()); Files The files will be stored in the [getApplicationDocumentsDirectory]/logs directory. For each day, a new File will be created. An auto-clean mechanism is available, where you have to specify the number of days to keep the files onto the disk: Fimber.plantTree(FileLogerTree(numberOfDays: 5)); To disable it, just pass a null value.
https://pub.dev/documentation/flutter_fimber_filelogger/latest/
CC-MAIN-2019-39
refinedweb
136
53.37
public class Solution { public int findKthLargest(int[] a, int k) { int n = a.length; int p = quickSelect(a, 0, n - 1, n - k + 1); return a[p]; } // return the index of the kth smallest number int quickSelect(int[] a, int lo, int hi, int k) { // use quick sort's idea // put nums that are <= pivot to the left // put nums that are > pivot to the right int i = lo, j = hi, pivot = a[hi]; while (i < j) { if (a[i++] > pivot) swap(a, --i, --j); } swap(a, i, hi); // count the nums that are <= pivot from lo int m = i - lo + 1; // pivot is the one! if (m == k) return i; // pivot is too big, so it must be on the left else if (m > k) return quickSelect(a, lo, i - 1, k); // pivot is too small, so it must be on the right else return quickSelect(a, i + 1, hi, k - m); } void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } } one question. while (i < j) { if (a[i++] > pivot) swap(a, --i, --j); }. why --i,--j, I think should simple swap(i,j) Hi FanFeng, in quick sort, I pick a[hi] as the pivot, and set i = lo, j = hi, our mission is to put all the numbers that are greater than the pivot to the right, and all the numbers that are less than or equal to the pivot to the left, so let's take a look at this example: lo ----- hi 5 2 1 4 3 i ------- j 3 is the pivot, since 5 (a[i++]) > pivot, let's put 5 to the right, to do that, we swap 4 and 5, so it becomes to: 4 2 1 5 3 i ----- j now since 4 is larger than pivot, we swap 4 and 1, we get: 1 2 4 5 3 i --- j as you can see, --i makes sure we can still check a[i] after the swap, and --j makes sure we won't overwrite the ones that are already done. Hope that makes sense to you. do you consider duplicated value? like {1,2,3,3,4,5}, the 4th largest should be 2 not 3. I guess what you mean is the 4th largest number should be 4. But this question has one requirement. Note that it is the kth largest element in the sorted order, not the kth distinct element. is there something with that sentence? if (m == k) return i; i think it should be return a[i]; // put nums that are <= pivot to the left // put nums that are > pivot to the right int i = lo, j = hi, pivot = a[hi]; while (i < j) { if (a[i++] > pivot) swap(a, --i, --j); } swap(a, i, hi); Can someone please point out why it's putting nums that are <= pivot to the left? @happyLucia I think it's because int p = quickSelect(a, 0, n - 1, n - k + 1); has converted the problem into find (n-k+1)th smallest. @Badger96 Thanks for your reply. I didn't make my question clear. Actually I meant to ask: it seems it's swapping a[i] with a[j]. while a[i] is > pivot for sure, it didn't check if a[j] < pivot or not. Did I miss anything here? How do you think? if (m == k) return i; what's the reason you return i here? I tried returning a[i] but it gives me wrong answer. I thought i is supposed to be an index? @zfrancica Since the quickSelect method is to find the kth smallet number, and we need to find the kth element, so we need convertsion here. Here's an iterative version of same idea. Note that we only shrink the range between l and r but never change k. Thanks for sharing! public int findKthLargest(int[] A, int k) { k = A.length - k; // convert to index of k largest int l = 0, r = A.length - 1; while (l <= r) { int i = l; // partition [l,r] by A[l]: [l,i]<A[l], [i+1,j)>=A[l] for (int j = l + 1; j <= r; j++) if (A[j] < A[l]) swap(A, j, ++i); swap(A, l, i); if (k < i) r = i - 1; else if (k > i) l = i + 1; else return A[i]; } return -1; // k is invalid } @jeantimex why is j-- ?why not --j?--j make the greater 3 number on the 3 left such as 4 2 1 5 3 Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/18662/ac-clean-quickselect-java-solution-avg-o-n-time
CC-MAIN-2017-39
refinedweb
778
81.46
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. Replacing product_category with external data source I am trying to replace the product_category model with an external datasource by extending the product_category model and overwriting the read method. I used this topic as an example: I don't want to replace or modify some values, but I want to use an external api to fetch the categories. So what I tried was fetching a list of categories with the python requests library, transforming the items in the list to the key/value structure that Odoo uses and returning this list. def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): url = '' params = { 'apikey': '....', 'limit': 20 } r = requests.get(url, params=params) res = [] for cat in r.json(): res.append({ 'id': cat[u'id'], 'complete_name': cat[u'name'], 'parent_id': None }) return res I got it working without errors, except for the fact that the actual json-rpc call only returns 1 result while a print statement in the method shows 20 items. I know that the one item that is returned by the json-rpc call has an identical id to one of the product categories in the odoo system and the other 19 not. What am I missing here? Maybe there is a more official
https://www.odoo.com/forum/help-1/question/replacing-product-category-with-external-data-source-59374
CC-MAIN-2017-04
refinedweb
236
53.31
Full code is here: Here's a minimal, complete, verifiable example: import random def newGame(): curveSetup() printStatistics() def curveSetup(): global curve curve = random.randint(12,35) global lvl lvl = 1 def printStatistics(): global expMax expMax = (lvl*curve) global lvl print "Character Level: "+str(lvl) newGame() Warning (from warnings module): File "D:\Code\PyRPG.py", line 64 global lvl SyntaxWarning: name 'lvl' is used prior to global declaration You're using lvl before declaring it global in printStatistics(), hence "name 'lvl' is used prior to global declaration". It is a warning only, since having global lvl anywhere in the function makes lvl global. The code still works. To get rid of the warning, move the global before use in that function: global lvl expMax = (lvl*curve) In fact, global lvl is not required in this function at all. It is only needed if you modify the global variable. Here the value is only used in calculations without changing lvl itself. Note that your program is horribly misusing globals. As you can see, it makes the logic difficult to follow. Global variables should be used rarely, and ideally for constants that don't change and won't require global declarations. Prefer classes to hold state instead.
https://codedump.io/share/qMn09Z6OrIP8/1/what-does-quotx-is-used-prior-to-global-declarationquot-mean-python-2
CC-MAIN-2017-30
refinedweb
204
55.34
WSClient++ For DotNet 1.0 Sponsored Links Download location for WSClient++ For DotNet 1.0 WSClient++ generates C# source code to connect to ASP.NET Web Service for Silverlight/WPF Applications, Supports IPropertyChangeNotifier and Multiple Web Services in single namespace....read more NOTE: You are now downloading WSClient++ For DotNet 1.0. This trial download is provided to you free of charge. Please purchase it to get the full version of this software. Select a download mirror WSClient++ For DotNet 1.0 description WSClient++ generates C# source code to connect to ASP.NET Web Service for Silverlight/WPF Applications, Supports IPropertyChangeNotifier and Multiple Web Services in single namespace System Requirements: Adobe Air...read more WSClient++ For DotNet 1.0 Screenshot WSClient++ For DotNet 1.0 Keywords WSClient For DotNet DotNet IPropertyChangeNotifier Supports IPropertyChangeNotifier Multiple Web Services Bookmark WSClient++ For DotNet 1.0 WSClient++ For DotNet 1.0 Copyright WareSeeker.com do not provide cracks, serial numbers etc for WSClient++ For DotNet 1.0. Any sharing links from rapidshare.com, yousendit.com or megaupload.com are also prohibited. Featured Software Want to place your software product here? Please contact us for consideration. Contact WareSeeker.com Related Software The Web Services Listener is a COM component that allows your organization to consume .NET Web Services without the need of installing the .NET framework or any other .NET component. This means your development team can use available .NET web services Free Download shboo.com(web design and ecommerce services Yorkshire) presenst crystal sudoku twist. Sudoku with a twist. Free Download Create & deploy web services Free Download Poster provides a developer tool for interacting with web services and other web resources. Free Download AmazonLib is an API for Amazon.coms Web Services. It is written in PHP. It simplifies the process of writing applications using Amazons Web Services. AmazonLib consists of four main components: 1) nurest.php -- a REST parser class which Free Download With the introduction of Web services as an open standards integration technology for Enterprise Application Integration (EAI) and Business to Business (B2B) Integration, you can do many things to promote operational efficiencies and thus ensure the Free Download Complete and growing collection of remotely hosted web tools, most services are ad free, and have extremely large free quotas Free Download Tool for the testing a Web Services. Free Download Latest Software Popular Software - The Python Web Services Developer, Part 2 - The web of services: using XML_RPC from PHP - Web services insider, part 1: Reflections on SOAP - How the IBM Web Services Compares with Microsoft Visual Studio .NET - Professional ASP.NET : Exposing Web Services - Web services and J2EE connectors for B2B integration - Is Web services the reincarnation of CORBA? - ASP.NET Web Services : Asynchronous Programming Favourite Software
http://wareseeker.com/download/wsclient-for-dotnet-1.0.rar/7e8c7596f
CC-MAIN-2015-18
refinedweb
456
51.85
It appears there may be a bug in the win32file.SetFileTime() method (or else there's a big bug in my understanding of how this pywin32 method is intended to work). We needed the ability to set the ctime,atime,mtime tuple of windows files. The python standard library method os.utime() only works for ctime,mtime. So we turned to pywin32 -- and foudn the SetFileTime seemed to be exactly what we needed. But it appears win32file.SetFileTime() performs time-zone related transformations that are tripping us up. Specifically, it alters the datetimes it is passed based on the local-system timezone. As a test, we passed the results from win32file.GetFileTime() win32file.SetFileTime(). In our view, this should have done nothing -- but instead it altered the ctime,atime,mtime of the files by advancing the times. I think a quick example can highlight the issue more clearly. Assume the following code is filetest.py: import win32file hnd = win32file.CreateFile('file.txt', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) ct, at, mt = win32file.GetFileTime(hnd) win32file.SetFileTime(hnd, ct, at, mt) hnd.close() We run it like this: C:\> ECHO hi > file.txt C:\> DIR file.txt 03/10/2012 12:55 PM 5 file.txt 1 File(s) 5 bytes C:\> PYTHON filetest.py C:\> DIR file.txt 03/10/2012 05:55 PM 5 file.txt 1 File(s) 5 bytes Our local timezone is EST (which today is GMT-5). Notice the last-write time is now 5-hours in the future (note: so are ctime, and atime, but for brevity, I've omitted the listing). It looks like SetFileTime() assumed it was passed a collection of times that represented localtime, and performed local -> GMT conversion. But this is counter to the documentation available with GetFileTime(). According to MSDN, a FILETIME structure (like those returned from GetFileTime()) is: "...a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC)..."\(v=vs.85).aspx After spending some head scratching time on this, we hacked up a quick C version to confirm our understanding was correct about GetFileTime/SetFileTime: #include <stdio.h> #include <windows.h> int main() { HANDLE hnd = CreateFile("file.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hnd == INVALID_HANDLE_VALUE) { printf("error, couldn't open file.txt\n"); return -1; } FILETIME ctime, atime, mtime; if (GetFileTime(hnd, &ctime, &atime, &mtime) == 0) { printf("unable to retrieve filetime(s)"); return -1; } if (SetFileTime(hnd, &ctime, &atime, &mtime) == 0) { printf("unable to set filetime(s)"); return -1; } CloseHandle(hnd); return 0; } This program works exactly as we expected and it does not alter any of the the file times. So we spent some additional time drilling down in the win32file.i swig code. The SetFileTime() declaration starts on line 718. On line 740, it begins processing the arguments passed (with code sections for each of the three times). Here's the one for ctime if (!PyWinObject_AsFILETIME(obTimeCreated, &LocalFileTime)) return NULL; // This sucks! This code is the only code in pywin32 that // blindly converted the result of AsFILETIME to a localtime. // That doesn't make sense in a tz-aware datetime world... if (PyWinTime_DateTimeCheck(obTimeCreated)) TimeCreated = LocalFileTime; else LocalFileTimeToFileTime(&LocalFileTime, &TimeCreated); lpTimeCreated= &TimeCreated; (NOTE: we did NOT add the somewhat offensive "sucks" comment. That was left over from whoever edited this code last) There's quite a bit of moving parts at this level of depth in the pywin32 code -- but it would appear to our superficial understanding that the pywin32 code at this point is converting the time passed to localtime. Is that correct? Has anyone else encountered a problem with win32file.SetFileTime() -- or are we just completely off our nut here? Our test setup: Windows 7 (64-bit) Running Python 2.7.2 (32-bit) pywin32-217 The filesystem we are writting to is NTFS Michael Vincent 2012-10-02 I'm seeing this behavior also, very annoying. Maybe the word "possible" should be removed from the defect title? It's certainly there. My use case for using this functionality as follows: I'm needing to set file creation times to their modification time so that media file viewers which can't extract this metadata from files (e.g. home videos) can get it from the timestamp. Roger Upole 2012-10-15 This is a leftover from older systems (95 &98) that stored these dates in local time. I seem to remember this having been discussed before somewhere, and the problem with fixing it was that it was already being used by pre-adjusting the time passed in. Changing it to no longer convert to local time will cause problems for anyone already using it that way. Also, I think FAT file systems may still use local time even now. Maybe we could add a flag to do localtime conversion, and defaults to True so current code continues to work as-is, but new code can use UTC by passing False. Mark Hammond 2012-10-15 That sounds like a great compromise! Mark Hammond 2012-11-24 Build 218 allows a new param to indicate whether the times are UTC - that defaults to false for b/w compat reasons, but should still allow this function to be used correctly. Mark Hammond 2012-11-24
http://sourceforge.net/p/pywin32/bugs/584/
CC-MAIN-2015-22
refinedweb
883
66.84
MySQL Creating account and changing password MySQL Creating account and changing password This MySQL provide the new creating account... with editing /etc/group manually. MySQL create new user account use the login user in mysql user in mysql how to create user in mysql? Please visit the following link: Account Management Statements the statement CREATE USER. It is used to create a new MySQL account. But for using... by inserting in user table of mysql database with User=?? or creating a user account...; In MySQL user account information?s are stored in mysql MySQL Creating and Deleting Database syntax is : CREATE USER user_name [IDENTIFIED BY[password] 'password'] Create User statement is used to create a new MySQL account. For using... CREATE USER privilege or DELETE privilege for the mysql database. The general How to Create a Different User Account in Windows 8? in creating a user account, here you are. In this windows 8 tutorial, we will discuss How to create a different user account in Windows 8? Once you install..., if you are not interested to create a password for the user account, you can MySql MySql what is default password of mySql, and how i configure mySql... to provide the Password for the user root at the installation time. You may try to login as: User: root Password: Blank (not password) just press enter if password MySQL Client . The MYSQL Graphic Clint The SQL 'create user... Engle This all-in-one tool will help you create, manage and edit MySQL databases.... The program makes working with MySQL easy without hiding the language from the user MySQL Client ; The MYSQL Graphic Clint The SQL 'create user' and 'grant' commands... similar to how MySQL disseminates it (that is, electronically for download... program, use an account that still has a pre-4.1-style password. * Reset MySQL How to Topic ; How to test a new user account and password in MySQL... the Password for Your Own User Account?...; How To Change the Password of Another User Account Welcome to the MySQL Tutorials the new creating account or you want to change the password then make new user .This lesson you learn how to create new password... Account Management Statements In MySQL user MYSQL MYSQL How to create time and date based trigger in mysql MySQL Time Trigger how can i create a mysql database to connect to this code - JDBC how can i create a mysql database to connect to this code i need help creating a mysql database for this code. code is import java.awt....(Exception e){} } else{ System.exit(0); } } }); tp.addTab("Create Account",panel MySQL Training ? Online Free MySQL Training process . Creating account, changing root password and deleting anonymous accounts This MySQL provide the new creating account or you want to change the password then make new user .This lesson you learn how MySql Alter User MySql Alter User This example illustrates how to alter user table. In this example we alter user table in which add a column by query "ALTER TABLE user... column. Query CREATE USER 'user'@'localhost' IDENTIFIED BY '1234556978 MySQL Front we will learn how to: 1. connect to the MySQL server 2. create..., the task of creating and manipulating MySQL databases is a daunting task. It is often... statements MySQL Front allows anyone to easily create and manage How to Create User Account in Windows 8 with Windows live ID to create an user account in Windows 9 using your windows live ID. 1. To start... id is added for creating the user account. 7. Once you e-mail id... to finish button below. 8. You have now successfully created your user account Creating an Encyclopedia using Java & mySQL 5 - Java Beginners Creating an Encyclopedia using Java & mySQL 5 Dear Editor, I'm... programming 3 since one month ago. I want to create an encyclopedia for my own practices... are to allow the user to search for a word. If the word is not found, a message would Change root password of MYSQL using Java Change root password of MYSQL using Java In this tutorial, you will learn how to change the root password of MYSQL database using java code. For every database, you have to reset the root password for its security. For mysql Creating a Database in MySQL Creating a Database in MySQL  ... the JDBC driver, you will learn how we can create our database. A database is a .... In this example we are going to create a database by MySQL and with the help MySQL User Interface , Create function syntax , Drop function Syntax . MySQL adding new user... create function Syntax The user-defined function is a way to extend mysql... to create it. MySQL DROP Function Syntax By this statement you can drop the user change password - JSP-Servlet a simple web application using mysql and jsp. now i want to create a web page for a user. this web page consists of changing the password for the existing user.../her password. so first user has to enter his/her password in the current MySQL For Window Graphical User Interface (GUI) allows you to create/edit all MySQL database objects..., you should install MySQL on Windows using an account that has administrator..., instructions on how to get started. This MySQL help page also gives more advanced MySQL Create Database MySQL Create Database MySQL... and choosing the Create New Table option. The MySQL Table Editor can... & 5 library to allow easy and user-friendly editing of MySQL tables. Note How to view database for user when they login in netbeans and mysql? How to view database for user when they login in netbeans and mysql? I create a web page where when user login they have to fill in a form, after... but it come out with all the other user information too. I'm using netbeans and mysql PHP MYSQL Interview Questions a requirement to create a new database everytime a user request to create a new..., just wondering how to create a database using PHP script? In reference to PHP...PHP MYSQL Interview Questions What kind of questions can be asked Setting up MySQL Database and Tables Database and you know how to work with the MySQL database. To access the database you should have valid user name and password. Let's now start by creating... Setting up MySQL Database and Tables   Connect JSP with mysql named 'usermaster' in mysql. To create this database we need to run the following... with mysql : Now in the following jsp code, you will see how to connect... parameters of string type connection url, user name and password to connect Mysql PHP Select ;girish"; $user="root"; $password="root"; $host="192.168.10.126"; $link= mysql_connect($host,$user,$password) or die("... Mysql PHP Select   Java Password Field = "jdbc:mysql://localhost:3306/"+dbName; String user = "root"; String password...Java Password Field In this section we will discuss how to use password field in Java. To create a password field in Java Swing JPasswordField is used mysql mysql how to open\import table in .dbf format in mysql Creating a MySQL Database Table to store Java Types Creating a MySQL Database Table to store Java Types... mind that whether the MySQL supports java types or not. This section describes how to create a table in MySQL database that stores all java types. Here we MySQL Configuration MySQL Configuration In this lesson you will read how to configured of mysql. This lesson you will also read how to easily configuring your server under window . The mysql MySQL remove MySQL remove We can use MySQL Delete statement to implement the removal on the database. If you want to remove any record from the MySQL database table then you can use MySQL Username password that checks whether the username and password is valid or not. If the user...Username password Hi there, I am trying to create a page on a JFrame... with the validation, so that if the username and password match it will continue Password encryption and decryption . Is there anyway that you could teach me how to encrypt the password and store it in database? and then call back the encrypted password to let the user login?? The given allow the user to enter username, password along with other fields mysql is the link for the page from where you can understand how to Download and Install MySQL...mysql How can install My sql drivers using a jar File Hi you need to download the mysql-connector jar file for connecting java program Installing MySQL on Windows ; In this section you will learn how to install MySQL 5.0 on windows... configuration wizard which allows user to install and configure a MySQL server...: MySQL installation wizard create a new entry in the start menu windows Creating table using DBCP = con.createStatement(); String QueryString = "CREATE TABLE user_master1(User_Id INTEGER NOT NULL AUTO_INCREMENT, " + "User_Name VARCHAR(25), UserId VARCHAR(20...;com.mysql.jdbc.Driver"); bds.setUrl("jdbc:mysql://localhost:3306/mydb Mysql Permission Mysql Permission Mysql Permission allows the user to connect to the database, Mysql... the permission to connect. All user /host/password combination are listed in this table Login authentication & mysql - Java Beginners I need to create a user account which is the user can register their personal account with the username and password, must save it in database (MySQL... Authentication with MySql using Java Swing: 1)Create a java class PHP MySQL Login Form . create table user (username varchar(10), password varchar(10)); After... a table which keeps the user-id and respective password, in this tutorial we will study how to create a login form, connect with the database server and login HOW WRITE GREEK CHARACTERS INTO MYSQL BY JSP ? :mysql://localhost:3306/XXXXX?user=userName&password=usersPassword&...HOW WRITE GREEK CHARACTERS INTO MYSQL BY JSP ? HALLOW TO ALL ! I'M... CODE IS BELOW DROP database IF EXISTS XXXXX ; CREATE DATABASE XXXXX DEFAULT doubt in connecting mysql in flex - XML doubt in connecting mysql in flex The ?Create application from database? is a Flex 3 feature that enable you to create simple applications in few... MySql Connection Host URL: localhost Database Name:users User Name: root Create a counter in mySQL 5 database through Java - SQL Create a counter in mySQL 5 database through Java Dear Editor... for 12 times. May i know how to create a counter (some sort like word search... question regarding Java & mySQL 5 database PHP User Authentication Login and password check Tutorial Creating a click counter is pretty simple. All it requires is after the code... to the database. $dbname="name"; #Password to verify its you. $dbpass="...;; //Now to connect to mySQL. $connect = mysql_connect("$dbhost" MySQL PHP Insert , user, password and host name is used to connect with MySQL database. Incase...= mysql_connect($host,$user,$password) or die("Could not connect: ".mysql.... Query for creating table named MyTable : mysql> CREATE TABLE MyTable MySQL Database Training ; MySQL Training Course Objectives How to use SQL to get output reports with MySQL. How to modify MySQL data with SQL. How to create a simple MySQL database Table MySQL MySQL Create queries in SQL that will retrieve the following information: Select all the clients whose surnames start with the letters 'GU' Select all clients in catered accommodation Select all the clients in non-catered MySQL PHP Query delete ;; $link= mysql_connect($host,$user,$password) or die("Could not connect: "...= mysql_connect($host,$user,$password) or die("Could not connect: ".mysql... on 'MySQL PHP Query delete'. To understand the example we create a table 'MyTable MySQL Create Table MySQL Create Table Here, you will read the brief description about the MySQL create table. The CREATE TABLE statement is used for creating a table in database.  PHP Chat Systems A MySQL Driven will show you how to create a simple chat script using PHP and MySQL database... and paste on your mysql editor or console: create table chat(userid int(10... will be the default user who can logged in and chat with someone else, similarly create more While creating a jar how to add MySQL database to project While creating a jar how to add MySQL database to project Hi, Please tell me how to attach MySQL database to the Java project while building a jar or their is any other process MySQL PHP Update ;girish"; $user="root"; $password="root"; $host="192.168.10.126"; $link= mysql_connect($host,$user,$password) or die("Could... respectively. Query for creating table named MyTable: mysql> CREATE TABLE Create a Table in Mysql database through SQL Query in JSP named 'usermaster' in mysql and create table "user_master". Create... Create a Table in Mysql database through SQL Query in JSP...; This is detailed java code to connect a jsp page to mysql database and create a table of given MySQL PHP Query delete ;; $link= mysql_connect($host,$user,$password) or die("Could not connect...;; $link= mysql_connect($host,$user,$password) or die("Could not connect: "... MySQL PHP Query delete   alter table create index mysql alter table create index mysql Hi, What is the query for altering table and adding index on a table field? Thanks Hi, Query is: ALTER TABLE account ADD INDEX (accounttype); Thanks MySQL Connection String : MySQL user account id to connect with MySQL. Pwd: MySQL user password... network address, user id, password and name of database.  ... MySQL Connection String   Ant Script to Create Mysql Table Ant Script to Create Mysql Table This example illustrates how to create table through...;sql.user"> is used to define user name of the database. The fourth MySQL Download necessary attributes *VServer user's option *Converts password... MySQL Download The MySQL Download MySQL software is published under an open source license Foreign key in mysql Foreign key in mysql Hi I am creating a website and linking it to a database using php and mysql. I need to create the databases in phpmyadmin..., there are foreign keys in some of the tables - does anyone know how to link Connect JSP with mysql you how to connect to MySQL database from your JSP code. First, you need... a database: First create a database named usermaster in mysql. Before running... url, user name and password to connect to database. */ connection login page php mysql example login page php mysql example How to create a login page for user in PHP Mysql? Please provide me a complete tutorial. Thanks in Advance MySQL Database user account for the web application itself *Create a PHP MySQL Site... in Dreamweaver. It will also cover some basic MySQL user account settings... for MySQL database and takes into account its features. Our Database Designer MySQL Books and MySQL to create Web sites, how to build six of the most everyday, practical... source database server. Whether you are a seasoned MySQL user looking to take your...-learn to create a dynamic online environment using only three programs. PHP, MySQL MySQL Tools could view the MySQL table schemas but not change or create new ones.  ... MySQL Tools MySQL Migration Toolkit The MySQL Migration Toolkit is a powerful framework jsp using include & with mysql "),application.getInitParameter("user"),application.getInitParameter("password...jsp using include & with mysql Sir, I am creating a login application using jsp & Mysql. The Codes are--- Html File...... < struts 2 mysql struts 2 mysql In the example : how is the username and password(in insertdata.jsp) which is entered by the user is transferred to the { ("INSERT employee VALUES mysql - SQL mysql hi i am using mysql. i want to create simple table with the foreing key. the reference table is also created. send to me how to create... the problem : CREATE TABLE parent (id INT NOT NULL, PRIMARY Struts 2 MySQL of MySQL driver ("org.gjt.mm.mysql.Driver"). Now, Make an account... Struts 2 MySQL In this section, You will learn to connect the MySQL database with the struts 2 application MySQL Order By MySQL Order By Here, you will learn how to use MySQL Order By clause. The Order By clause is used for sorting the data either ascending or descending order according to user DriverClass hibernate mysql connection. :3306/hibernate</property> Setting user name and password as- <property...DriverClass hibernate mysql connection. What is DriverClass in Hibernate using mysql connection? DriverClass implements java.sql.Driver. mysql - WebSevices , myuser Auth-Type := Local, User-Password == mypass@wd Session-Timeout = 60... = 0x000000020104a70101048101, user196 Auth-Type := Local, User-Password..., User-Password == mypass@wd Session-Timeout = 3600 encrypt the username and password using PHP encrypt the username and password using PHP How can we encrypt the username and password using PHP? Hi friends, You can use the MySQL... into user (password, ...) VALUES (PASSWORD($password?)), ...); Thanks MySql,java MySql,java In MySQL table i am adding the fields of name,photo,video... maths) but here i am not creating the separate table for each table. tell me procedure is it necessary to create different tables for each category.and also MySQL PHP Search $database="girish"; $user="root"; $password="root"; $host="192.168.10.126"; $link= mysql_connect($host,$user,$password... the database name, user name, password name and host name that is used to access DataBase Connectivity with MySql in Visual Web JSF Application Using Net Beans IDE ; This Application illustrates how to create database.... In this application, we are going to create a database connection with mysql step... browser. 1. Creating database table Right click on Database and create New MYSQL - SQL MYSQL how to select last row in table?(MYSQL databse) How to select last row of the table in mySql Here is the query given below selects tha last row of the table in mySql database. SELECT * FROM stu_info forget password? forget password? can anyone help me? how to create a module of forget password?the password can reset by generate random password and send to user's email..i develop the php system using xampp and dreamweaver MySQl - SQL MySQl How to Remove password for root in MY SQl.....? Please Provide the steps Immediately Java Bank Account Application Java Bank Account Application Here we have created a Bank Account Application that will allow users to do their transactions. For this, user will have to enter all the required information like, name, account number, account type how to use mysql event scheduler in hibernate how to use mysql event scheduler in hibernate Hi all, I am creating... of time, i need to use mysql event scheduler My query is like this create event... : Unexpected Token Create and when u use this query in function session.createSQLQuery How to rename MySQL table? How to rename MySQL table? The designing and development of any software... a review you many have to change the name of database. The MySQL database... the table. Suppose you have a table called called account and now you have MySQL by MySQL by In the following example you will see the how to use the MySQL by. Here, we will use...; Table: employee CREATE TABLE `employee` (  MySQL Not In MySQL Not In MySQL Not In is used to updates only those records of the table whose fields 'id... The Tutorial illustrate an example from 'MySQL Not In'. To understand and grasp how to insert and retrieve an image from mysql using java - Java Beginners how to insert and retrieve an image from mysql using java how to insert and retrieve an image from mysql using java? Hi friend, Code... Connection connection = null; /* Create string How can we create a database using PHP and mysql? How can we create a database using PHP and mysql? How can we create a database using PHP and mysql MySQL Administrator significantly better visibility into how your databases are operating. MySQL... user interface to the MySQL server. It's called simply and appropriately, "MySQL... MySQL Administrator   mysql query mysql query how do transfer into the excel data to my sql Hello Friend, First of all create a dsn connection.For this,Follow... the mysql connection in your php and store the list values inside the mysql Mysql PHP Where ;girish"; $user="root"; $password="root"; $host="192.168.10.126"; $link= mysql_connect($host,$user,$password) or die... respectively. Query for creating table named MyTable: mysql> CREATE TABLE MyTable Creating a database Creating database At first create a database in MySql database named studentadmissionprocess then create a table stud_admission as Use the SQL code to create table stud_admission stud_admission CREATE TABLE stud_admission JDBC Example with MySQL will learn how we can create our database. Creating a Database...; Creating a MySQL Database Table to store Java Types Dear user, consider.... This section describes how to create a MySQL database table that stores all java types Ask Questions? If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://www.roseindia.net/tutorialhelp/comment/97962
CC-MAIN-2013-20
refinedweb
3,481
65.01
#include using namespace std; struct Base { virtual void foo(); }; struct Derived : Base { virtual void foo(); }; void Base::foo() { cout << "Base::foo() was called.\n"; } void Derived::foo() { cout << "Derived::foo() was called.\n"; } int main() { Base* b = new b; b.foo(); delete b; b = new Derived; b.foo(); delete b; return 1; } What, then, is a pure virtual function, and how do these fit into abstract classes? Pure virtual functions are simply functions that have no implementation in the base class, relying on derived classes to provide their own implementations. This means that no runtime instances (objects) can be created from the base class - these classes only exist to act as generic blueprints for other classes. This can, when used correctly, really help tidy up your class hierarchy. You define a pure virtual functions like this - virtual void foo() = 0; Then derived classes simply declare the function as normal, ie. - void foo(); Note that because you cannot create runtime instances of abstract classes, this will fail - class Abstract { virtual void foo() = 0; }; int main() { Abstract a; // Error here. } It is, of course, perfectly legal to create pointers such as Abstract* a; for the purpose of dynamic runtime casting. An abstract class, often also called an abstract base class, is a class that cannot be instantiated due to the presence of one or more virtual functions that are declared but not implemented by the class, ie pure virtual methods. It's a way of telling yourself: Do not create create instances of this class, subclass it. abstract abstract class Polygon { abstract public double getArea(); } abstract class Polygon { abstract public double getArea(); } type TPolygon = class(TObject) public function GetArea: double; virtual; abstract; end; type TPolygon = class(TObject) public function GetArea: double; virtual; abstract; end; See the other writeups for a C++ example. My C++ is too rusty, sorry. Making the method abstract says explicitly that the class is too generic to give a reasonable default implementation for the abstract method, and that all concrete child classes must override it in thier own way. A base class that is intended only for subclassing and not for direct use defines an interface contract that is shared by all of its child classes. However, calling code can deal with an object that appears to be of the base type, and does not need to know how the method is implemented by the particular child class. Thus the calling code deals only with the interface contract defined by the base class. Log in or register to write something here or to contact authors. Need help? accounthelp@everything2.com
https://everything2.com/title/abstract+class
CC-MAIN-2017-22
refinedweb
432
58.62
: github.com/mads379/SublimeListTabs /Mads Not to be rude, but unless I'm missing something, this is what the Goto Anything panel does. (control/command + P). Anyway, its nice to see people looking to give back the the ST community. Almost However, if you start typing in to Goto Anything view it will start searching for anything. With this plugin it will just filter the tabs so it's more efficient for navigating through your open files. Also, this doesn't activate the 'quick preview' feature. Some people love it, I personally don't so that's nice. This might change in the future though if the semantics of 'show_quick_panel' is changed So it isn't that different from 'Goto Anything' but it's different enough that I wanted to write a plugin for it @mads_hartmann I don't know if my code below may be of interest to you . I use two shortcuts to run this, one to list the files alphabetically and one to list by their last modified date. It's ignoring new/untitled files (and different groups) for the moment. I might modify it to work with new/blank views - I'll use 'datetime.now()' as their 'modified' value, but I just need to convert this to a float value (to prevent it error-ing out when comparing it to the other modified (float) values). import sublime_plugin from os import path from operator import itemgetter from datetime import datetime class OrderedFilesCommand(sublime_plugin.WindowCommand): def run(self, index): OF = OrderedFilesCommand OF.file_views = ] win = self.window for vw in win.views(): if vw.file_name() is not None: _, tail = path.split(vw.file_name()) modified = path.getmtime(vw.file_name()) OF.file_views.append((tail, vw, modified)) else: pass # leave new/untitled files (for the moment) if index == 0: # sort by file name (case-insensitive) OF.file_views.sort(key = lambda (tail, _, Doh): tail.lower()) win.show_quick_panel([x for (x, y, z) in OF.file_views], self.on_chosen) else: # sort by modified date (index == 2) OF.file_views.sort(key = itemgetter(2)) win.show_quick_panel( (datetime.fromtimestamp(z)).strftime("%d-%m-%y %H:%M ") + x \ for (x, y, z) in OF.file_views], self.on_chosen) def on_chosen(self, index): if index != -1: self.window.focus_view(OrderedFilesCommand.file_views[index][1]) This is (almost) exactly what I've been looking for. The only addition I'd like is to list tabs available in all sub-windows. Thanks!
https://forum.sublimetext.com/t/listtabs/5501/4
CC-MAIN-2016-44
refinedweb
400
50.53
Question: So you know off the bat, this is a project I've been assigned. I'm not looking for an answer in code, but more a direction. What I've been told to do is go through a file and count the actual lines of code while at the same time recording the function names and individual lines of code for the functions. The problem I am having is determining a way when reading from the file to determine if the line is the start of a function. So far, I can only think of maybe having a string array of data types (int, double, char, etc), search for that in the line and then search for the parenthesis, and then search for the absence of the semicolon (so i know it isn't just the declaration of the function). So my question is, is this how I should go about this, or are there other methods in which you would recommend? The code in which I will be counting will be in C++. Solution:1 Three approaches come to mind. Use regular expressions. This is fairly similar to what you're thinking of. Look for lines that look like function definitions. This is fairly quick to do, but can go wrong in many ways. char *s = "int main() {" is not a function definition, but sure looks like one. char * /* eh? */ s ( int /* comment? // */ a ) // hello, world /* of confusion { is a function definition, but doesn't look like one. Good: quick to write, can work even in the face of syntax errors; bad: can easily misfire on things that look like (or fail to look like) the "normal" case. Variant: First run the code through, e.g., GNU indent. This will take care of some (but not all) of the misfires. Use a proper lexer and parser. This is a much more thorough approach, but you may be able to re-use an open source lexer/parsed (e.g., from gcc). Good: Will be 100% accurate (will never misfire). Bad: One missing semicolon and it spews errors. See if your compiler has some debug output that might help. This is a variant of (2), but using your compiler's lexer/parser instead of your own. Solution:2 Your idea can work in 99% (or more) of the cases. Only a real C++ compiler can do 100%, in which case I'd compile in debug mode ( g++ -S prog.cpp), and get the function names and line numbers from the debug information of the assembly output ( prog.s). My thoughts for the 99% solution: - Ignore comments and strings. - Document that you ignore preprocessor directives ( #include, #define, #if). - Anything between a toplevel {and }is a function body, except after typedef, class, struct, union, namespaceand enum. - If you have a class, structor union, you should be looking for method bodies inside it. - The function name is sometimes tricky to find, e.g. in long(*)(char) f(int);. - Make sure your parser works with template functions and template classes. Solution:3 For recording function names I use PCRE and the regex "(?<=[\\s:~])(\\w+)\\s*\\([\\w\\s,<>\\[\\].=&':/*]*?\\)\\s*(const)?\\s*{" and then filter out names like "if", "while", "do", "for", "switch". Note that the function name is (\w+), group 1. Of course it's not a perfect solution but a good one. Solution:4 I feel manually doing the parsing is going to be a quite a difficult task. I would probably use a existing tool such as RSM redirect the output to a csv file (assuming you are on windows) and then parse the csv file to gather the required information. Solution:5 Find a decent SLOC count program, eg, SLOCCounter. Not only can you count SLOC, but you have something against which to compare your results. (Update: here's a long list of them.) Interestingly, the number of non-comment semicolons in a C/C++ program is a decent SLOC count. Solution:6 How about writing a shell script to do this? An AWK program perhaps. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2018/06/tutorial-finding-function-name-and.html
CC-MAIN-2018-43
refinedweb
694
74.19
I’ve been alerted that some of the release information listed for Silverlight 2 needs to be updated. Silverlight 2 and RTW is slated for Fall.? How about supporting .flv since most of the video on internet currently is using this format? Silverlight isn’t designed with an extensible codec model in mind, so there is no date/version announced for). Currently the alternative to this is Expression Media Encoder. It will have support for taking different formats like flv and converting them into Silverlight supported formats. 2. Which streaming server protocols does Silverlight support currently and which will be supported in near future? MMS now and future. 3. Why the support for displaying a .gif image is is missing? When it will be added? 4. Is the size of Silverlight 2 Beta plug-in expected to increase by the time of final release? Which namespaces Microsoft is planning to add in final release. It may increase a little, but the size is not known at this time. Beta 2 will contain the full set of namespaces. To see the list of namespaces in Beta2 you will have to wait. 5. What would be the full and final set of controls that are expected to be included with Silverlight 2 - final release? The controls in Beta 2 will be the full set in the final release. You will be able to see that once Beta 2 comes out. 6. When is Silverlight 2 - final version expected to be released? We are targeting late Summer Here is a rough timeline:Silverlight 2.0 Beta 1 (Q1CY08 with limited (non commercial) Go-Live) Silverlight 2.0 Beta 2 (Q2CY08 with Go-Live)Silverlight 2.0 RTM (Summer 2008) – Exact timing TBD Silverlight v.next – We are working on a v.Next plan and have nothing to announce at this time Silverlight for mobile – No date available 7. Is there going to be a big difference in terms of features/component model etc. in Silverlight 2 beta and final release (just like it is the case with 1.1 Alpha and 2.0 Beta)?There will be breaking changes between Beta 1 and Beta2 of Silverlight 2 but the changes will not be drastic between Beta2 and Final Release. You can expect almost similar feature set as with Beta2 which is expected to come out in the Month of May 2008.Also, if you develop your websites using 1.0 it will be compatible when 2.0 comes out. Then you simply have to update your skill set capabilities.Silverlight 1.0 is shipping separately so we can provide key customers the stability and support they need to begin delivering fast, cost-effective delivery of high-quality media experiences to all major browsers running on Mac OS or Windows and soon Linux. There is only one Silverlight so all the capabilities of 1.0 will be unified in the 2.0 release. 8. Will Silverlight 2 final release offer some local Caching API (with automatic expiration, notifications etc.) just like System.Web.Cache API in ASP.Net 2.0/3.5?It’s already in the Beta and called ‘Isolated Storage’ Isolated storage can solve some of the requirements of caching APIs (but without the notification), the browser cache can handle others (again, without notification). 9. In order to call a WCF Service from Silverlight 2 Beta, you have to use “basicHttpBinding” currently. Will Silverlight support additional bindings in near future like MSMQBinding and others? We have not planned for this feature as of yet. So I would personally say ‘probably not’. However this is an interesting feedback 10. Does Microsoft have any authentic estimates of Silverlight usage by the end users? Adobe claims 90% coverage of Flash, We know Silverlight is new but would like to know the current coverage, estimated coverage in next 1 year and Microsoft’s plans to increase its coverage, to move forward with our development efforts with even more confidence J We’ve announced that we’re at about 1.5 million downloads per day at the moment. The problem with putting out some % values like Adobe do is that it is hard to be accurate and hard to verify. Since the launch of Silverlight 1.0, the number of partners participating in the Microsoft Silverlight Partner Initiative has already grown to more than 60 organizations, and new customers have delivered Silverlight applications. Most recently UVNTV.com and NBA.com have committed to going live on Silverlight. We are very excited about success of Silverlight 1.0, download numbers continue to be in line with expectations to date. You can get an idea about the future of Silverlight with the amount of efforts that are being put on this technology. Have a look at the partner initiatives that would attract hardware/software developers, solution providers etc. I would recommend you to visit the news and announcements section frequently to remain updated about technology. If you would like to receive an email when updates are made to this post, please register here RSS PingBack from Mint azt már hallhatátok, a MIX08 konferencián bemutatták a Silverlight (korábban WPF/E) 2.0-ás (korábban What about the plugin for Opera, IE6 on Windows 2000 and Safari for Windows??????????? I came across a great post about updated Silverlight 2 roadmap . Silverlight is about 7 month old kid Silverlight: Silverlight Roadmap questions Ashish Thapliyal Third Silverlight v1.0 Servicing Release Any update on: - Current beta version is not search engine friendly, is going to be this feature on the final release? - Ability to save or print a given canvas form silverlight (right now you have to go to the server side and paint it using WPF or GDI+). Thanks Braulio h2.entry-title {font-size: 1.1em; clear:left;} ul.hfeed {list-style-type: none;} li.xfolkentry {clear Hi, Any idea when Silverlight 2.0 will be released to market? It will be very interesting to see Silverlight 2.0 final release against JavaFX 1.0, as both said in their roadmaps, will be available this fall. I am using Silverlight 2.0. The narrowcast video will cache in client local machine, after caching it will start to play. I feel, caching is fine. But i don't want user to see my cached copy right's video and audio files. -- Any Help, Thanks in Advance
http://blogs.msdn.com/ashish/archive/2008/04/03/silverlight-roadmap-questions.aspx
crawl-002
refinedweb
1,064
67.55
15 September 2011 13:49 [Source: ICIS news] LONDON (ICIS)--Economic growth in the EU stalled in the second quarter of 2011 after growing strongly in the first quarter, amid crises in the financial market, the European Commission said on Thursday. In an interim forecast, which contains updated projections for GDP and inflation for the seven largest EU member states, the eurozone and the EU for 2011, it added that growth is now expected to remain subdued in the second half of the year, coming close to a standstill at year-end. The Commission added that a “soft patch” predicted in its spring forecast is now likely to deepen with growth predictions for the second half of the year being revised down by half a percentage point for the EU and the eurozone, following signs emerging over the summer of a more extensive weakening in global demand and world trade. However, the Commission added that the slowdown would not result in a double-dip recession. It also said GDP growth for 2011 as a whole is set to remain unchanged from the spring forecast of 1.7% in the EU and 1.6% in the eurozone, following a stronger-than-expected performance in the first quarter. “The outlook for the European economy has deteriorated. Recoveries from financial crises are often slow and bumpy,” said EU economic and monetary affairs commissioner Olli Rehn. “The sovereign debt crisis has worsened, and the financial market turmoil is set to dampen the real economy. To get the recovery back on track, it is crucial to safeguard financial stability and put budgets on a path that is sustainable beyond doubt,” he added. Forecast quarterly growth rates for the EU and eurozone were revised down by about a quarter of a percentage point. Growth projections for the EU are now at 0.2% in both the third and fourth quarter, and 0.2% in the third and 0.1% in the fourth quarter for the euro area. “The downward revisions concern all the member states under review, suggesting both a common factor and the high level of interconnection of our economies. Nonetheless, growth is expected to remain uneven across member states,” the Commission said. It added that global output is now projected to grow by around 4% in 2011, a downward revision of about half a percentage point compared with the spring forecast, as financial market conditions deteriorated on the back of “contagion of the sovereign debt concerns in the eurozone and anxiety about the outlook for growth and fiscal sustainability in the ?xml:namespace> In addition, uncertainty about the economic outlook remains high with some of the downside risks considered in the spring forecast now materialising. “In particular, the global economy has slowed down, and hopes that the sovereign debt crisis would gradually dissipate have been disappointed,” the Commission said. The next interim forecast covering all EU member states and looking further ahead will be released
http://www.icis.com/Articles/2011/09/15/9492535/financial-market-crisis-stalls-eu-economic-recovery.html
CC-MAIN-2014-42
refinedweb
491
57.81
- Android Development Tutorial - Android Core Concepts - Installing Android Studio - Your First Android App - Android Project Overview - Android Activity - Android View and ViewGroup - Android Layout - Android Fragment - Android ActionBar - Article TOC Test - Android Toast - Android TextView - Android Buttons - Android Web Apps Using Android WebView Android ActionBar The Android ActionBar component is the top menu bar in Android apps. This screenshot shows an Android ActionBar at the top of the screenshot: Android's ActionBar can contain menu items which become visible when the user clicks the "menu" button on Android phones, or the "menu" button in the ActionBar on tablets. The menu button on tablets is the "hamburger" icon (the three horizontal stripes under each other) in the upper right corner. In this text I will explain how to add menu items to the Android ActionBar. You can add menu items and decide if they should be visible in the ActionBar always, if there is space for them, or only be visible in the menu shown when the user clicks the menu button. Please note, that from Android 5 and forward there is a new Toolbar widget which can do the same things as the ActionBar and more. From Android 5 and forward you should probably use the Toolbar instead of the ActionBar. Adding an ActionBar All activities that use the theme Theme.Holo or a theme derived from Theme.Holo will automatically contain an ActionBar. You can see what theme your app uses in the src/main/res/values/styles.xml. Adding Menu Items to the ActionBar You add menu items to the ActionBar in the menu XML file src/main/res/meny/???.xml file. The menu file is not actually called ???.xml. The menu file is typically called the same as the activity it belongs to, but without the "activity" part. Thus, if the activity the menu belongs to is called MyActivity the menu file will be named my.xml . Here is an example of a menu XML file: <menu xmlns: <item android: <item android: </menu> This menu file contains two item elements. Each item element defines a menu item in the ActionBar. The first item element contains 4 attributes: android:id android:icon android:title android:showAsAction The android:id attribute specifies the id of the menu item. This works like ids anywhere else in your Android app. An android:id value starting with a @+id/ will create a constant in the R.menu constant collection. The android:icon attribute references an icon in the drawable directories. Remember to create one icon for each screen resolution. You can read more about how to do that in Android's official Iconography guide. This guide also contains a link to downloading a set of standard icons you can use, so you don't have to draw every single icon yourself. The android:title attribute value contains the title of the menu item. In the example above the attribute value @string/action_settings references a string defined in the src/main/res/values/strings.xml . The android:showAsAction attribute specifies how the menu item is to be displayed. You can use one of these values: never ifRoom ifRoom|withText collapseActionView always The value never means that the menu item will never visible in the ActionBar as an icon. It will only be visible when the menu button is clicked, in the menu that is popping up. The value ifRoom means that the menu item will be visible in the ActionBar if there is room for it. Different size devices have space for a different number of menu items, so if a given device has room for the menu item in its ActionBar, the menu item will be displayed. The value ifRoom|withText means that the menu item should be displayed with both icon and title if there is room for it. If there is not room for both icon and title, Android will attempt to show just the icon (still, only if there is also room for the icon). I don't yet know exactly what the collapseActionView value means. The explanation in the official Android documentation is a bit weak about its meaning. The value always means that the menu item should always be displayed in the action bar. Inflating the Menu Into the ActionBar In order for the menu items defined in the menu XML file to be displayed, you need to inflate the menu file. You do so inside the onCreateOptionsMenu() method of the activity you want to add the ActionBar to. Here is an example: public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.my, menu); return super.onCreateOptionsMenu(menu); } Notice the call to inflater.inflate(R.menu.my, menu). The R.menu.my parameter is the constant referring to the menu XML file. The menu parameter is the menu into which you want to inflate the menu items. This parameter is passed as parameter from Android to the onCreateOptionsMenu(). Handling ActionBar Item Clicks You can respond to clicks on the ActionBar menu items inside the onOptionsItemSelected() method of the activity hosting the ActionBar. Here is an example: @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_favorite) { // Mark the currently visible content (e.g. article) in the activity as a favorite // - requires app specific code which is omitted here. // Tell Android that the item click has been handled. return true; } return super.onOptionsItemSelected(item); } This example first looks at the item id of the MenuItem passed as parameter to the onOptionsItemSelected() method. This MenuItem parameter represents the menu item that was clicked. If the id of the clicked menu item is equal to R.id.action_favorite (the id defined for this menu item in the menu XML file), then the app will do something related to the favorite menu item. Typically some action will be performed which remembers that whatever is visible in the hosting activity should be marked as a favorite. This code is left out here, because how something is marked as a favorite, and what that even means, is specific to the app doing it. If the item click was handled by the app, then the onOptionsItemSelected() method should return true. Else it should return super.onOPtionsItemSelected(item), giving the superclass of your activity class a chance to handle the menu item click. Showing and Hiding the ActionBar You can hide the ActionBar from anywhere inside the hosting activity, using this code: ActionBar actionBar = getActionBar(); actionBar.hide(); If the ActionBar is hidden you can show it again using this code: ActionBar actionBar = getActionBar(); actionBar.show(); The getActionBar() method is inherited from Activity so it is available anywwhere in your Activity subclass. A Full ActionBar Example Here is the code for a full ActionBar example: public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.my, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } The menu layout XML file looks just like shown earlier in this text. Here is a screenshot of how the ActionBar looks:
http://tutorials.jenkov.com/android/actionbar.html
CC-MAIN-2017-13
refinedweb
1,202
55.44
Hi I am new to performance measurement using counters. I am using 7th generation kabyLake processor and I want to measure the LLC miss per slice for a portion of code very similar to as something mentioned in here. It mention of first setting the MSR for measuring LLC_LOOKUP and then read for each C-Box. So I was wondering if someone could give me some idea as to how MSR would be set and with what value to get he LLC_LOOKUP and then measure for per slice for the given processor. I am trying to use libpfc to achieve the above purpose. However, to me the method of gathering the measurement is not very important. Also I am not sure if any such counter is available for the processor I am using. So that would be helpful to know if I can use the methodology mentioned in the paper. Any help would be greatly appreciated. Thank you. Link Copied There are different ways to get to the counts. The examples are for Intel Skylake, it might be slightly different for Kabylake although the changes between Skylake and Kabylake are minor (for hardware performance monitoring) - Like in the paper: Get number of LLC slices (Bits 0-3) # rdmsr 0x396 Stop all counting in all LLC slices # wrmsr 0xE01 0x0 Configure LLC_LOOKUP event in all 4 LLC slices of Intel Skylake desktop chips (Bit 20 and 22 are user-mode counting and enable bit, 0x34 selects LLC_LOOKUP and 0x8f specifies "0x80: Any request , 0x1: modified state, 0x2: exclusive state, 0x4: shared state, 0x8: invalid state) # wrmsr 0x700 0x508f34 # wrmsr 0x710 0x508f34 # wrmsr 0x720 0x508f34 # wrmsr 0x730 0x508f34 Now we need to start all counters (Bit 29 for unfreeze, 0xf: one enable bit per LLC slice # wrmsr 0xE01 0x2000000f > Run your code Stop all counting # wrmsr 0xE01 0x0 Read all counter registers # rdmsr 0x706 # rdmsr 0x716 # rdmsr 0x726 # rdmsr 0x736 You should set the config registers (0x700, 0x710, 0x720, 0x730) to zero when done - Using perf (/proc/sys/kernel/perf_event_paranoid needs to be 0) perf stat -e uncore_cbox_0/event=0x34,umask=0x8f/, uncore_cbox_1/event=0x34,umask=0x8f/, uncore_cbox_2/event=0x34,umask=0x8f/, uncore_cbox_3/event=0x34,umask=0x8f/ <executable> The paper does not mention which umask value they are using. Although 0x80 specifies 'any request', you can also try 0xf0 for (read, write, snoop and any). Hi Thomas Thank you so much for the comments. I was trying to use the msr tool and I used the rdmsr 0x396 and it gives out an output of 5. My CPU architecture have 4 cores which should have 4 slices. I am not sure if the MSR for getting the number of slices is different for kabylake or actually there are 5 slices which would be really odd. Can you also provide me some information that where can I get the MSR numbers and their details for a particular processor architecture (kabylake in my case). There is another issue as well. I am trying to execute rdmsr and wrmsr in an inline assembly. I am providing my sample code below: static inline uint64_t rdmsr() { uint64_t low, high; asm volatile ( "rdmsr" : "=a"(low), "=d"(high) : "c"(0x10) ); return ((uint64_t)high << 32) | low; } int main(int argc,char *argv[]){ printf("%ld\n",rdmsr()) ; return 0; } So I guessed that could be because of the privilege level issue which is also mentioned in this post. But I tried to run even with a root access and it still gave me segmentation fault. A dmesg gave me the following output. [ 4859.889760] traps: LLC_RE[2224] general protection ip:4005e5 sp:7ffd11f14030 error:0 in LLC_RE[400000+1000] So even though I am running at a lower privilege level still it causes protection error. So I was wondering how this can be solved. Hi, you can find the register addresses in the Intel SDM Volume 4 Chapter 2. When your Kabylake has 5 CPU cores, you probably also have 5 LLC slices. The Skylake mentioned in my post has 4 cores. You can use the rdmsr and wrmsr instructions only in ring 0 (kernel) and not in user-space. You have to use either the msr-tools or run as root and use the msr kernel devices (/dev/cpu/*/msr with pread()/pwrite()). That's why I posted the perf code because you can use it as user. You can also use LIKWID. If you need it in your C program as user, you can also use the perf_event_open system call or the LIKWID library. Hi Thomas Thanks for the answer. But as I mentioned in my second comment I have 4 physical cores and I don't understand how the number of slices output is 5 after inquiring 0x396 representing 5 slices. Or the MSR register value has been changed? I guess that I really don't need it inside my code and so I can use the MSR tool. But I don't understand why there are 5 slices. The current SDM (January 2019) lists in Table 2-40 (Uncore PMU MSRs Supported by 6th Generation, 7th Generation, and 8th Generation Intel® CoreTM Processors, and Future Intel® CoreTM Processors) four MSR_UNC_CBO_* sections but in MSR_UNC_PERF_GLOBAL_CTRL (0xE01) you have bits for LLC slices 0-4 thus 5 slices. So there are some inconsistencies. Same but opposite issue for CannonLake (Table 2-43). There you have 8 MSR_UNC_CBO_* sections but in MSR_UNC_PERF_GLOBAL_CTRL (0xE01) you can select only 5 LLC slices. Hi Thomas I am using the msr kernel (/dev/cpu/*/msr with pread()/pwrite()) to read the MSR. I am using the core part of the rdmsr/wrmsr from MSRTool to read and write the MSR. Thanks again. Hello I have few questions as I am working on the problem. I am going through the events (in chapter 19 of 3 B) and msr (chapter 2 of volume 4). However, I didn't see any documentation as what events are applicable to which msr. I believe all the events are not applicable to all the msr and I was wondering if there is a map that maps certain events to their corresponding msr. Also in the first reply thomas mentioned that the LLC_LOOKUP is the 0x34 event. However, when I was going through the event list of kaby lake (i7-7700k), I couldn't see any such event listed in the event table of kaby lake. But it is mentioned in the uncore event list (table 19-12) of intel 4th generation cpus. So I was wondering this is applicable to my 7th gen intel and if this is applicable then what other event list that would be applicable to my processor generation and how can I know about it. edit: After googling, I came across this document describing all the MSR and their detailed description. It also lists the events in chapter 3. I was wondering if the events are applicable for my 7th generation kaby lake processor as well. The reason I am asking is because I conducted the experiment of LLC miss per slice as suggested in the first reply by thomas. But the results that I have been getting makes me doubtful. Luckily, Intel did a pretty good job with its performance events and you can use most events in any config-counter-pair. Moreover, Intel publishes the event lists as JSON documents, too. See . You can check the mapfile.csv which subfolder you have to select for your architecture. I assume your system has the model id 0x8E or 0x9E which points to the SKL (Skylake) folder. There you find an Uncore file which contains LLC_LOOKUP (0x34). Each event has a field 'Counter' which defines on which counter you can measure the event. For LLC_LOOKUP it is "0,1", so both available config-counter-pairs are suitable. There ist not much difference between Skylake and Kabylake at performance monitoring level, so the document you found should be valid for Kabylake as well.
https://community.intel.com/t5/Software-Tuning-Performance/Getting-the-per-slice-last-level-cache-miss-details/td-p/1183399
CC-MAIN-2021-10
refinedweb
1,327
68.7
Address book sorting functions. More... #include "config.h" #include <stddef.h> #include "mutt/lib.h" #include "address/lib.h" #include "config/lib.h" #include "sort.h" #include "lib.h" #include "alias.h" #include "gui.h" Go to the source code of this file. Address book sorting sort.c. Compare two Aliases by their short names - Implements sort_t. Definition at line 48 of file sort.c. Compare two Aliases by their Addresses - Implements sort_t. Definition at line 69 of file sort.c. Compare two Aliases by their original configuration position - Implements sort_t. Definition at line 117 of file sort.c. Sorting function decision logic. Definition at line 137 of file sort.c. Sort and reindex an AliasViewArray. Definition at line 157 of file sort.c.
https://neomutt.org/code/alias_2sort_8c.html
CC-MAIN-2021-39
refinedweb
124
66.4
django-durationfield¶ Warning Django 1.8 introduced a native DurationField. It is highly recommended to Django’s DurationField instead of this reusable app, as ongoing maintenance of this app is likely to end. Currently there is no automatic migration path from django-durationfield to Django’s DurationField, but pull requests are welcome. A reusable application for a DurationField in Django. This reusable app was conceived as a temporary solution for an old request to add native support for an interval or duration field to Django core, #2443, “Add IntervalField to database models.” This app started from the 2010-01-25 patch by Adys (Jerome Leclanche), DurationField.patch and has evolved considerably as people have used it in their own applications. There have been discussions as to the merit of including into a DurationField in Django core. As of the moment, it appears that most developers favor keeping DurationField separate from Django (both to prevent bloat and to allow rapid evolution of the DurationField’s implementation). That being said, we have developed the DurationField so that if it ever does get merged into Django core, it should be simple for users to switch. This is beta software, please test thoroughly before putting into production and report back any issues. Django Versions¶ django-durationfield supports Django 1.4.21, and Django 1.6.11 through Django 1.10+, with the goal to target the currently support versions of Django releases in the future. So as the Django Project drops support for older versions, django-durationfield will do the same. Django 1.4.2 is a minimum version as it introduced compatibility features for supporting both Python 2 and Python 3. django-durationfield has support for Python 3.4 & 3.5. Please report any bugs or patches in improve version support. Usage¶ In models.py: from durationfield.db.models.fields.duration import DurationField class Time(models.Model): ... duration = DurationField() ... In your forms: from durationfield.forms import DurationField as FDurationField class MyForm(forms.ModelForm): duration = FDurationField() Note that database queries still need to treat the values as integers. If you are using things like aggregates, you will need to explicitly convert them to timedeltas yourself: timedelta(microseconds=list.aggregate(sum=Sum('duration'))['sum']) Example¶ Enter the time into the textbox in the following format: 3 days 2:20:10 or: 3d 2:20:10 This is interpreted as: 3 days 2 hours 20 minutes 10 seconds In your application it will be represented as a python datetime.timedelta: 3 days, 2:20:10 This will be stored into the database as a ‘bigint’. You can be rather more elaborate by using microseconds and weeks (or even months, and years with a configuration setting): 1 year, 2 months, 3 weeks, 4 days, 5:06:07.000008 Years and Months¶ You will need to set a setting in your settings.py to allow your users to enter values for years or months. This causes a loss of precision because the number of days in a month is not exact. This has not been extensively tested. To allow users to enter X years or X months add: ``DURATIONFIELD_ALLOW_YEARS = True`` or: ``DURATIONFIELD_ALLOW_MONTHS = True`` Currently, those fields will be translated into days using either 365 or 30 respectively. To override this setting, add an entry into your settings named DURATIONFIELD_YEARS_TO_DAYS or DURATIONFIELD_MONTHS_TO_DAYS setting a new translation value. Development¶ Please fork and submit issues at Changelog¶ 0.5.5 - Add Django 1.11 support thanks to Anton Linevych. However, recommend future projects use Django’s native DurationField 0.5.4 - Handle cases when database returns a :py:cls:`decimal.Decimal` under Django 1.10. Cast the Decimal to a float (may be a lossy conversion) 0.5.3 - Add support for Django 1.10. 0.5.2 - Remove deprecation warning in Django 1.8 0.5.1 - Correctly parse microseconds. Previously, “0.01” would be incorrectly interpreted to mean 1 microsecond, instead of 10000 microseconds. Thanks to `Troy Grosfield >>`_) for bug report and patch. 0.5.0 0.4.0 - Python 3 support. Drop support for Django < 1.4
https://django-durationfield.readthedocs.io/en/latest/
CC-MAIN-2020-40
refinedweb
680
50.73
of the redirects in are inaccurate, and I'm not sure how they got that way. Has anyone seen these kinds of problems after their SMW 1.0 upgrade? "The following redirects link to non-existent pages: " # Property:true category → Attribute:true category # Property:true title → Attribute:true title # ... but both of the property pages on the left exist as regular pages, neither is a redirect! Perhaps the switch in namespaces in 1.0 left entries in the redirect table? These aren't repaired by a refresh or a re-save. # Dct:Box → Type:Box # Property:Dct:Box → Type:Box # Vector → Type:Vector But Type:Box and Type:Vector exist! I think this second glitch is fixable if you change the redirect page to redirect to another page, and then change it back. Only then MediaWiki figures out that the redirect links to an existing page and removes it from this special page. -- =S Page I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/semediawiki/mailman/semediawiki-user/thread/47D2309E.9000504@earthlink.net/
CC-MAIN-2016-36
refinedweb
198
58.48
Hello. I have an issue regarding the JS exit method on XSA. Here are the detailed steps whichi have done. First of all, I have a CDS view with a simple entity: entity BusinessPartner { key BusinessPartnerID: Integer; isCustomer: hana.TINYINT; Name: String(100); isSupplier: hana.TINYINT; } Then, a simple odata service: service namespace "SUPPLY_CHAIN_TRACKING"{ "poc_scm.db.data::SupplyChainTracking.BusinessPartner" as "BusinessPartnerSet" } At this moment, everything is perfect. In the next step, I want to use a JS function exit on entity creation, so, I created a businessPartnerCreateMethod.xsjslib file, and on that file I have a createMethod with some insert logic. The next step is to change the odata service declaration: service namespace "SUPPLY_CHAIN_TRACKING"{ "poc_scm.db.data::SupplyChainTracking.BusinessPartner" as "BusinessPartnerSet" create using"xsjs:businessPartnerCreateMethod.xsjslib::createMethod"; } When I do a simple POST request, everything is working. The create method is called, everything is ok. The problem comes, when I do the Batch request. On Batch request, the error message says: {"error":{"code":500,"message":{"lang":"en-US","value":"context.functionExecutor is not a function"}}} (It works for a simple POST request!) Any help will be appreciated. Thank you. P.S If someone need more information, I can provide it. Hi Alex, did you find a solution by any chance? Hi Neha. Unfortunately not. I managed to run it with a single request and the workaround was to turn the batch request mode off in the SAPUI5 app. But I don't know the way to fix it while using the batch mode. oModel.setUseBatch(false); oModel.submitChanges(); Hi Alexandru, the issue should be solved with SAP note 2421178 Best regards, Christian You already have an active moderator alert for this content. Add comment
https://answers.sap.com/questions/172495/java-script-exit-method-on-xsa-using-batch-request.html
CC-MAIN-2019-09
refinedweb
284
50.73
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. AccessError: No value found function field I am getting the error: AccessError: ('AccessError', "No value found for account.invoice(u'66',).state") I have this code here: def _get_invoice_status(self, cr, uid, ids, invoice_status, arg, context=None): inv_status = {} inv_obj = self.pool.get('account.invoice') for record in self.browse(cr, uid, ids, context=context) : _inv = record.invoice and inv_obj.browse(cr, uid, record.invoice, context=context) or False inv_status[record.id] = _inv and _inv.state or '' <-- error is from this line. How can I fix it? return inv_status _name = 'intrac.batches.registrations' _columns = { 'name': fields.char('Registration Number', readonly=True), 'invoice': fields.integer('Invoice'), 'invoice_status' : fields.function(_get_invoice_status, type='char', store=False, string='Invoice Status'), } Probably invoice with ID = 66 not exists. My suggestion: before inv_obj.browse you call inv_obj.search. If not empty search result call browse. for record in self.browse(cr, uid, ids, context=context) : inv_status[record.id] = '' inv_ids = inv_obj.search(cr, uid, [('id', '=', record.invoice)], context=context) if inv_ids: _inv = inv_obj.browse(cr, uid, inv_ids, context=context) inv_status[record.id] = _inv.state invoice with id = 66 does exist zbik. before inv_obj.browse you call inv_obj.search. If not empty search result call browse I am not sure how to do this exactly Hello Abdullah, In particular line define below giving you error : inv_status[record.id] = _inv and _inv.state or '' This type of error comes when the particular state field in line you are browsing it's also functional field and It state field should be store=False. So, that's system can't find that particular field in database or their value and throwing error. Make Sure that particular "state" field define your system it's also displaying value in database Check in database. Thanks, Hi Hiren, I check the database and the record is there. Hi Abdullah, Make sure you have to check state field in 'account.invoice' object. Because you are taking value of 'account.invoice' object. Define your line in below. _inv = record.invoice and inv_obj.browse(cr, uid, record.invoice, context=context) or False Here inv_obj is 'account.invoice' object. Otherwise, If you want to solve out this issue immediately Checked if condition define below code. _inv = record.invoice and inv_obj.browse(cr, uid, record.invoice, context=context) or False if _inv: inv_status[record.id] = _inv and _inv.state or '' else: inv_status[record.id] = False Otherwise specify in functional field which value you want to browse because I can't understood why you are browsing account.invoice object and checking with current current object. Thanks, @Hiren store=False has nothing to do with accessing the value of state field. The _inv here is a browse_object, an ORM object that will have all the fields values, regardless of stored or not. It will just calculate the value if functional field if not stored. My mean is to check status field of 'account.invoice' object not your 'invoice_status' field. _inv = record.invoice and inv_obj.browse(cr, uid, record.invoice, context=context) or False Because in particular line you are taking value of 'account.invoice' object And Sorry to say you but you are browsing value in wrong way Let me brief explain: You are taking value like this : _inv = record.invoice and inv_obj.browse(cr, uid, record.invoice, context=context) or False Means you are browsing 'account.invoice' with id 'record.invoice'. 'record.invoice' is the value of your current object. If you are passing nothing then it will take False value of your "_inv" variable. If in your current object you are passing 2 for invoice field then it will browse account.invoice object which have ID contain 2. Then you have to simply check in database that what ever value you are passing for your current object define field : 'invoice': fields.integer('Invoice'), This field value you have to consider as a id as per your code. Suppose you are passing 5 in this particular field. Then you have to check in 5 number ID in account.invoice object and this particular state will be return. 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 @Abdullah, can you share the log (server or javascript console) that indicates that the line causing the problem is indeed that line? I've commented in your other question that u'..' is a unicode. Also, I can't find the exact error message in OpenERP v7 (your code is v7/old API style), are you using other version?
https://www.odoo.com/forum/help-1/question/accesserror-no-value-found-function-field-74121
CC-MAIN-2017-13
refinedweb
789
62.24
Hi, I need to be able to quickly generate reasonably random numbers i.e. not a series of numbers produced at one time but successive new random integers between 0 and 8 inclusive. I think my problem arises from the fact that the time period between successive generations is so short that seeding is incapable of producing randomness. I have very limited experience with random number generation. The code I have been trying follows: where the integer left after the above condition is used. The above code was from:where the integer left after the above condition is used. The above code was from:Code: #include "stdlib.h" int randnum; while (8 > (randnum = rand() / (RAND_MAX/8))) { ; } I'm not eternally attached to the above code so if anyone has a simple way to generate "reasonably random" integers between 0 and 8 inclusive with very little time between generations it would be highly appreciated. Thanks in advance, N.
https://cboard.cprogramming.com/c-programming/106942-rapid-random-number-generation-problem-printable-thread.html
CC-MAIN-2017-43
refinedweb
157
54.42
Fabulous Adventures In Coding Eric Lippert is a principal developer on the C# compiler team. Learn more about Eric. I was discussing the difference between executing in local and global scopes the other day. A reader points out something that I forgot to mention – there are two sneaky ways to manipulate the global namespace from an “eval” in Jscript. First, the Function constructor constructs a named function in the global scope. This had slipped my mind when I was writing the entry. The second trick was very much on my mind but I did not mention as it would be yet another digression. That is the fact that assigning a value to an undeclared variable creates a new variable in global scope. This was on my mind because a couple weeks ago my buddy (and open source zealot, I mean enthusiast) CJ was debugging an irksome incompatibility between Gecko and IE. It turned out to hinge on the fact that in IE, fetching the value of an undefined variable is illegal, but setting it is legal. According to CJ, in Gecko both are legal. (I wouldn’t know, never having actually used any browser other than IE since IE3 was in development.) Now, if you look at the ECMAScript Revision 3 specification (aka E3) in some depth it becomes clear that IE and Gecko are both in compliance with the spec, and yet incompatible with each other. "Howzat?" I hear you ask. The logic is a little tortuous! Creating a new global variable when setting an undeclared variable must be legal according to E3 section 10.1.4, line 5, which states that an identifier undeclared in all scopes on the scope chain results in a "null reference", and section 8.7.2, line 6 which states that an assignment to a null reference creates a new variable in the global scope. IE does this, and I assume that Gecko does as well. But setting the value of an undeclared variable must throw an error according to E3 section 8.7.1, line 3, which states that fetching the value of a null reference creates a ReferenceError exception. IE does this. If Gecko creates a variable in some scope rather than throwing a ReferenceError exception then clearly they have produced a situation in which a program running in Gecko has different semantics than when running in the browser used by the other 90% of the world. Such situations are, as my buddy CJ discovered, very painful for developers -- mitigating this pain is why my colleagues and I went to the massive trouble and expense of defining the specification in the first place! However, if that is the case then Gecko is not _actually_ in violation of the specification thanks to E3 section 16, which states: "An implementation may provide additional types, values, objects, properties, and functions beyond those described in this specification. This may cause constructs (such as looking up a variable in the global scope) to have implementation-defined behaviour instead of throwing an error (such as ReferenceError)." [Emphasis added] The E3 authors explicitly added the parenthetical clauses to make Gecko-like behaviour legal, though discouraged. However, the clause is necessary -- without this clause it becomes very difficult to define certain browser-object-model/script-engine interactions in a manner which does not (a) make both IE and Navigator technically noncompliant with the spec, (b) drag lots of extra-language browser semantics into the language specification and (c) make it difficult to extend the language in the future. We earnestly wished to avoid all these situations, so the rule became "any error situation may legally have non-error semantics." This is in marked contrast to, say, the ANSI C specification which rigidly defines what error messages a compliant implementation must produce under various circumstances.
http://blogs.msdn.com/b/ericlippert/archive/2003/09/22/53072.aspx
CC-MAIN-2014-35
refinedweb
635
50.46
Farid Zaripov wrote: [...] >>>>". But it doesn't point to the right container. Unless I'm still missing something this needs to pass: #include <assert.h> #include <deque> int main () { std::deque<int> x, y; std::deque<int>::iterator i = x.begin (), j = x.end (); std::deque<int>::iterator k = y.begin (), l = y.end (); std::swap (x, y); assert (i == y.begin () && j == y.end ()); assert (k == y.begin () && l == y.end ()); } > > If we decide to set deque<>._C_end._C_node = 0 for end iterator of > empty > deque It would be a big change (we should change the all places where > _C_end._C_node member dereferenced). Couldn't we just repoint _C_end._C_node in swap()? I thought that's what we were doing anyway so I guess I still don't fully understand the problem. Martin
http://mail-archives.apache.org/mod_mbox/stdcxx-dev/200707.mbox/%3C469286E9.1090208@roguewave.com%3E
CC-MAIN-2015-11
refinedweb
134
73.54
At this point, no pun intended, you might like to try a simple example, just to make sure it all works. There are also some practical matters we have to deal with about how you create a new class within the NetBeans IDE. First start a new Java project in the usual way only this time tick the "Create Main Class" selection box. Now that we are starting to learn about class and object we might was well start making use of them. The only new feature is that now you will find a default class created for you with the same name as your project. For example, if you called the project PointOne then a class called PointOne will be created for you complete with a main method. As you might guess the main method is where your code starts when the program is run - so this is the place to put your Java code. Before we start adding code to the main method however we need to create the class. It is usual in Java to store each class you create in a separate file of the same name. The easiest way of doing this using NetBeans is to use the New command. Right click on the folder that the main class is stored in and select New and then Java Class: Just give the class the name Point and you will see that a separate file has been created called Point.java. This one class to one file of the same name is a peculiarity of Java and if you have worked with another object oriented language you might find it difficult to get used to at first. To enter the simple code for the Point class all you have to do is double click on the file and when if opens in the editor enter: public class Point { public int x; public int y;} You will discover that the public class Point line has already been entered for you. Now move back to the main class and enter: public static void main(String[] args) { Point Current; Current = new Point(); Current.x = 10; Current.y = 20; System.out.println(Current.x); System.out.println(Current.y); } This simply creates an instance of the class “Point”, stores something in each of its data members and then prints them out to the Output window just to show that x and y really do exist and work as variables. If you run the program you should see 10 and 20 in the Output window. Instead of a two-step process - create a variable and then store an object in it, you can use a one-step object creation process that is a common way of writing things in Java and other object oriented languags. The two lines Point Current; Current = new Point(); can be combined into Point Current = new Point(); The only confusing part is the way the identifier “Point” occurs at both ends of the instruction. The first point gives the type of the variable Current and the second is the type of object you are creating to store within Current. A class defines a program in miniature. It can have variables and any number of functions that you care to define. However there is one important idea that is new. When you declare a variable or a function then you have a choice. You can declare it to be public, in which case it is accessible from outside of the class or you can declare it to be private in which case it isn't. If you don't use public or private then the default is public.There are other options but for the moment it is enough to consider these two cases. Anything that you declare as public is a property of the class or rather of the object it creates. In the previous example when we wrote: public int x; public int y; public int x; Then both x and y are public properties of the class and can be accessed from outside of the class using a fully qualified name e.g. Current.x = 10; If x had been declared as private int x; then any attempt to access it as Current.x would have failed with an error message. The private variable can be used by any of the functions within the class but it isn't accessible from outside of the class. The basic idea here is that a class is a bag of Java code that can be used by other Java programs. However you don't necessarily want the outside world to see the internal workings of this bag of code and so you use private variables and functions. The variables and functions that you do choose to make public define the characteristics of the objects the class creates to the outside world - it defines the objects interface with other objects. You also need to remember that any variables defined with a function are local to that function and have nothing to do with any variables of the same name anywhere else in the program. If this all seems complicated it soon settles down to being second nature.
http://www.i-programmer.info/ebooks/modern-java/4569-java-working-with-class.html?start=1
CC-MAIN-2016-26
refinedweb
868
74.22
More and more employers have to send their employees to locations that require them to spend nights away from home. To compensate their employees, the employer will generally provide for the accommodation, and may provide for food and incidentals, however where they don’t, it is important to structure the employees pay packet so they can maximise the full use of the tax system. Travel allowance can be effective way to compensate employees but, if not done correctly, can have significant adverse effect for the employee which can result in unhappiness which can affect an employer’s business. ATO focus The Australian Taxation Office (ATO) (in its 2013-14 Compliance Plan) advised that it would “look closely” at high work-related travel expense claims. The ATO has followed through with that plan and has been focusing on allowances paid, not only in the 2013/2014 tax year but earlier years. Recently, there have been a number of adverse outcomes (which have been for significant amounts) as a result of ATO audits. This risk highlights the importance of ensuring that allowances paid to employees are structured correctly and meet the requirements to limit this risk. Below, we have identified a number of areas of confusion for employers and employees. Sources of confusions for Employers When dealing with travel allowances, it is important that the Employer is able to answer the following: - Are travel allowances required to be disclosed on an employee’s PAYG summary? - Does PAYGW apply to travel allowances? - Does Super apply to travel allowances? - Does Payroll tax apply to allowances? Getting it wrong with any of these questions can have serious personal consequences for employers. Sources of confusions for Employees When receiving a travel allowance, employees want to know: - Are deductions allowed? - Will PAYGW be withheld from my travel allowance? Are travel allowances required to be disclosed on an employee’s PAYG summary? In limited circumstances, the allowance does not have be shown as assessable income in the employee’s tax return (and therefore, not disclosed on the employee’s payment summary) and therefore, PAYGW is not required to be paid. Where the “allowance” paid is not in fact an “allowance” but, say, salary and wages, PAYG, may be required to be withheld and remitted to the ATO. It is important for employers to get this right as getting it wrong may result in personal liability attaching to the employer. Does PAYG withholding apply to travel allowances? A travel allowance is assessable income to an employee and is generally included as income in the employee’s tax return. Depending on whether the allowance is bona fide or not, will depend on whether PAYG is withheld. Does Superannuation apply? Super guarantee contributions are payable on an employee's ordinary time earnings. Most allowances are included in ordinary time earnings. However, most expense allowances and reimbursements are not 'salary or wages' and therefore are not ordinary time earnings. Does Payroll tax apply to allowances? Most allowances paid are taxable wages and therefore must be included in the employer’s calculation of payroll tax liability. However, certain allowances (including accommodation allowances) may be exempt and may be excluded from the purposes of payroll tax. Are deductions allowed? Deductions for expenses are allowed. In certain cases, the employee will not be required to provide proof of expenditure in order to claim the deduction (i.e. where the allowance is a bona fide travel allowance and where the amounts do not exceed what the ATO deems reasonable). However, the employee will should still have incurred the expenses. There can be significant costs to the employee, where the allowance is not found to be a bona fide travel allowance and the employee has not kept proof of expenditure. Will PAYGW be withheld from my travel allowance? As mentioned above, a travel allowance is assessable income to an employee and is generally included as income in the employee’s tax return. If the allowance is a bona fide travel allowance, no PAYGW will apply. Structuring a travel allowance is critically important to maximize the benefits available under the current tax system. With the ATO’s focus on allowances, it is equally important for employees to understand how they work.
https://www.lexology.com/library/detail.aspx?g=6732201d-aa1a-48bc-a671-a192cf57b5cd
CC-MAIN-2019-04
refinedweb
703
54.02
- Type: Bug - Status: Resolved - Priority: Major - Resolution: Fixed - Affects Version/s: 3.0.0 - - Component/s: build / infrastructure - Labels:None Most of the tests under org.apache.openjpa.persistence.jdbc.maps behave random when they test against a real database. Those tests capture the JQPL path navigation for Maps (Covered in the spec in 4.4.4.1). public class @Entity Division { private Map<Division, VicePresident> orga; } Such structures can be navitated via KEY(), VALUE(), and ENTRY(). Our tests did create 2 Divisions with 2 orga entries. And using query.getResultList().get(0) to verify the results. And this was exactly the problem. using get(0) leads to random behaviour with real databases. On the default Derby database it didn't make any difference as the result from the index query was always in the order in which the data got written to disk. But this is not guaranteed for performance tuned databases like PostgreSQL, MariaDB and MySQL. In those cases we got random errors.
https://issues.apache.org/jira/browse/OPENJPA-2764
CC-MAIN-2019-51
refinedweb
165
51.65
Earlier today, we shipped Visual Studio 2005 and .NET Framework 2. Later in the day, the final bits will be up on MSDN for our MSDN subscribers around the world to get access to the product.! You just made my day. 🙂 Soma, congrats to you and all the staff on this release. As a developer I've never been more excited in my career than I am about this release and this product. Great job! Shoddy Awesome! The wait is over. Great job! Congratulations! Can't wait to see it in MSDN downloads! This is a great news! I hope that UPS will work as good as usually is doing in order we can get Visual Studio 2005 asap. Congratulations from Brazil. Great job. It is a great product. Many, many times better than VS 2003. Congratulations to you all guys!!! I too have been excited about this release! Thanks! Congratulations to all the people involved on this huge project! 🙂 Congratulation to every member in the product teams. This is such a major release. Finally the wait is over 🙂 Someone pass the cigars around 😉 <ComicBookstoreGuy>Best. News. Ever.</ComicBookstoreGuy> Congratulations to everyone in the Developer Division. This must be a great day for you guys! I'm off to MSDN to try and download (servers are getting hammered :P) Congrats to all. I hope the .NET, VS, SQL and BizTalk teams get a nice reward and some time to relax before the launch events. Congratulations! Thanks for making available to download at MSDN. Can't wait to see it in MSDN downloads! Awesome, downloading now. Great news for the Developer community. I'm eager to see how the whole community going to embrace and start deploying innovative solutions. Also curious to see how it will be priced and how MSDN will accomodate small ISVs into the subscriptions model Somasegar Prabhuji, This really saves the day! See you in Belgium, November 10th! Namaste! Thanks for the good news Soma! Jason Thanks Soma!! that's really a big news and its going to help us a lot. Meanwhile, are you aware of SQL Server 2005 release ?? This is great news! Congratulations on the release, I am really looking forward to downloading it and giving a go...but it looks like the download servers are a little hammered right now. Gee, I wonder why? 😉 Thank's for all the great work you guy's have done on this release.. I'm really anxious to get this great stuff in my fingers 😛 Also SQL Server 2005 appears to be shipped today! Best day of my life so far (only 20 years old :P) Great news! I appreciate all the effort you guys put into this and like to thank you verry much. Congratulations! Looking forward to start using it! never could repeat the moment - enjoy! Congratulation, Soma (and everyone on the team)! My customers will be glad to hear that we can finally stop using a beta version for doing their product! 😉 To me, VS 2005 and .NET 2.0 have been the single most important productivity boost factors of the last years. Cheers Rick - "Awesome! The wait is over." ...until you attempt to download it....then the wait is back on... Congrats to you and everyone on the teams, I'm looking forward to trying it out - once it is downloaded from MSDN. Now I'm looking towards Vista, WPF, WWF and ORCA, this is an exciting time! Klaus Enevoldsen, Denmark Congratulations to the compelete Dev Division on getting such a BIG release out of the door on (Before) time! Congrats! Looking forward to the launch event in London Get some sleep, and think about a sabbatical, or a 1 month vacation. The last MSDN drop was pretty tight, what was fixed? Congrats! Congratulations! - You've made my night!...UK bandwidth is about to be heavily affected by us MSDN subscribers Congratulation from Slovakia... I am just waiting for SQL server and Express Editions to download and give it fast try. Any info/link on these editions? It totally made my day when I went out to MSDN and saw that. Then I came here to confirm it was true. ROCKZ!!! This is a big deal and an exciting time. Great job guys and congratulations. -fs defining moment!! Congratulations from Iceland 🙂 congrats from ghana Great job done! Soma, What can I say!! You have conquered the hearts of scores of developers like myself who breathe and dream Visual Studio. Net. I am one of the early adopters of VS.Net and I find it totally irresistible. Obi Oberoi, Toronto (Canada) I can't comment until being able to use it. I hope those things that I expected to be in there are all in there and really work and be useful. Otherwise, I wouldn't be as happy. Let's wait and see if anything sucks. Thanks. Whohoo!! Excellent They have done it again ! Since Visual C++ 1.5, 2.x, 4.x, 5 & 6 et VS NET series, I am still with you !!!!! All thoses products makes working in a good way. Using them 10 hours a day is comfortable. << Chapeau bas >>, messieurs ! Great work folks, best .NET release thus far! Now there's the wait for Orcas:-) Just in time for my B-Day on the 28th. Thanks guys!! Now it gets really exciting!!! Thanks! Congratulations from the Czech republic! Started working with the DOS versions of the MSC series. Still remember the german launch event for the first Windows version (VC1.0) very well, where every attendee a 5kg package with printed documentation! Trust that I will be very pleased with VS05. Did send it by ship? Put it on an airplaine! Huge congratulations, guys! You've done a great job! Will VS2005 be available for download through MSDN Adademic Alliance soon? Thanks Congrats Man Did You released Visual Source Safe 2005 too? Great!I have waiting for it long long ago!!!! The VS Team is Great!!!Thank you! Hiya, Will it work with the WinFX September CTP release? Congratulations! Are you going to the San Francisco launch? If so--see you there! Congratulations on the release of the of the biggest and (I hope) the best VS IDE from the Microsoft stable. Many thanks from France 🙂 Big news for us!!! We've been working with all the betas, since 2004, and we just love this new version 2.0. And VStudio 2005 is also great Can't wait working with it!!! Fantastic guys! Keep up the good job. Many congrats from Holland Best set of development tools ever built by Microsoft. Thanks for all your effort! Yes, we did release Visual Source Safe 2005 as well yesterday. - somasegar We are excited about the new release after trying the Beta2 release. Excellent job and really happy to have a company like Microsoft who makes dreams come true from Developers. Congrats again from Australia and God bless all of you. Hats off to you. I have never seen any Microsoft release generate as much interest in Pakistan (and the world) as this one. Truly phenomenal! Congratulations! I downloaded from MSDN on Thursday and am quite impressed. Very big and good work Congratulations Namaste from India. This is great news. I'm looking forward to install the product now itself. I can't wait more time. Don't try to install it on Vista, it doesn't work, the worthless thing thinks you need SP2! Congratulazioni from Italy! This release is really a breakthrough in productivity. All you msdn blogger guys have create a really great and exciting community! Any clues where it is? Because I can't find it for download anywhere on the site, and yes I am an MSDN subscriber. What a frustrating experience. Shouldn't be that easy to find anyway, since Microsoft support couldn't do it either... I notice that if we attend a launch event in the US we get free versions of VS and SQL but in the UK we don't, just some sandwiches ... do you know why this is not a universal offer ? The tab on the MSDN web site says you will get complimentary software but when you follow through to UK ... its not on offer any more To RJL: We’ve reconfirmed that VS2005 RTM works on the latest Vista October CTP (bld# 5231) and is also working on the latest internal builds as well. Previous Vista releases (Beta1 and PDC) still require VS2005 Beta2. We cannot find any issues regarding the “SP2” error you noted; if you could supply more information on this error I will make sure the right folks investigate it. Thanks! Chris Dias chris.dias@microsoft.com Great!!! Just a pitty there's no product launch in the Southern Parts of the world!? Thanks for the hard work to all the creators of VS 2005. looking forward. From ZA Congratulations!. Looking forward to the launch event in Atlanta. Thanks Hey Soma, Great job on the visual studio. But i would just like to say publicly THANK YOU. For all you have done for me by helping me with my school assignements. You are a really great man and I think most highly of you. Keep it up all the good work. Dean 🙂 Congratulations! Visual Studio 2005 is a real quantum leap. I hope "Orcas" will be even more amazing, can't wait LINQ and other cool technologies. Great job! Awesome! Cant wait to get my hands dirty with it... 🙂 That's great!! Looking forward for the launch on 7th November. Congratulations! I have one question: Could you summarize the difference between RC and final release? Thanks. Great New Soma!!!! Super stuff 🙂 Just downloaded it from MSDN - and gee am I looking forward to getting it up and running on my machine!! Congratulations to you and your team! Congratulations to all of you !!! You can be proud of you Do you guys filter the comments, since every one applauses ??? for us .NET is a pain, we will continue VB6 until you provide migration tools. Joe Hi Joe, There is NO filtering of the comments on my blog. Every comment that gets posted is for all to read. - somasegar We've done substantial work in this version to address some of the concerns that were raised by Visual Basic 6.0 developers. One site that you could check out is VBRun: The Visual Basic 6.0 resource center. This contains some of our best Visual Basic 6.0 content, information on using VB6 and VB .NET together, offers from our partners, and information for developers looking to move to Visual Basic 2005. We have two books from MS Learning that have been posted online as a part of this site. The Patterns and Practices group has put together some guidance for developers moving their code and skills that you can find at. One feature in the product which will be particularly interesting to Visual Basic 6 developers is the addition of RegFree COM. This allows you to deploy a VB6 control without having to register it on the local machine. You can now reuse existing code without any risk of impacting existing applications and could even deploy different version of the same COM component side by side with different applications. Many of our developers have told us that the soul of VB is back with Visual Basic 2005. The productivity that was the hallmark of Visual Basic is enhanced with features like the My namespace, AutoCorrect, scalable drag-and-drop data binding and the return of Edit and Continue. If you have additional ideas on things we could be doing, my email address is posted on VBRun and I'd invite you to mail me. Soma...congrats to you and all the team members involved in the release of the product. good job done folks....keep it up. hope to see the product in our development environment here and explore the same. One of the requirements that i expect from .NET Framework 2.0 is offering the FTP class for uploading and downloading the files from/to the remote systems. i read on internet somewhere that the FTP class is available in Framework 2.0 version. hope to see the FTP class available with this product. Congratulations !!! Namaste ! 🙂 Congratulations !!! where to download? Sorry to rain on your parade guys but... Having been amazed at how fabulous VS 2002 and 2003 were, I expressed major concerns about this product while using the CTPs and the RC. My concerns were well founded. It is the most painful Microsoft product since Vizact. We've installed it 3 machines and every around hour the VB compiler fails with a send error report (on different projects!) We then have to sit through 6 or 7 submit reports before it finally drops out of memory with a feeble apology. Even the CTP didn't do this! You have implemented some amazing things guys, but when the basics no longer work it kinda makes the whole excersize pretty pointless. Hi Nag, Here's a sample app that ships with V2.0 that demonstrates how to use the FTP class: ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_fxsamples/html/7b16941d-2a77-4fb6-9ba7-40cd6d9897b7.htm You use FtpWebRequest and FtpWebResponse to do the work. - somasegar Congratulations from India,BLR.. Even I too excited about this Mega Product release! Congratulations to everyone in this team, Who are all designed and introduced lot many things to finalize the product. Really really ...it must be a great day for you all guru's. Congrats once again ! Looking for the launch event in India especially in BLR. gudos to VS Team and Somasegar Hi guys, Now that we have the final version of VS.NET 2005, my question is can we have VS.NET 2005 installed and safely working along-side VS.NET 2003 that I already have (which is my current production environment)? Has anybody had a rough experience in doing this? I want to develop some projects in VS.NET 2005 and keep developing some projects in VS.NET 2003. To do this i will need to install both the environments (and the relevant Framework version as well) together in the same production environment. Is it safe to do this - or should i use the Virutal PC to install VS.NET 2005? Note: I have the final VS.NET 2005 version (production reelase, not the Betas or RCs), since I am an Universal MSDN subscriber. Thanks. thx friend what can i say!!! now you are bilding my dream ! thanks I cannot find Visual Express RTM to download. All I get is beta 2 version. How to get the new Express Edition? nigh: The Express Editions can be downloaded from. Thanks, Luke Hoban There does not seem to be any place to get CLRProfiler. CLRProfiler Beta 2 does not run any of the new applications created by the released version. Great job ! I am looking forward to the launch of Visual Studio 2005 in India. As a technical writer I want to know the major differences in VS .Net 2003 and VS .Net 2005. Congrats once again Hi Vibhuti, We have a whole bunch of information including a feature guide out on MSDN. Here is the link to that - - somasegar Thanks a lot and wait for a great product is over. Well that's good, because 2003 sux. No need to give up 6.0 until I've put 2005 through the wringer though. Hi Somasegar, I can't wait to work on vs.net 2005 with sql 2005. Just wondering, do you have any free msdn events related to 2005 version as a cd or slides, where we can download.. Core information related to vs.net 2005. I read so many articles related to vs.net 2005.. But it would be much helpful, if i can get as a download link. Thanks, Vasudha Hi Vasudha, You can download the Express editions of VS 2005 from. You can also get trial editions of VS 2005 from. Also, depending on where you reside, you may want to attend the local launch of VS 2005/SQL Server 2005 and Biztalk Server 2006. - somasegar Thanx to Visual Studio Team.. I am Qamar. I am MCP and want to learn new feature of Visual Studio 2005 and .NET Framework 2.0 / SQL Server 2005 Quickly can you tell me the right way [qamar.gilani@gmail.com] Hi Somasegar, I'm looking forward to attend NOV 22nd session on Vs.net 2005 in NY. Also I have the trial versions installed. Do you recommend any good books on Vs.net2005 and SqlServer2005 ? Thanks, Vasudha Sir, Congratulationsssssssss for the whole team. I already worked on Visual Studio.net 2003. I would like to work on Visual Studio2005 and SQL-Server 2005. Presently, I would like to know the difference between Visual Studio 2005 and Visual Studio.net 2003. Since several people have asked for this again, I will repeat this. You can go upto and get a whole bunch of information about Visual Studio 2005. Specifically, we have a feature guide for VS 2005 - that will tell you what's new in this version of the product. - somasegar Hi Somasegar, I have VS.NET 2003 installed for my production use. I have VS.NET 2005 but have not installed it yet in my production machine, but would like to start developing future projects in 2005 VS.NET. Can you confirm that having VS.NET 2003 and VS.NET 2005 (final release version) together in one production machine is safe. Thanks. Hi .NETUser, Having VS.NET 2003 and VS 2005 in the same machine is absolutely supported. Having these two reside side-by-side is one of the key configurations that we support. - somasegar Congratulations 🙂 Hope to be there at India Launch on 9th December PingBack from Visual Studio 2005 Professional along with SQL Server 2005 RTM’ed last week – right on time… actually... Visual Studio 2005 et le .NET Framework 2.0 sont finalisés. C'est ce qu'a annoncé Soma Somasegar sur... Soma said it. It must be true. This is great news. I am very excited about this release. I wonder if... Visual Studio 2005 Professional along with SQL Server 2005 RTM’ed last week – right on time… actually... Visual Studio 2005 Professional along with SQL Server 2005 RTM’ed last week – right on time… actually... If you haven't heard the news, Microsoft Visual Studio 2005 (meaning Microsoft Visual Basic 2005) and PingBack from free learn english online game free myspace music videos codes in spanish We are having a problem with the date picker control. It is hiding behind a drop down list while rendering. Can you please provide us a solution for this or a workaround for resolving this problem. We are having a problem with the date picker control. It is hiding behind a drop down list while rendering. Can you please provide us a solution for this or a workaround for resolving this problem. Padmakar - I am sorry you are having an issue... Is it with an ASP.NET web project or a Windows Forms project? Can you tell me a little more about what is happening? You can drop me an email at: Hi, i m using crystal report .net 2005 in my windows application,in which there is a main report in which there are 4 subreport.at run time when i click on main report , subreport open in new tab, how can i restrict so that subreport will not open in new tab. can anybody help me? They released it today on MSDN earlier than the original 11/7 launch date. Here is some more information PingBack from PingBack from PingBack from PingBack from PingBack from plise give the carrect ans. this answar is no corract for my question thank tanksssssssssssssssssssssssssssss we have a project developed in .net framework 2.0.40607(BETA). and after that VS2005 has launched with framework 2.0.53727. Now, many classes have been obesolate of beta framework. How can i use old framework to do some changes in my project becausse VS 2005 is not migrating automatically to new framework? plz reply..urgent Sachindevtripathi@gmail.com it's an opportunity to thank the community and early adopter customers for their incredible help and invaluable contributions in helping us ship the right product. regards, <a href="">find a freelancer</a> must be great to be part of the team, congrats on that. Thank you very much gosto
https://blogs.msdn.microsoft.com/somasegar/2005/10/27/visual-studio-2005-and-net-framework-2-0-shipped/
CC-MAIN-2017-30
refinedweb
3,432
77.13
Version: draft 0.0. The NetBeans PHP support is popular and obtains many users. It's the support that attracts many new people that are switching from other IDEs. The features in the release NetBeans 6.9.Next will be mainly targeted to improve productivity of the IDE. Support checking coding standards. Obviously editor cannot support all extensions for the PHP language, all frameworks Implements some refactoring that are missing PHP 5.3 brought many features that were not fully supported in 6.8 and still are not supported in 6.9. Phar,namespace view (analogy of package view in java) should appear in PHP project plan, but also additional editor improvemnts
http://wiki.netbeans.org/wiki/index.php?title=PHPNB70&diff=42039&oldid=39371
CC-MAIN-2020-10
refinedweb
112
60.92
in reply to Re^5: Why Does Test::Deep Kill Test::Class in thread Why Does Test::Deep Kill Test::Class You don't if the module does its exporting right, and most do. I realize you're talking about having relative spaces in the code though. To me that would add arbitrary levels of (human) ambiguity for the hacker trying to read it. I think this could be solved in Perl too with some export/namespace alias magick but I wouldn't like or use the feature. There is no ambiguity in how it's done in python and after 4 years of python, I've never had a problem or even heard a complaint about that. Howver, squishing it into Perl would be hard because you'd have to make it live side-by-side with the currently absolute package names and without introducing new syntax, you would have ambiguity and confusion. Python doesn't provide any syntax for addressing packages with using an absolute name. You can do it but by digging around in sys.modules but it's not part of the language as such. All that said, I have rarely missed Perl's absolute package scheme when writing python and I have often missed python's relative package scheme when writing Perl. Used as intended The most useful key on my keyboard Used only on CAPS LOCK DAY Never used (intentionally) Remapped Pried off I don't use a keyboard Results (437 votes), past polls
http://www.perlmonks.org/?node_id=752126
CC-MAIN-2015-11
refinedweb
250
67.18
. The size of wchar_t is shown as 1 byte in the table whereas it is shown as 2 byte in the example. What is the use of wchar_t if its size is 1 byte? The table indicates the minimum size for each type. wchar_t can be 1, 2, or 4 bytes. On my machine/compiler (Windows/Visual Studio), it’s 2 bytes. If wchar_t is 1 byte, it can still be used to hold utf-8 text. That said, wchar_t is a mess, and should generally be avoided altogether. I mention it in the lessons simply because it’s part of the standard, and so I can tell you that’s its a mess and that you should avoid it. 🙂 hi Alex I can’t understand this program how can the result of program took 6 how can the program be solved? can i use ‘long’ instead of ‘int’ #include <iostream.h> int main() { using namespace std; int x; x=2^4; cout<<"x="<<x<<endl; cout<<"the size of x is:"<<sizeof(x)<<"bytes"<<endl; system("PAUSE"); return 0; } /* this result of programme is x=6 but 2^4=16 16 in binary is 10000 the size of x is : 4 bytes */ The ^ symbol is not an exponent in C++. ^ is a bitwise XOR. 2 bitwise XOR 4 evaluates to 6. If you fail to compile demo code, like this: ‘char16_t’ was not declared in this scope| ‘char32_t’ was not declared in this scope| or error C2065: ‘char16_t’ : undeclared identifier error C2070: ”unknown-type”: illegal sizeof operand error C2065: ‘char32_t’ : undeclared identifier error C2070: ”unknown-type”: illegal sizeof operand Please use following command to compile it: g++ -std=c++0x -o bin/Debug/2 main.cpp Why is sizeof() considered an operator and not a built-in function? How can we distinguish between a function and an operator? sizeof is an operator because the C++ standard says so. 🙂 It also requires type information that’s only available at compile time. If it were a function, it wouldn’t be run until runtime, and the size information it needed wouldn’t be available. If it’s on the operator list (see section 3.1 -- Precedence and associativity), it’s an operator. Otherwise, it’s a function. 🙂 Thank you! this line: "Because modern computers have a lot of memory, this often isn’t a problem, especially if only declaring a few variables." I would like you to delete it and instead suggest the would be programmers to always optimize their code. "A jug fills drop by drop." - The Buddha the future is in you hands. make it… right. Actually, best practice is to NOT prematurely optimize your code. You should code for readability, debugability, and consistency, and then optimize if and when necessary. In the book Computer Programming as an Art (1974), Donald Knuth (a renowned Computer Scientist) said, “The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.” For example, you _could_ pack every one of your boolean variables into bit flags to save memory, but for 99.99% of programs this simply isn’t necessary, and it adds a lot of complexity, degrades understanding, and increases the chance of error. It’s much better to use a little more memory than increase the risk of your program producing the wrong output or crashing. 1974 Yes, it’s from 1974. But back then, optimization was much more important than it is now since they had such small amounts of memory. So being from 1974 does not make it any less correct. In your code, you follow the order given in your table except for ‘long long’ and ‘float’ (see below). I recommend switching these lines of code for consistency. Also, with 4-space tabs (as recommended), ‘long long’ needs only one tab in its print line. If you make this change, be sure to update your output table. Also, typo: "Note that you can not take the sizeof the void type, since is (it) has no size" Also fixed. Thanks for pointing these out. #include<stdio.h> #include<conio.h> struct stud { int roll; char nm; }; int main() { printf("%d",sizeof(struct stud)); getch(); return 0; } this program shows me the output as 8. But it shoud be the 5 brecause int takes 4 bytes and char takes 1 byte. First off, your example is using C, not C++. I’ll forgive you. The sizeof a struct is not necessarily equal to the sizeof the elements it contains. The reasons for this are discussed in lesson 4.7 -- structs. Just a simple question: Why would you use the sizeof() function? Sizeof is used mostly for reasons you’ll learn about in future lessons. First, you can use sizeof() to see how large integers are on your machine, so you know the largest and smallest numbers they’ll hold. You’ll sometimes see developers document assumptions about variable sizes like this: Second, later on, we’ll learn about ways to dynamically allocate memory while your program is running. If you wanted to dynamically allocate memory for 4 integers, you’ll need to know how large those integers are, so you allocate enough memory for them. So I don’t have to worry about it too much right now? Nope, no need to worry about it too much right now. At this point, it’s more used to illustrate that variables have different sizes, so we can talk about the ramifications of that later. What is the minimum size for int? I think 4 Bytes. Please Check your table. The minimum size for int (as guaranteed by the C++ standard) is 2 bytes. However, for most modern architectures, ints are 4 bytes, and thus are larger than the minimum guaranteed size. Hey Alex, Just a heads up, the print out from your computer is missing the "long" output. It goes from "float" straight to "long long". Thanks, fixed. It’ll be a problem if I use the C++11 language standard to compile my programs for the rest of the tutorial? That was the only way i could make the code work, otherwise it’ll not compile at all. It’s fine if your compiler doesn’t support C++11. You’ll occasionally need to modify an example to remove C++11 specific lines (as in the case above), but I’ll generally try to keep the C++11 stuff separate so the examples will work whether your compiler supports C++11 or not. Alright, that's weird… So I ran the program, curious as to what was different. I expected my values to probably have one or two higher than normal. Instead, it popped up minimum values for everything… except one. (Well, two; int was 4 instead of 2; made sense after checking the next chapter though; that’s not what bothers me, though.) Somehow, char32_t shows up as only 2 bytes for my machine, but in the tutorial it states that C++ architecture ensures char32_t will have an absolute minimum of 4 bytes. So… yeah, I dunno what's up. Is it feeding me incorrect information, or has there somehow been a change where it was found to actually be possible to compress char32_t into 2 bytes instead of 4? Something's strange regardless of the answer. ----------- NEVER MIND, I'd typed that all out and figured out the problem: In the above code, there's an error. What you have listed is: cout << "bool:tt" << sizeof(bool) << " bytes" << endl; cout << "char:tt" << sizeof(char) << " bytes" << endl; cout << "wchar_t:t" << sizeof(wchar_t) << " bytes" << endl; cout << "char16_t:t" << sizeof(wchar_t) << " bytes" << endl; // C++11, may not be supported by your compiler cout << "char32_t:t" << sizeof(wchar_t) << " bytes" << endl; // C++11, may not be supported by your compiler What SHOULD be listed is: cout << "bool:tt" << sizeof(bool) << " bytes" << endl; cout << "char:tt" << sizeof(char) << " bytes" << endl; cout << "wchar_t:t" << sizeof(wchar_t) << " bytes" << endl; cout << "char16_t:t" << sizeof(char16_t) << " bytes" << endl; // C++11, may not be supported by your compiler cout << "char32_t:t" << sizeof(char32_t) << " bytes" << endl; // C++11, may not be supported by your compiler It was feeding me the stats for wchar_t not char16_t or char32_t, hence why it popped up 2. Once I fed in the updated code, it gave back the correct 4 bytes for char32_t, and char16_t remained at 2 bytes. I double-checked all the others just to be on the safe side and the rest of them are good, it was just the char16_t and char32_t that were off. Anyway, problem solved! Yay! Shame it wasn't possible to compress char32_t down to 2 bytes, though. =P Yup, copy/paste error in the sample code. It’s fixed now. Thanks for debugging. 🙂 Welcome, thanks for teaching me how to in the first place! =P I'm starting to think coding's a bit more of an artform than I already thought, though. Like it was already clear that it requires a lot of logic, but also a fair bit of grace. At this point, I'm starting to think it follows the rule for art: Art is never "finished", it simply runs out of time, resources or patience. Debugging seems to be a similar endeavour - you'll never get 100% of it cleared out on really complex programs (Maya, Windows, whatever), which explains why they're always coming out with new patches to fix stuff. I kind of knew before that changing anything in a program could inadvertently break something else in the process if you didn't especially carefully comment the hell out of everything, hence why so many games break something during a patch (LoL and WoW are especially notorious for such). I'm starting to see why it happens so often now, though, and even good commenting isn't always enough to completely avoid the damage. I suppose that's why alpha testers are so important though, and why wide-scale beta tests are essential. A million people trying to break something are simply vastly more effective at finding ways to do so casually, than a handful of dedicated testers that are actively trying to break something. Anyway, thanksies for the tutorial as normal. I'd almost suggest the average person should try to go through the first 2-3 chapters just to get a feel for how many problems there can be when writing a program, so that they're a little more understanding of the issues faced. =P Shouldn't cout << "char16_t:\t" << sizeof(wchar_t) << " bytes" << endl; // C++11, may not be supported by your compiler cout << "char32_t:\t" << sizeof(wchar_t) << " bytes" << endl; // C++11, may not be supported by your compiler be cout << "char16_t:\t" << sizeof(char16_t) << " bytes" << endl; // C++11, may not be supported by your compiler cout << "char32_t:\t" << sizeof(char32_t) << " bytes" << endl; // C++11, may not be supported by your compiler Otherwise it prints out wchar_t size instead of char16_t and char32_t! Using long doubles I made a program which can compute factorials up to 170!, more than my TI-831!. Since ^ is being so freely used here in the comments, I must mention to be careful using ^ as an operator in C++ expressions. C++ has NO built-in operator for exponentiation. The ^ operator in C++ is a binary (operating on two values) operator performing a bitwise XOR. For example what does 2^3 resolve to in C++? 2^3 int x = 2^3; x will not contain the value 8, it will contain the value 1 Why is this? Assuming 8 bit wide integers this is what happened: 00000010 ^ 00000011 -------- 00000001 <== bitwise XOR of the two integers results in value of 1. Any time you use mathematical operators with pointer types, you then are working with pointer arithmetic, and the expressions will evaluate differently depending on the size of the type pointed to. int i; size_t size1 = &i+1; // size1 is assigned address of next byte in storage space of the integer i size_t size2 = (int*)(&i+1); // size2 is assigned address of the next following integer, perhaps in an array. In the case of the size2 assignment in your posting, pointer arithmetic will resolve the size of the type, by taking the difference of the addresses of two identical data types that are adjacent in memory.?? Most modern compilers have options you can specify on the command line to target different architectures. There is a lot of information in the g++ documentation about this.? This is a challenging question with no easy answer. If you’re writing for portability, the best thing to do is assume that variables are only as large as their guaranteed minimum sizes and avoid the problem in the first place. If you do need to assume long double is 16 bytes for your code, you could use assert() to “document” that: That way anybody who compiles the code on an architecture or compiler that is using a different size would be aware of the issue.. Sometimes they just go round and round..) what the resone behind it, why you can’t overload the size of operator ? REgards, Ranjan Why would you want to? 🙂. Very nice. Being able to oveload the sizeof operator would be total anarchy. What do you mean when you use ^ and n in your equations? Are these standard operators and variables? 2^n means 2 to the nth power. eg. 2^3 = 2 * 2 * 2 = 8. 2^4 = 2 * 2 * 2 * 2 = 16. C++ does not have a built-in operator for exponentiation. There is a pow() function in the <cmath> library. And ^ is the C++ bitwise XOR. <cmath> Wow, imagine how many variables I could store in a kilobyte 😀 I know that years ago when they used to use punchtape in stuff like CNC machines, having a strip of tape that was over 12 kilobytes of information was very impracticle 😛 Back in the late 1970s we had an air show at the Air Force base I was stationed at. We had a paper tape punch machine set up so that attendees could type in their name or whatever and have it punched out on the tape as the actual letters, not the binary. Was a hit. My int takes 2 bytes. I am working with tourbo C . My PC is 32-bit. Turbo C only produces 16 bit DOS programs and is not C++ complaint. Consider upgrading to DJGPP, MinGW or any other modern compiler long double takes 12 bytes I bet you say that to all the ladies. now THAT is funny!! This page should have a like button! 😀 Lol As does mine. I bet that’s how you ADDRESS the ladies. too late? My long double is 16 bytes wide. But 7 years ago it probably would have been 12 like yours. how? . Yes, using 1-byte variables saves space. Modern architectures generally have memory that is byte-addressable, meaning you can read/write memory one byte at a time. x86 architecture computers can move different size “chunks” around (1 byte, 2 byte, 4 bytes, etc…). Generally you won’t have to worry about how the computer internally accesses memory and moves data around. Your compiler should be smart enough to use the best set of assembly instructions for whatever task you’re throwing at it. It would be easier to explain the whole thing using the architecture name x86(x86_64) rather than calling them ’32-bit’ machines. Confuses people.. Edit: To be clear, I’m not sure I see the practical use of using wchar_t instead of a variable that’s guaranteed to be at least 16 bits (e.g. char16_t). Pocket PC/Windows Mobile only uses wide characters. Beyond that the practical use is for foreign languages. Some languages (like Chinese) have a lot more than 128 characters. Name (required) Website
http://www.learncpp.com/cpp-tutorial/23-variable-sizes-and-the-sizeof-operator/comment-page-1/
CC-MAIN-2018-05
refinedweb
2,670
71.24
Hello commUnity, I am wandering how to surely get the Mono Version for a given Unity3D application ? Dynamically you only can get that : $INSTALLPATH\Unity350f5\Editor\Data\Mono\bin\mono.exe" -V Mono JIT compiler version 2.0 (Visual Studio built mono) TLS: normal GC: Included Boehm (with typed GC) SIGSEGV: normal Notification: Thread + polling Architecture: x86 Disabled: none But according to this post, I only get that information : Unity 3.2 uses a mono 2.6 (slightly customized with some bug fixes of ours). Unity 3.2 uses a mono 2.6 (slightly customized with some bug fixes of ours). So how can we have more precisions on that version and on the "slightly customized " ? (I need these precisions because I think I'm lacking System.Threading.Tasks from this) Ok it kind of puts me in the right direction, as I get the same error as with implementing a.NET 4.0 dll. I know Unity should be able to run a .NET 4.0 like mono implementation, at least nowadays. However, I apparently have jit compier 2.0 instead of the current version ( editor\data\mono\bin\mono -V --> jit compire v 2.0). How to fix? This is not a answer to the question, please post your own question if you have one Answer by Ghopper21 · Oct 17, 2012 at 12:01 PM Here you go (with thanks to the helpful Stack Overflow user who answer my similar question over there): Type type = Type.GetType("Mono.Runtime"); if (type != null) { MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (displayName != null) Debug.Log(displayName.Invoke(null, null)); } Thank you ! it works You'll need. using System; using System; But I used the code above on Unity 3.5.4 and 4.5 .Both told me the version is 2.0,not 2.6. Answer by Cyrille-Paulhiac · Jul 08, 2014 at 10:11 PM Well, I found a more precise solution now (the upper one gives only 2.0 as a result). Try this line of command: ...\Unity\Editor\Data\Mono\bin>monop2 --runtime-version mono.exe For Unity 4.5.1f3, I obtained "runtime version: 2.0.50727.1433" We're still quite in the past, aren't we ? Good Day, Just ran this against Unity Version 5.6.0f3 and it reports as follows: > monop --runtime-version mono.exe runtime version: 2.0.50727.1433 and in the editor, using the method described by @Ghopper21 it reports the following: 2.0 (Visual Studio built mono) UnityEngine.Debug:Log(Object) Also ran against Version 2017.1.0b3, the current beta on their site using the same method as above with the same versions reported. Answer by wvdv · Sep 24, 2015 at 04:18 PM Running monop --runtime-version mono.exe returns runtime version: 4.0.30319.17020 Is this current? I need to know when googling on stack overflow, which version of C# answers to actually read. I'm on OS X so I can't run this myself. This is listed as the Microsoft .Net version under Runtime Runtime: Microsoft .NET 4.0.30319.34209 GTK 2.24.20 GTK# (2.12.0.0) (Check the About tab in Mono, being the easiest way to find versions) All assemblies are listed under the Show Loaded Assemblies. `System.IO.File' does not contain a definition for `AppendText'? 1 Answer What version of Mono does Unity 5 use? 0 Answers How to run the Mono csharp interactive shell? 0 Answers Is there any way to use CSharpCodeProvider in build? 0 Answers Why do Two Instances of MonoDevelop Open when I double-click a CS file in Inspector? 0 Answers
http://answers.unity3d.com/questions/259448/how-to-determine-mono-version-of-unity-.html
CC-MAIN-2017-43
refinedweb
614
70.09
Hi @naisy, I previously updated the PyTorch 1.9 patch to include the NEON patch (after finding it was causing runtime computation errors) Hi @naisy, I previously updated the PyTorch 1.9 patch to include the NEON patch (after finding it was causing runtime computation errors) That is the path from which I built it on my Jetson. This is the corresponding location in the PyTorch 1.9 source code: This is the Context.cpp file, and I have build source and set variables. And why I still have the problems? terminate called after throwing an instance of 'c10::Error' what(): quantized engine QNNPACK is not supported Exception raised from setQEngine at /media/nvidia/NVME/pytorch/pytorch-v1.9.0/aten/src/ATen/Context.cpp:181 (most recent call first): frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) + 0xa0 (0x7f445c7300 in /home/yuantian/.local/lib/python3.6/site-packages/torch/lib/libc10.so) frame #1: c10::detail::torchCheckFail(char const*, char const*, unsigned int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) + 0xb4 (0x7f445c36b4 in /home/yuantian/.local/lib/python3.6/site-packages/torch/lib/libc10.so) frame #2: at::Context::setQEngine(c10::QEngine) + 0x138 (0x7f5aeb0940 in /home/yuantian/.local/lib/python3.6/site-packages/torch/lib/libtorch_cpu.so) frame #3: THPModule_setQEngine(_object*, _object*) + 0x94 (0x7f5fa12364 in /home/yuantian/.local/lib/python3.6/site-packages/torch/lib/libtorch_python.so) <omitting python frames> frame #5: python3() [0x52ba70] frame #7: python3() [0x529978] frame #9: python3() [0x5f4d34] frame #11: python3() [0x5a7228] frame #12: python3() [0x582308] frame #16: python3() [0x529978] frame #17: python3() [0x52b8f4] frame #19: python3() [0x52b108] frame #24: __libc_start_main + 0xe0 (0x7f78952720 in /lib/aarch64-linux-gnu/libc.so.6) frame #25: python3() [0x420e94] Aborted (core dumped) @_av @dusty_nv Kind regards Thanks for the reply. I tried out your suggestion and used the latest updated patch from @dusty_nv () to build PyTorch. It did successfully resolved my ISSUE 1. Now, it takes about 10 sec to parse the tensor from CPU to GPU. However, the ISSUE 2 which is the error of the torch.solve function still appears. Should I just ignore the error or does the error means anything in this case? Thank you and I do appreciate your help very much! Hi @ziimiin, I haven’t built MAGMA before, but are you able to test run MAGMA independently of PyTorch? Maybe there is some setting you need to compile MAGMA with to enable the correct GPU architectures for Jetson? (sm53, sm62, sm72) EDIT: It appears they need to be added in the MAGMA makefile: Hi @ziimiin I built MAGMA and Pytorch with Jetson and tried your ISSUE2. When using MAGMA in Python, it seems that you need to call magma_init () first. If I do not call magma_init(), I will get an error message. Error in magma_getdevice_arch: MAGMA not initialized (call magma_init() first) or bad device Calling magma_init() will resolve this error. I have uploaded the docker I used. (17.6GB) I confirmed that it can also work with Jetson Nano. sudo docker run --runtime=nvidia --rm -it -u jetson naisy/jetson451-pytorch-magma python3 import torch import ctypes magma_path = '/usr/local/magma/lib/libmagma.so' libmagma = ctypes.cdll.LoadLibrary(magma_path) libmagma.magma_init() A = torch.randn(2,3,3).cuda() B = torch.randn(2,3,4).cuda() torch.linalg.solve(A, B) libmagma.magma_finalize() The built source code is under /opt/github/. Appreciated your help! Thanks so much Same to @dusty_nv . Thanks for the response and help as well. Hi, I try to use libtorch (v1.9.0 precompiled) with QT (5.9.5) on a Jetson nano. I included the library : LIBS += -L"/home/jetson/libs/libtorch/lib" -ltorch but I got this error : skipping incompatible /home/jetson/libs/libtorch/lib/libtorch.so when searching for -ltorch cannot find -ltorch I found on internet that this error would mean that the library doesn’t correspond to the system (lib x86 and system x64), but when I check the lib : file libtorch.so I got libtorch.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=710c62b2bda3d3b7bb737e5026de30fd9aca88e0, not stripped So I’m a bit lost… Anyone has an idea ? Regards Stéphane Hi @steph27, when I run the same thing and inspect libtorch.so, I see that it was built for aarch64 (not x86_64): ~/.local/lib/python3.6/site-packages/torch/lib$ file libtorch.so libtorch.so: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, BuildID[sha1]=a00d5bc6e166568806d09407e6cf14873c5687e4, not stripped Are you sure that you installed the PyTorch 1.9 wheel for Jetson from this link? Thanks for the path !! As I couldn’t find the library and the include (for c++), I downloaded the pre-builded version () which is not compatible with the Jetson Nano. Thank you for your help. No problem - by the way, you can find these paths by running pip3 show <package-name>, and it will print out where the package is installed to. After I run the code ‘sudo pip3 install torch-1.7.0-cp36-cp36m-linux_aarch64.whl’ it shows that torch 1.7.0 is successfully installed But when I ‘import toch’ It still shows ‘No module named torch’ I dont know why Thanks! Hi @619914127, are you running python3 to import torch? Can you run python3 -c 'import torch'? I believe it’s because you are running python and pip which are the Python 2.7 versions - whereas you installed the wheel for Python 3.6 with pip3. Try using python3 and pip3 instead. I am having Jetson Xavier nx with jetpack 4.4 I am unable to install pytorch 1.5.1 through the commands given above. PyTorch v1.5.0 torch-1.5.0-cp36-cp36m-linux_aarch64.whl Please tell how to install that as soon as possible. Firstly it get install successfully but when I downloaded the other libraries given below:- numpy pillow scikit-learn tqdm albumentations jupyterlab matplotlib natsort scikit-image>=0.16.1 tensorboardx tensorboard torchcontrib tifffile pygit2 Archiconda then it automatically get removed and Now it is not downloading again throwing the error. Hi @vashisht.akshat.rn.04, I believe your issue is that you are using pip to try an install the wheel, when you should be using pip3 ( pip is for Python 2.7 and pip3 is for Python 3.6 - and these wheels are for Python 3.6) Also, please make sure the wheel you are installing is compatible with the version of JetPack you have. That wheel you linked to is only for JP 4.4 Developer Preview (L4T R32.4.2). If you are on the JP 4.4 production release (L4T R32.4.3) you would want to use a more recent wheel. I could not import torchaudio. As the instructions in l4t-pytorch , sudo docker pull nvcr.io/nvidia/l4t-pytorch:r32.6.1-pth1.9-py3 sudo docker run -it --rm --runtime nvidia --network host nvcr.io/nvidia/l4t-pytorch:r32.6.1-pth1.9-py3 I started l4t-pytorch container. But when I ran the code import torch import torchaudio I got a warning message /usr/local/lib/python3.6/dist-packages/torchaudio-0.9.0a0+33b2469-py3.6-linux-aarch64.egg/torchaudio/backend/utils.py:67: UserWarning: No audio backend is available. warnings.warn('No audio backend is available.') And then, I installed the sox pip3 install sox But I still got the same waring message. Is there anyone knows how to solve this problem, any advice would be appreciated. Thanks. Hmm I tried rebuilding the container after adding pip3 install sox (I already had apt-get install sox in the dockerfile), but still got this issue. Will require further investigation…if you figure it out, let me know.
https://forums.developer.nvidia.com/t/pytorch-for-jetson-version-1-11-now-available/72048?page=44
CC-MAIN-2022-33
refinedweb
1,302
59.4
Im working on a project where speed is a major concern and where I'm also working on alot of 4x4 arrays of chars. I would like to XOR these chars by grouping them together 4 at a time(by casting), hopefully as a optimization(so the proc is working with its normal 32 bit amount). Sounds simple but I cant seem to appease the compiler gods. My code: gives:gives:Code: #include <stdio.h> int main() { unsigned char x[4]; unsigned char y[4]; x = (unsigned char[4])((unsigned int)x ^ (unsigned int)y); return 0; } Any advice?Any advice?Quote: xor.c: In function 'main': xor.c:7: error: cast specifies array type Thanks
http://cboard.cprogramming.com/c-programming/103638-fast-xoring-chars-printable-thread.html
CC-MAIN-2015-48
refinedweb
116
74.08
Problem with plotting multiple plots in the same MatplotlibWidget graph - NilleDaWize last edited by NilleDaWize Hi, I am new to both python and QT4 but have since a couple of weeks back been working on a software that will take user based input and present the results in the QT matplotlibwidget. I can currently present one plot at a time in the widget but have not been able to plot multiple plots in the same graph. Oddly enough I am able to achieve multiple plots in the same graph if I use a normal matplotlib window(not the widget) when I run the same code using plt.show() instead of draw(). However when I call self.matplotlibwidget.axes.show() on the matplotlibwidget nothing appears in the plot. Here is the code that I can't get to run the way I would like: def plotRetained(self): i = 0 colors = cm.rainbow(np.linspace(0, 1, len(Model.busSetDictionary))) for everySet in Model.busSetDictionary: #busSetDictionary is a dictionary containing dictionaries(busDictionary) which contains a list busDictionary = Model.busSetDictionary[i] data = {"x":[], "y":[], "label":[]} for label, coord in busDictionary.items(): data["x"].append(coord[1]) data["y"].append(coord[2]) self.matplotlibwidget.axes.plot(data["x"], data["y"], marker='o', color = colors[i], markerfacecolor=colors[i], markersize=12) i+=1 self.matplotlibwidget.draw() When I run this code only the last itteration of busDictionary will be plotted instead of all the busDictionaries. If anybody could help me identify the problem that would be greatly appreciated! Ps. There are 1500 lines of code so I can not post all of it but if anyone is curious about other parts of the code just let me know and I will post that too. - SGaist Lifetime Qt Champion last edited by Hi and welcome to devnet, This is a question you should rather bring to the Matplotlib folks. On a side note, unless you are locked to that version, please move to Qt 5. Qt 4 has reached end of life a few years ago. - NilleDaWize last edited by The reason I asked you guys is that is seems specific to the QT MatplotlibWidget. Like I mentioned in the post I can achieve what I want in the normal Matplotlib Window but not in the MatplotlibWidget - SGaist Lifetime Qt Champion last edited by Well, that's the thing: the Qt MatplotLibWidget is still implemented by these guys hence my suggestion to ask them. You should also check whether you are using PyQt or PySide to see if it makes any difference. It should not but who knows. - NilleDaWize last edited by Ahh I see. I'll check it out! Thanks for the suggestion. If you have any other ideas please let me know.
https://forum.qt.io/topic/106093/problem-with-plotting-multiple-plots-in-the-same-matplotlibwidget-graph
CC-MAIN-2020-16
refinedweb
458
63.7
Here's a C program to check whether the person is in teen age or not with output and proper explanation. Here we find out whether a person is a teenager or not by using an if-else condition and C logical operators. # include <stdio.h> # include <conio.h> void main() { int age ; clrscr() ; printf("Enter the age : ") ; scanf("%d", &age) ; if(age >= 13 && age <= 19) printf("\nThe person is in teen age.") ; else printf("\nThe person is not in teen age.") ; getch() ; }Output of above program is Enter the age : 18 The person is in teen age. Explanation of above program Here first user enters a number specifying an age. Then in the If part of If-else condition we check whether the previously entered age is between the range of 13-19 i.e. the teen age. If the age that user entered is indeed between 13 and 19 then the If block gets executed otherwise the else part will be executed. Note: In the If condition here, if you notice you'll see that we are using logical AND (&&) operator for the conjunction of two conditions i.e. age >= 13 and age <= 19. That means the if part will only gets executed when both the conditions are true. Hello, Great post. Well though out. This piece reminds me when I was starting out C Programming Tutorial after graduating from college. I need to check how many numbers in strings of 16 numbers is less than for an example 6. I only need a main routine.. Excellent tutorials - very easy to understand with all the details. I hope you will continue to provide more such tutorials. Cheers, Franda
http://cprogramming.language-tutorial.com/2012/01/program-to-check-whether-person-is-in.html
CC-MAIN-2021-10
refinedweb
280
74.9
Right now it sounds like we have a fair amount of fragmentation in the JS GC heap. The reason this happens is that we have a big chunk that's mostly unused. One idea to solve this would be to allow individual arenas in the chunk to be marked as uncommitted (so that the address space is reserved but they're not backed by anything). I haven't considered it in depth, but naively this doesn't seem super difficult. We'd have to have a way of knowing which arenas are committed or not, so that we don't accidentally try to access an uncommitted arena's header or something. This would probably impose some additional expense in conservative stack scanning (maybe an additional hashtable lookup or something). The arena allocation and deallocation code would also get a little slower. However, I think that most of the time we only access the header of an arena where we know object's are stored. Before doing this, it would be good to have more data about the fragmentation. It would be useful to be able to separate out these two things: the unused space in a chunk that belongs to an unused arena versus the unused cells in an allocated arena. If most of the unused space is of the former kind, the optimization will work well. If it's of the latter kind, it will work poorly. Note that we would still pay a cost for having lots of mostly empty chunks. Each chunk has a fairly large amount of fixed overhead---mostly the mark bits, I think. I'm not sure how big this is offhand. Gregor, Igor, does this seem feasible to you guys? (In reply to comment #0) > > Before doing this, it would be good to have more data about the > fragmentation. It would be useful to be able to separate out these two > things: the unused space in a chunk that belongs to an unused arena versus > the unused cells in an allocated arena. Bug 670594 is open for this. I'm partway through a patch. I mentioned this to Nick briefly recently, but it seems that managing the JS arenas seems to be something we could allow jemalloc to do. jemalloc already does the decommit work at least, in much the same way that we would do it ourselves. I looked at the platform-specific decommiting code that jemalloc does. It actually seems like it would be trivial to port. Windows: VirtualFree(addr, size, MEM_DECOMMIT); Mac 10.6+: madvise((void *)((uintptr_t)chunk + (i << pagesize_2pow)), (npages << pagesize_2pow), MADV_FREE); jemalloc doesn't do this for all decommits, but rather keeps a track of dirty pages and does it when that hits some threshold. It could be that this is expensive, or it could be that the myriad hacks built into our jemalloc prevented us from doing this in a nice way. There may be a way on 10.5, but I've still to solve that bug for jemalloc (bug 670492). I dont think madvise works on 10.5). Other (linux+android I guess): if (mmap(addr, size, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, 0) == MAP_FAILED) abort(); Paul, would you mind checking what this call does on Linux and Mac? mprotect(addr, len, PROT_NONE); On 10.6, that instantly decommits (that is, Activity Monitor does not count the decommited memory, instantly). Tested with: #include <sys/mman.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <strings.h> int main() { int size = 100 * 1024 * 1024; char* x = malloc (size); memset(x, 1, size); printf("Ready...\n"); sleep (10); printf("Go!!\n"); mprotect(x, size/2, PROT_NONE); sleep (10); } OK, I just tried it on Linux myself. The mprotect thing didn't work by itself, but this does: mprotect(addr, len, PROT_NONE); madvise(addr, len, MADV_DONTNEED); I'm not sure about Mac. mprotect works the same on 10.5 as 10.6.. (In reply to comment #8) >. Ah yes, that's right. Back to the drawing board. >. This doesn't work on Mac. However, I tested the mmap call from comment 3, and that _does_ decommit, so I think we have a winner there. I'm going to experiment on doing that for jemalloc, and watch whether Tp5 drops. That will definitely confirm it. See bug 669245 comment 13 for alternative ways to deal with the fragmentation issue. Created attachment 545769 [details] [diff] [review] WIP - works on Mac This seems to work on Mac (no crashes). I'm going to benchmark shortly, but after that I think we should see how bug 669245 comment 13 plays out before finishing this. So this implementation completely destroys the performance. Running earley-boyer in the shell goes from .26s to 2.5s, v8-v6 takes 9s instead of 1.5s. So Earley-boyer is 2.25s slower, and has 29584*2 arena allocations/deallocations. That seems to be about 4.35*10^-5s per mmap. I tried to see if that's reasonable, and wrote a benchmark that does 10,000,000 mmaps (half committing+memset, half decommtting), and takes 26 seconds (vs 0.5s for just 5,000,000 memsets). So that means a single mmap call takes 2.6*10^-6s. Assuming that's the best case, we'd optimally add 0.4s to a benchmark which currently takes .26s. So the number of mmaps would need to be improved 30x or so. Since each chunk has 32 arenas, the only thing that sounds plausible is to limit this to the case when we have only 1 or two arenas live in a chunk, and we want to mmap the rest of the chunk. All in all, this doesn't seem a good way to go, at least compared to the promise of bug 669245 comment 13 and beyond. Are you doing it for every GC? I think we should only consider it for the "idle-GC" (gckind == GC_SHRINK) and on the background thread. (In reply to comment #13) > Are you doing it for every GC? > I think we should only consider it for the "idle-GC" (gckind == GC_SHRINK) > and on the background thread. This seems like a great idea. Then we'll never trigger this at all during the benchmarks. This would make it so that arenas could be in three states (used, free, or free and uncommitted) rather than two, but that should be easy to handle. That seems a good idea. I'll fix that up tomorrow and how it goes. Actually, I'm going to wait and see how bug 671702 goes, it looks like it's simpler and will work better. Created attachment 566330 [details] [diff] [review] WIP v2: updated to current tip. Updated to apply against current mozilla-central. Left to address: over-allocates memory in the chunk header, how much memory do we actually save, what is the performance implication?. Created attachment 566390 [details] [diff] [review] WIP v3: fix most crashers. This minimizes the excess memory we require in the chunk headers for the arena bitmap. It also catches more places where we attempt to access an uncommitted header and does a better job of bringing arenas safely back to life after they have been uncommitted for a time. We can now pass all of the shell tests with no aborts. Unfortunately, this still has a catastrophic effect on v8 performance, including an OOM when running splay: Before: [terrence@kaapuri v8]$ ../js-opt/js -m -n run.js Richards: 7117 DeltaBlue: 8622 Crypto: 10957 RayTrace: 3510 EarleyBoyer: 7824 RegExp: 2104 Splay: 10007 ---- Score (version 6): 6288 After: [terrence@kaapuri v8]$ ../js-opt/js -m -n run.js Richards: 7173 DeltaBlue: 4850 Crypto: 9636 RayTrace: 2230 EarleyBoyer: 3455 RegExp: 1889 splay.js:50: out of memory Todo: - figure out why we are OOMing on splay - find out how much of the overhead is in the OS's page management and how much is in the new arena management (In reply to Justin Lebar [:jlebar] from comment #18) >. I played with madvise(MADV_DONTNEED), mprotect(PROT_NONE), and mmap(PROT_NONE) yesterday afternoon. Only mmap causes linux to count the uncommitted memory towards our RSS. I worry about the utility of tracking unused pages in userspace if we cannot point to an easily visible number that we are improving. This is a job that the kernel is already doing, with the help of dedicated hardware. Ideally, providing the kernel with more accurate information from userspace should help it do a better job of managing our memory. The fact that we are making things worse with this patch is probably entirely our own fault still -- e.g. we could be keeping the page table from helping by aggressively thrashing the PROT bits on a handful of arenas. I'll do some serious profiling once I get things fully working to see if we can find and remedy the root cause of the slowdown. > Only mmap causes linux to count the uncommitted memory towards our RSS. Really? That's surprising. What's the RSS of the following program after it goes to sleep? For me, it's 256MB, indicating that memory freed by MADV_DONTNEED is not counted against RSS. #include <sys/mman.h> #include <stdio.h> #include <unistd.h> #define SIZE (512 * 1024 * 1024) int main() { char *x = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); int i; for (i = 0; i < SIZE; i += 1024) { x[i] = i; } madvise(x, SIZE / 2, MADV_FREE); fprintf(stderr, "Sleeping. Now check my RSS. Hopefully it's %dMB.\n", SIZE / (2 * 1024 * 1024)); sleep(1024); return 0; } $ ps -p 4770 -F UID PID PPID C SZ RSS PSR STIME TTY TIME CMD jlebar 4770 4677 0 132067 262520 7 20:41 pts/0 00:00:00 ./temp You are quite right: that works. I was using a malloc'd block when I performed the test. I thought that glibc's malloc used madvise to reserve addresses -- I will have to go find out what is really going on there now. Created attachment 567229 [details] [diff] [review] WIP v4: performance improved to match baseline when body commented When we comment out the actual decommit/recommit functionality (they are not by default in this patch), this patch matches the performance of mozilla-central. E.g. we _can_ get equivalent performance managing the free set outside of the arena bodies with a bit of work to find pages efficiently. This patch includes code for using mmap to decommit pages (commented) and madvise to decommit pages. The second seems to be a bit faster and, more importantly, does not fail with ENOMEM when we have too much fragmentation (i.e. on v8 splay). The performance of both however is cripplingly bad, almost halving our performance on v8 splay and EarleyBoyer. I don't think you need to madvise(MADV_NORMAL) memory to recommit it. Unless this actually improves performance? (I doubt it does much of anything...) I also don't understand why you're EOM'ing with "hard" commit/decommit (which is what you'll need to use on Windows...) but not with "soft" decommit (madvise). Do you understand what's going on here? It looks like this patch decommits an arena as soon as it's freed; I assume the plan, now that you've showed that it's possible for this code to perform well, is to decommit less aggressively? Created attachment 567233 [details] Synthetic benchmark. Build with: g++ -std=c++0x -O3 -o test test.cpp This synthetic benchmark allocates 1GiB of memory with mmap, fills a vector with pointers to the first byte of every page in the chunk of memory, then shuffles those pointers. It then walks the list (e.g. random walk of the memory area) and commits the page, decommits the page, or touches the first byte of the page, as listed, recording the time taken for the entire operation (e.g. time of all accesses/commits/decommits in the 1GiB chunk). The results from a typical run are: Allocate: 5 us Touch: 127993 us Touch: 2340 us Touch: 2340 us Commit: 38980 us Commit: 39210 us Commit: 38910 us Touch: 2292 us Touch: 2303 us Touch: 2321 us Decommit: 247002 us Decommit: 71764 us Decommit: 71452 us Commit: 40491 us Commit: 40383 us Commit: 40039 us Touch: 189611 us Touch: 4063 us Touch: 2712 us Decommit: 160546 us Decommit: 71747 us Decommit: 71436 us At one point, the rss at the end of this test was ~500MiB, but I cannot reproduce that -- at the moment it is sitting at 3KiB. Observations: - Decommitting has about the same overhead as a page fault. - Decommitting causes a page fault (after recommit). - Committing is fast, but not all that fast. Things still to do: - Investigate cost of commit/decommit of larger batches of pages (with touch on all subpages). - Figure out how jemalloc does this without incurring disastrous overhead. > - Figure out how jemalloc does this without incurring disastrous overhead. 1. On Linux/Mac, there's no explicit commit step. Memory freed with MADV_DONTNEED (Linux) or MADV_FREE (Mac) doesn't need to be explicitly re-madvise'd before it's touched. When you modify an MADV_DONTNEED'ed page, you incur a page fault which gives you a physical page there. 2. jemalloc keeps around some amount (a few mb) of committed but unused memory. (This is reported in about:memory as heap-dirty.) 3. When jemalloc decommits, it decommits adjacent pages in a single operation. I don't know how easy this would be to test, but I wonder whether malloc'ing arenas directly would be comparable in speed here. It's a shame to have to reinvent this wheel. (In reply to Justin Lebar [:jlebar] from comment #29) > I don't know how easy this would be to test, but I wonder whether malloc'ing > arenas directly would be comparable in speed here. It's a shame to have to > reinvent this wheel. Note that the new version of jemalloc (bug 580408) appears to have very fast, lockless paths for malloc and free. So if the current malloc is too slow, the new one might be fast enough. The memory reductions from this bug, plus the speed increases of the new jemalloc, might be enough to convince us to assign to it the resources it needs. Created attachment 567630 [details] [diff] [review] v5 - Memory decommit on GC_SHRINK. This is two patches, one part commented, the other uncommented. 1) The commented bits are the sane implementation using two bitmaps to track the free/uncommitted states. This version is slower because of the extra math in the fast path (commenting the committedArenas.get() check restores our performance). 2) The uncommented bits are the same computations, but tracking the free/committed state of each arena in a full byte in the chunk header. This version is the same speed as tip, even though it wastes a huge amount of memory (we spill 41 bytes into our last arena and end up with 4055 bytes of padding per chunk). The correct solution here is probably going to be: use the 'next' pointers in the arena headers to track free arenas (like tip) and add a single bitmap (which fits in our current padding) to track committed arenas. This will complicate the state tracking a bit, but should reduce our fragmentation and allow us to preserve our current performance on splay. If that does not work, the last thing we can try is to smash the free/committed bitmaps into one oversize bitmap. This will reduce the amount of math we need to do back to the single-bitmap case, but will require us to write some custom bit twiddling. (In reply to Justin Lebar [:jlebar] from comment #24) > I don't think you need to madvise(MADV_NORMAL) memory to recommit it. > Unless this actually improves performance? (I doubt it does much of > anything...) No, this is just ported forward from Paul's original patch with mmap. It is good to have there so that we can easily compare performance between methods that require this step and those that don't. (In reply to Justin Lebar [:jlebar] from comment #25) > I also don't understand why you're EOM'ing with "hard" commit/decommit > (which is what you'll need to use on Windows...) but not with "soft" > decommit (madvise). Do you understand what's going on here? Yes, it's pretty clear from the man page. When we decommit an arena from the middle of one memory mapping that the kernel is tracking, it now has to track two memory maps. If we split enough memory maps, we overflow the number of memory mappings that the kernel will allow one process to have. (In reply to Justin Lebar [:jlebar] from comment #26) > It looks like this patch decommits an arena as soon as it's freed; I assume > the plan, now that you've showed that it's possible for this code to perform > well, is to decommit less aggressively? Yes, on GC_SHRINK in particular. This will help the browser out without impacting shell performance. (In reply to Justin Lebar [:jlebar] from comment #29) > I don't know how easy this would be to test, but I wonder whether malloc'ing > arenas directly would be comparable in speed here. It's a shame to have to > reinvent this wheel.. This is a reasonable tradeoff for the js engine, but not for jemalloc. >.) > If we split enough memory maps, we overflow the number of memory mappings that the kernel will > allow one process to have. Interesting! I wonder what's going to happen on Windows, where we don't have madvise. (In reply to Justin Lebar [:jlebar] from comment #33) >.) Bill already tried this: the overhead of the hash lookup was too high. The real, long-term, solution to this bug is to have a moving GC and do compaction. Using malloc, even if it gives us a speedup in the short term, will make it harder to solve the fundamental problem later. > Interesting! I wonder what's going to happen on Windows, where we don't > have madvise. Are you volunteering to do the porting work? :-) > Bill already tried this He tried both the naive hashtable and the hybrid hashtable / trie approach I suggested? Can you point me to a bug? (There are all sorts of things one might do here if the data structure is a bottleneck. I'm skeptical that we can't make the operation "is page X contained in our data structure?" very fast, even for a table of ~50,000 elements.) I don't want to distract us from the bug at hand; I think what you're doing is the right short-term solution; it's easier than getting jemalloc2 to work. But I don't understand how a compacting GC changes the game. You still have to manage chunks and decommit memory you're not using, right? My point is that this is hard to do right. Just to clarify, I haven't tried replacing chunks with malloc. Igor might have tried something like that, but it was a while ago. A moving GC would pretty much make this bug obsolete, since compaction eliminates fragmentation and there's no need to decommit. We won't have that for a while, though. Let's stay focused on this bug. Created attachment 567909 [details] [diff] [review] v6 - Getting close. This patch tracks free arenas in a linked list, as with tip, and tracks decommitted arenas in the chunk header in a bitmap, as in prior patches. Arena decommit is done (in the simplest possible way currently) when we take a GC_SHRINK event. With the re-arrangement I have made to allocateArena, this patch actually gives a very slight speedup on shell tests. Open Questions: 1) How is the style and naming? 2) What do we want/need to do when our (De)CommitMemory fails? On linux, we can ignore this (and should be skipping the CommitMemory call). On windows, these are not advisory, so it is more serious there. Do we want to throw an OOM exception up, investigate our recovery options, abort? 3) Where should I really put the call to DecommitFreePages? Right now it is right after the MarkAndSweep call, but that's a wild guess on my part. This seems like a reasonable place to put it, but there is a ton of THREADSAFE in this area that I don't totally understand yet. 4) How do we want to reflect this change in about:memory? I think they still get reflected in the dirty chunk counts, but we probably want to track them separately so that we can distinguish them in bug reports, etc. > 4) How do we want to reflect this change in about:memory? I think they still get reflected in the > dirty chunk counts, but we probably want to track them separately so that we can distinguish them in > bug reports, etc. We are, like, *so* unconcerned with mappings which don't contribute to RSS. I'd add a new js-heap-decommitted field and make the rest of the numbers reflect resident memory. Comment on attachment 567909 [details] [diff] [review] v6 - Getting close. Looks good! Terrence and I talked about this in person. Created attachment 569413 [details] [diff] [review] v7: With working Windows memory decommit. This appeared to work in Windows, but crashed once in an opt build and had many assertions in debug build. However, tip had the same assertions in a debug build. I think my windows build environment may just be wrong somehow. I have commented out the "only in GC_SHRINK" check (so we always decommit when collecting) in the attached patch -- could I get a try run of this patch/configuration to see if any of the windows buildbots explode? If they don't explode it will be strong evidence that the problem is on my end and increase our confidence in the correctness of this patch. Still TODO: update about:memory counters. The sizes we report in about:memory do not seem to match up with any of the OS reported memory sizes. Is this expected. > Still TODO: update about:memory counters. The sizes we report in about:memory do not seem to match > up with any of the OS reported memory sizes. Is this expected. Is what, exactly, expected? I'd add an additional js-gc-heap-chunk-decommitted field and make js-gc-heap-chunk-{dirty,clean}-unused track only committed pages. I pushed this to try: On Mac, we're going to want something like bug 693404 to unmap and remap the MADV_FREE'd pages before we measure RSS, so we get accurate measurements there. Pushed again: Created attachment 570746 [details] [diff] [review] v8: Simplified arenaAllocate The use of JS_(UN)LIKELY is actually a significant perf increase with this branch structure, which it was not for the previous. With the JS_(UN)LIKELY annotations, this version is actually just a tad faster. Comment on attachment 570746 [details] [diff] [review] v8: Simplified arenaAllocate Review of attachment 570746 [details] [diff] [review]: ----------------------------------------------------------------- Nice patch. My comments are just nits. I think it's almost done, although we still have to do the about:memory stuff. Do you have time to do that? If not, I can take care of it soon. ::: js/src/ds/BitArray.h @@ +40,5 @@ > + > +#ifndef BitArray_h__ > +#define BitArray_h__ > + > +#include "js/TemplateLib.h" It's not really necessary, but it would be nice to #include jstypes.h, since it's what defines JS_BITS_PER_WORD. @@ +59,5 @@ > + } > + > + inline bool get(size_t offset) const { > + return map[offset >> tl::FloorLog2<JS_BITS_PER_WORD>::result] & > + ((size_t)1 << (offset & (JS_BITS_PER_WORD - 1))); It's kind of nice how the GC does this, with getMarkWordAndMask. Maybe we could do that here too. ::: js/src/jsgc.cpp @@ +551,3 @@ > > /* We clear the bitmap to guard against xpc_IsGrayGCThing being called on > uninitialized data, which would happen before the first GC cycle. */ While you're here, could you fix this comment to have the usual style? /* * */ @@ +555,5 @@ > > + /* Initialize the arena tracking bitmap */ > + decommittedArenas.clear(false); > + > + /* Initialize the chunk info */ Period at the end of the comment, here and elsewhere. @@ +565,1 @@ > /* The rest of info fields are initialized in PickChunk. */ This comment should probably stay at the end of the function. @@ +568,5 @@ > + for (jsuint i = 0; i < ArenasPerChunk; i++) { > + arenas[i].aheader.init(); > + arenas[i].aheader.next = (i + 1 < ArenasPerChunk) > + ? &arenas[i + 1].aheader > + : NULL; This takes one extra branch per loop iteration, but hopefully it won't matter. It is clearer this way. @@ +626,5 @@ > + return i; > + for (jsuint i = 0; i < info.lastDecommittedArenaOffset; i++) > + if (decommittedArenas.get(i)) > + return i; > + JS_ASSERT(false); It's more idiomatic to use JS_NOT_REACHED here. @@ +630,5 @@ > + JS_ASSERT(false); > + return -1; > +} > + > +ArenaHeader* This should be |ArenaHeader *|. Only the tracer code leaves out the space (and not for long). @@ ? @@ +2621,5 @@ > + */ > + chunk->info.freeArenasHead = NULL; > + > + while (aheader) { > + /* store next so that we have it after we decommit */ Please capitalize at the beginning and add a period at the end. Also below. ::: js/src/jsgc.h @@ +365,5 @@ > > JSCompartment *compartment; > + > + /* > + * ArenaHeader->next has two purposes: when unallocated, it points to the next ArenaHeader::next @@ +367,5 @@ > + > + /* > + * ArenaHeader->next has two purposes: when unallocated, it points to the next > + * available Arena's header. When allocated, it points to the next arena of the > + * same size class. ...of the same size class and compartment. @@ +558,5 @@ > + /* Free arenas are linked together with aheader.next */ > + ArenaHeader *freeArenasHead; > + > + /* > + * Decommitted arenas are tracked by a bitmap in the chunk header. We use We use one space after a period. Please fix this elsewhere too. @@ +567,5 @@ > + > + /* > + * We need to track num freed, decommitted (at OS level) and the total. We > + * track free and the total and compute decommitted, since free and total > + * unused are used in a fast path and decommitted is not. For the names, I would suggest numArenasFree and numArenasFreeCommitted. Then the comment could be like this: numArenasFree: number of free arenas, either committed or decommitted numArenasFreeCommitted: number of free committed arenas Right now, it's hard to tell what they mean. @@ +572,5 @@ > + */ > + uint32 numArenasFree; > + uint32 numArenasUnused; > + > + /* Number of gc cycles this chunk has survived. */ gc -> GC @@ +580,5 @@ > +/* > + * Our chunk overhead takes up less than 8 arenas (32KiB), so there is no point > + * computing the exact number of bits we need to track the arenas in a chunk -- > + * it will always be the same number of bytes as tracking all possible arenas > + * in a chunk. Above this paragraph, it would be good to explain the basic calculation. Something about how you over-estimate the number of arenas per chunk, and use that to compute the size of the decommit bitmap. And then you compute the actual number of arenas per chunk by dividing the remaining space by the amount of per-arena data (including its mark bitmap). Then there's more context for describing how the over-estimate is actual about as good as we're going to get in practice. @@ +587,5 @@ > +const size_t MaxArenasPerChunk = ChunkSize / ArenaSize; > + > +/* Number of bytes we allocate to bitmap bits to track per-arena state. */ > +JS_STATIC_ASSERT(MaxArenasPerChunk % JS_BITS_PER_BYTE == 0); > +const size_t ChunkArenaBitmapBytes = MaxArenasPerChunk / JS_BITS_PER_BYTE; I like the name ChunkDecommitBitmapBytes better. @@ . @@ +804,5 @@ > } > #endif > > inline void > +ArenaHeader::init() This is the same as setAsNotAllocated now. I'd rather leave the code as before, without changing prepare or. ::: js/src/jsgcchunk.cpp @@ +272,3 @@ > #endif > > namespace js { Could you just wrap this whole thing in namespace gc? Then you wouldn't need the scoping below. @@ +273,5 @@ > > namespace js { > > inline void * > FindChunkStart(void *p) Can this function be static? @@ +339,5 @@ > } /* namespace js */ > > +#ifdef XP_WIN > +bool > +js::gc::CommitMemory(void *addr, size_t size) These functions should go inside the js and the gc namespace declarations. @@ . @@ +371,5 @@ > + int result = madvise(addr, size, MADV_DONTNEED); > + return result != -1; > +} > +#else > +JS_STATIC_ASSERT(1 == 0); It's more typical to use something like |#error "No CommitMemory defined"|. Created attachment 570900 [details] [diff] [review] v9: With review feedback. This is not yet ready for re-evaluation: I will figure out the memory reporters for about:memory tomorrow, at which point it should be good for a final review. (In reply to Bill McCloskey (:billm) from comment #46) > Comment on attachment 570746 [details] [diff] [review] [diff] [details] [review] > v8: Simplified arenaAllocate > > Review of attachment 570746 [details] [diff] [review] [diff] [details] [review]: > ----------------------------------------------------------------- > > @@ ? This was actually a significant slowdown -- !>0 is not equal to ==0 and GCC gets the first slower. Replaced this with a new inline method noAvailableArenas. > @@ +558,5 @@ > > + /* Free arenas are linked together with aheader.next */ > > + ArenaHeader *freeArenasHead; > > + > > + /* > > + * Decommitted arenas are tracked by a bitmap in the chunk header. We use > > We use one space after a period. Please fix this elsewhere too. My English teacher twitches anxiously in her grave. > @@ . I have Python on the brain still, it. ArenaHeader is about half one way and half the other, so I made the things I touched consistent. Looks like I moved things the wrong direction. :-) > ::: js/src/jsgcchunk.cpp > @@ +272,3 @@ > > #endif > > > > namespace js { > > Could you just wrap this whole thing in namespace gc? Then you wouldn't need > the scoping below. It makes sense to me. I thought we had changed our style to not wrap our cpp files with namespaces last week -- I'm probably just not understanding exactly what was decided. Everything in jsgcchunk needs a thorough scrubbing to remove the C/jemalloc look. > @@ +273,5 @@ > > > > namespace js { > > > > inline void * > > FindChunkStart(void *p) > > Can this function be static? Fixed. Everything in jsgcchunk also needs a thorough scrubbing to remove the Copy/Paste-itis. > @@ . My C roots are showing. > I will figure out the memory reporters for about:memory tomorrow What's the plan? It's not clear to me what the best thing to do is. (In reply to Nicholas Nethercote [:njn] from comment #48) > > I will figure out the memory reporters for about:memory tomorrow > > What's the plan? It's not clear to me what the best thing to do is. From comment 41: > I'd add an additional js-gc-heap-chunk-decommitted field and make > js-gc-heap-chunk-{dirty,clean}-unused track only committed pages. Also, from comment 43: > On Mac, we're going to want something like bug 693404 to unmap and remap the MADV_FREE'd pages > before we measure RSS, so we get accurate measurements there. I'm not wild about the nomenclature in this patch, fwiw. Everything I've read (e.g. [1], jemalloc) uses "committed" to mean "you can touch this without segfaulting". So when I mmap a chunk, the whole thing is "committed", even though the mapping doesn't have any physical pages until I touch it. [1] Justin, could you explain what went on in bug 693404? Reading it made my head hurt. Regarding nomenclature, I think that on Linux and Mac we do exactly what jemalloc does. On Windows, my understanding is that MEM_RESET does pretty much the same thing as decommitting from a memory usage perspective. If that's not true, it's easy to change--we never actually touch the page anyway. But it seems confusing to invent a new word to describe a concept that differs from decommitted in only a very esoteric way. My concern about nomenclature stems mainly from MSDN's description of MEM_RESET: >. It seems weird to say that we're "decommitting" memory by calling something which says it's not doing that. (jemalloc uses the words in the same way; it explicitly doesn't "decommit" memory when it calls madvise(MADV_DONTNEED).) But I agree that making up a new name might not make things clearer. It may depend on the name. :) > Justin, could you explain what went on in bug 693404? Reading it made my head hurt. Er, yes. I didn't explain things very well in that bug. The problem is that on Mac, when you madvise(MADV_FREE), you're hinting to the OS, "I don't need these pages, so you can take them back whenever." The OS is lazy about this, and only takes back the pages when there's memory pressure on the machine. Until then, they count against your RSS. This means that whatever memory gains you're getting from MADV_FREE, you can't measure with RSS. You could say that your "true RSS" is RSS minus the number of pages you've MADV_FREE'd, but then when you have memory pressure and the OS frees those pages, you're under-counting your RSS! The hack we did in jemalloc is to add a function which explicitly purges all MADV_FREE'd pages, by decommitting and recommitting them (with mmap(PROT_NONE) and mmap(PROT_READ | PROT_WRITE)). We then call this function before we read RSS on Mac [1]. This way, when you open about:memory, you'll see the correct RSS (in about:memory and in the Mac task manager). Telemetry also calls this function, so it'll report the correct result. [1] (see GetResident implementation). I should add that I'm quite guilty of being loose with this nomenclature. In about:memory, we use "heap-committed" to mean "heap that's in memory". In fact, jemalloc_stats.committed is, on Linux and Mac, the type of "committed" in this patch, rather than the segfault type of committed. Anyway, if we're going to abuse the word, we should at least be clear about it in the code. I agree with Justin that the word decommit is wrong here; it's what I've been using because that's what the patch I started with called it, and that was probably the original intent. We know now that full decommission doesn't work well enough. I switched to "advisory decommission", but didn't update the name of the function. I'd love to change it now before this gets, err, committed. What color should this bikeshed be: What is the right word for this memory state? Based on an e-mail exchange with jasone, the author of jemalloc, we should double-check that VirtualAlloc(MEM_RESET) frees memory and is reflected in Firefox's RSS as we expect on all supported platforms. Created attachment 571440 [details] [diff] [review] v10: Hooked up about:memory Now that about:memory is hooked up, we can finally view the full effects of this patch in the real world. Result: useless. <1MB returned to the OS after closing all tabs after MemBench. If we run the decommit aggressively on every GC, this improves to 54MB, but immediately drops to <1MB after a second cycle, even with only 130MB used of the 800MB allocated. Unfortunately, our fragmentation appears to reside as heavily within arenas as it does within chunks. The Memshrink work, will, doubtless, make this even worse by putting more objects in each arena. Created attachment 571473 [details] [diff] [review] v11: rebased and fixed a critical bug Things may not be as bleak as I thought. The analysis appeared to be working -- it got some results. However, Bill spotted a typo that would have usually, but not always, have kept us from counting all the decommitted memory. Re-testing now. Comment on attachment 571473 [details] [diff] [review] v11: rebased and fixed a critical bug Review of attachment 571473 [details] [diff] [review]: ----------------------------------------------------------------- You haven't updated the computation of gcHeapUnusedPercentage. Maybe that's deliberate, but you've changed it's meaning. I'm not sure if that's a good thing or not. The description of "js-gc-heap-unused-fraction" needs changing to make clear it no longer counts decommitted memory. Perhaps it should be renamed "js-gc-heap-committed-unused-fraction" (similar to "heap-committed-unallocated-fraction"). Or, the computation should include the decommitted counts. You also haven't updated the computation of numDirtyChunks, you probably should. I wonder if it's better to not change any of the counters under "explicit", and just add a "js-gc-heap-decommitted" counter to the "Other Measurements" list. That would be less likely to introduce errors in the existing counters. ::: js/xpconnect/src/XPCJSRuntime.cpp @@ +1573,4 @@ > > js::IterateCompartmentsArenasCells(cx, data, CompartmentCallback, > ArenaCallback, CellCallback); > + js::IterateChunks(cx, data, ChunkCallback); Don't you have to call this before using data->gcHeapChunkCleanDecommitted above? @@ +1947,5 @@ > + JS_GC_HEAP_KIND, > + data.gcHeapChunkCleanDecommitted + data.gcHeapChunkDirtyDecommitted, > + "Memory in the address space of the garbage-collected JavaScript heap that " > + "is currently returned to the OS.", > + callback, closure); The description should say "The same as 'explicit/js/gc-heap-decommitted'. Shown here for easy comparison with other 'js-gc' reporters.", similar to the description for "js-gc-heap-chunk-dirty-unused". You should also change the description of gc-heap-chunk-*-unused to make it clear that they're mutually exclusive with the gc-heap-decommitted. > I wonder if it's better to not change any of the counters under "explicit", and > just add a "js-gc-heap-decommitted" counter to the "Other Measurements" list. > That would be less likely to introduce errors in the existing counters. I think it's Good and Right if explicit only counts memory which counts against our RSS. Nick and I are talking about this on IRC and I *think* he agrees, but I'm not sure. :) Do you have any performance numbers for low-end machines? Using less memory should be a big win there but also interesting is the performance when we have to use the memory again. So with respect to the memory reporter, Nick and I agreed that it's OK if you report it in explicit, so long as the not-in-core memory is a separate line item from the in-core memory. The plan is to add a new memory reporter type for not-in-core (what we've been loosely calling "decommitted") memory, so we can distinguish it from in-core memory. But we don't need to block this work on that. Created attachment 571863 [details] This appears to work in win7. In this screenshot, memory usage plunged in the windows system monitor after we closed all tabs and did a decommit cycle. Created attachment 571866 [details] [diff] [review] v12: final version I believe this should be the last version. Nicholas and I discussed the changes I made to the XPConnect code on IRC, so I think that part is good now. I would also like feedback on the big block of text I added to jsgc.h to explain the ArenasPerChunk calculation: is this still clear when read by someone who is not me? I think we can land this for FF10 with time to spare. Comment on attachment 571866 [details] [diff] [review] v12: final version Review of attachment 571866 [details] [diff] [review]: ----------------------------------------------------------------- The memory reporter stuff looks ok. There's room for improvement in the terminology: we talk about "used", "unused", and "decommitted". More accurate would be "used", "used-and-committed", "unused-and-decommitted". (And better names would obviate the need for the "decommitted is mutually exclusive with unused" part of the descriptions.) Those names are rather wordy, though. If you can think of better names, that'd be great. If not, what you have in the patch will do. ::: js/xpconnect/src/XPCJSRuntime.cpp @@ +1289,5 @@ > +{ > + IterateData *data = static_cast<IterateData *>(vdata); > + for (uint32 i = 0; i < js::gc::ArenasPerChunk; i++) > + if (chunk->decommittedArenas.get(i)) > + data->gcHeapChunkDirtyDecommitted += js::gc::ArenaSize; Should decommittedArenas be called dirtyDecommittedArenas? @@ +1561,5 @@ > data->compartmentStatsVector.SetCapacity(rt->compartments.length()); > > + data->gcHeapChunkCleanDecommitted = > + rt->gcChunkPool.countDecommittedArenas(rt) * > + js::gc::ArenaSize; Should countDecommittedArenas() be called countCleanDecommittedArenas()? @@ +1573,4 @@ > > js::IterateCompartmentsArenasCells(cx, data, CompartmentCallback, > ArenaCallback, CellCallback); > + js::IterateChunks(cx, data, ChunkCallback); A comment above this call saying that it sets data->gcHeapChunkDirtyDecommitted would be nice. @@ +1640,5 @@ > data->totalAnalysisTemp += stats.typeInferenceMemory.temporary; > } > > size_t numDirtyChunks = (data->gcHeapChunkTotal - > data->gcHeapChunkCleanUnused) / I think you need to subtract data->gcHeapChunkCleanDecommitted as well? I'm fine doing the Mac measurement fixes for this (comment 52) as a followup, but we do need to do it. Can you please file a blocking bug? (In reply to Justin Lebar [:jlebar] from comment #65) > I'm fine doing the Mac measurement fixes for this (comment 52) as a > followup, but we do need to do it. > > Can you please file a blocking bug? This is only a problem on 10.5, right? I'm pretty sure it's a problem on all versions of Mac OS. We initially didn't turn jemalloc on for 10.5 because jemalloc appeared to be a regression. But on 10.6, it just so happened that jemalloc's high water mark was close to the system malloc's memory usage, so we didn't see a regression. My understanding is that this will not be a _regression_ on MacOS, correct? If not, I think we should push forward with this for the win it gives us on Windows and Linux. We then have 6 weeks to hammer out real improvements to the entire allocation path, rather than just papering over this difference. There are just 2 work days remaining in this merge window and it would be nice to have broader testing on at least one nightly before it becomes difficult to fix any regressions that crop up. > My understanding is that this will not be a _regression_ on MacOS, correct? Correct. It should be a memory win on MacOS, but we won't be able to measure it. In a sense, we are regressing our ability to measure memory usage accurately, but I don't think that's enough to hold up this patch, which should be a big win. Comment on attachment 571866 [details] [diff] [review] v12: final version Review of attachment 571866 [details] [diff] [review]: ----------------------------------------------------------------- Great, thanks a lot! ::: js/src/jsgc.cpp @@ +2906,5 @@ > > MarkAndSweep(cx, gckind); > > + if (gckind == GC_SHRINK) > + DecommitFreePages(cx); Could you move these lines to SweepPhase, right after the chunk expiration stuff near the bottom? That way it will get timed as part of the PHASE_DESTROY stuff. It also makes more sense there. ::: js/src/jsgc.h @@ +612,5 @@ > + */ > +const size_t BytesPerArenaWithHeader = ArenaSize + ArenaBitmapBytes; > +const size_t ChunkDecommitBitmapBytes = ChunkSize / ArenaSize / JS_BITS_PER_BYTE; > +const size_t ChunkBytesAvailable = ChunkSize - sizeof(ChunkInfo) > + - ChunkDecommitBitmapBytes; This will fit on one line (we allow up to 100 characters). @@ +727,5 @@ > bool unused() const { > + return info.numArenasFree == ArenasPerChunk; > + } > + > + bool noAvailableArenas() const { Let's just have one function to do this and reverse the polarity, as we discussed. Created attachment 572145 [details] [diff] [review] v13: final final version Applied review feedback. Created attachment 572146 [details] [diff] [review] v13: with a fixed reviewer string Missed this when refreshing the patch header. The change is very small, but it may be statistically significant. Before the change there were no scores of 177, and after the change 3 out of 8 runs have that score. In normal use of the browser, I see 0mb decommitted in about:memory (latest trunk). Is this normal? Also, have you filed the followup bug for measurement on Mac? (In reply to Justin Lebar [:jlebar] from comment #78) > In normal use of the browser, I see 0mb decommitted in about:memory (latest > trunk). Is this normal? Yes, this is normal. The decommit code only runs on GC_SHRINK, which currently only happens when the browser is idle and allocates a new chunk. The most significant impact right now is going to be for people who leave their browser on overnight with many tabs open. There are plans underway, as in the bug you linked, to make GC_SHRINK happen more frequently. > Also, have you filed the followup bug for measurement on Mac? No, I thought you were going to do that. > There are plans underway, as in the bug you linked, to make GC_SHRINK happen more frequently. Bug 700291 has to do only with about:memory, so normal users aren't going to get a memory boost from that. Are there bugs on the other plans which are underway to make this GC_SHRINK happen more often? > Also, have you filed the followup bug for measurement on Mac? Sure, I'd be happy to. (In reply to Marco Bonardo [:mak] from comment #76) > I was not able to reproduce this. On a linux32 opt build I get before and after this patch times of: before (79812:ec39a58d7f39) - 2379.68runs/s (Total) after (79813:940adaea65a1) - 2403.43runs/s (Total) That noise must have been rats or something. Nothing there now. I see that DecommitMemory can returns false. But do we have any indications that this can happen in practice? For example, we assume that munmap/VirtualFree is infallible, so I suppose that the decommit should be similar. You are quite correct! The reason I left it returning bool is that it is not clear that we want a strictly advisory decommit on all platforms. We are currently doing only advisory decommit because stricter decommission can fail on Linux, and MEM_RESET has equivalent semantics on Windows: it was the path of least resistance. On MacOS, however, the advisory decommit does not show up in RSS, so we probably want to investigate doing a stronger, fallable decommit there at some point. I left this as future work because the stronger requirements will require significantly more testing, and it is on a platform I do not use regularly. I don't consider this a super-high priority, but the decommit isn't on a fast-path, so I didn't bother changing it after we decided to only go with the less-strict decommit at first. (In reply to Terrence Cole [:terrence] from comment #83) > The reason I left it returning bool is that it is > not clear that we want a strictly advisory decommit on all platforms. We > are currently doing only advisory decommit because stricter decommission can > fail on Linux, What is the stricter decomission?. (In reply to Igor Bukanov from comment #84) > What is the stricter decomission? VirtualFree/munmap: removal of the pages from the process' memory mapping. What we are currently doing is VirtualAlloc(..., MEM_RESET, ...) and mmadvise(..., MADV_DONTNEED, ...) which keeps the pages in the process' management, but tells the kernel that the pages are no longer in use. The effect of this is that if the kernel needs to free up physical memory in the future, it will preferentially use these pages and not bother swapping them out before overwriting them. (In reply to Nicholas Nethercote [:njn] from comment #85) >. On it. The stricter decommit is not needed with MADV_DONTNEED on Linux. On Linux, MADV_DONTNEED'ed pages don't count against your RSS. It is needed with MADV_FREE'd pages on Mac. I don't know about Windows; we should test... Created bug 702480. (In reply to Justin Lebar [:jlebar] from comment #87) > The stricter decommit is not needed with MADV_DONTNEED on Linux. On Linux, > MADV_DONTNEED'ed pages don't count against your RSS. I saw few times on Linux that when GC decommits, say, 300, MB of pages, then RSS shrinks just by 30-50 MB max. Does MADV_DONTNEED really works on Linux as advertised? > Does MADV_DONTNEED really works on Linux as advertised? Perhaps not! Or perhaps its behavior is different in the browser than in the simple tests I've run. (It's also possible that 250mb of the 300mb decommitted was not in physical memory.) I filed bug 702979 on checking this out.). (In reply to Randell Jesup [:jesup] from comment #91) >). The patch can only improve the situations - it tells the system that a particular page is unused and its physical memory can be used for other things. Without the patch that page will be sitting on the GC empty list to be only released when the whole 1MB GC chunk is released.
https://bugzilla.mozilla.org/show_bug.cgi?id=670596
CC-MAIN-2016-30
refinedweb
7,942
64.81
Posted 21 August 2012 - 04:50 AM Posted 21 August 2012 - 07:25 AM Posted 21 August 2012 - 08:15 AM I gets all your texture budgets! Posted 21 August 2012 - 08:48 AM struct Tileset { EditorWindow* pWindow; EditorImage* pTilesetImage; EditorSelectRect* pSelectRect; Update(); Draw(); } Posted 21 August 2012 - 09:25 AM New game in progress: Project SeedWorld My development blog: Electronic Meteor Posted 21 August 2012 - 09:35 AM I gets all your texture budgets! Posted 21 August 2012 - 10:05 AM For instance, a clickable menu entry can be an aggregate of a TextEntry and a Button A scrollbar (just the bar itself, not the screen it scrolls) would be a Button and a Draggable entity with vertical/horizontal constraints added to it #pragma once #include <Windows.h> #include <vector> #include "Input.h" #include "Sprite.h" using namespace std; class EditorObject { public: EditorObject(void); virtual ~EditorObject(void); void Setup(int iID, int iX, int iY, float fZ, int iWidth, int iHeight, Sprite* pSprite); virtual bool Over(Vector2 vMousePosition); //mouse is pointing at this object? virtual void Draw(float fZ); virtual EditorObject* Check(Vector2 vMousePos); //return object at which the mouse is pointing virtual bool Update(void); virtual void UpdateSuper(int iOffX = 0, int iOffY = 0); void SetX(int iX); void SetY(int iY); void SetSuperX(int iX); void SetSuperY(int iY); int GetID(void); int GetX(void); int GetY(void); int GetWidth(void); int GetHeight(void); Sprite* GetSprite(void); protected: bool Activate(bool bActive, int iStateID = 0); bool IsActive(int iStateID = -1, int iStateException = -1); bool m_bActive; int m_iActiveState; int m_iX, m_iY, m_iOffsetX, m_iOffsetY, m_iSuperX, m_iSuperY; int m_iWidth, m_iHeight; float m_fZ; Sprite* m_pSprite; int m_iID; Vector2 ProjectPosition(Vector2 vMousePos, bool bCap=true); //project a given point to object space }; #pragma once #include "EditorButton.h" #include "Timer.h" class EditorScrollBar : public EditorObject { public: EditorScrollBar(void); virtual ~EditorScrollBar(void); void Setup(Sprite* pSprite, Texture* pFrame, int iID, int iX, int iY, float fZ, int iLength, bool bVertical); void SetButtons(EditorButton* pUpperButton, EditorButton* pLowerButton, EditorButton* pMidButton); void SetValues(int iMinVal, int iMaxVal); void SetNowValue(int iNewValue); int GetNowValue(void); void Draw(float fZ); bool Update(void); void UpdateSuper(int iOffX = 0, int iOffY = 0); private: int m_iMinVal,m_iMaxVal,m_iNowVal; Vector2 m_vTemp; Timer m_cTimer; EditorButton* m_pUpperButton, *m_pLowerButton, *m_pMidButton; }; Edited by The King2, 21 August 2012 - 10:28 AM. Posted 21 August 2012 - 11:05 AM I gets all your texture budgets! Posted 21 August 2012 - 11:33 AM What I don't see here in your implementation is a widget hierarchy. The lack of this hierarchy is causing some of the problems you're having here I believe, and it makes you resort to some quite hacky and non OO implementations. Those "super" functions are some very obvious warning signals here -to be honest with you I have no idea what these are supposed to do, but from your description I can pretty much assume they are a hack-, just like that "check" function you have in your EditorObject class. With a hierarchy you define a root widget which has all the widgets in your editor as children. Each of these widgets can have children of themselves as well, and the position of these children now becomes relative to their parents. The absolute position of a widget now becomes: relative position to parent + absolute position of parent. Sticking all of your behavioral code inside an update function of a widget instead of using MVC for example will force you to create a new class which inherits your scrollbar for each use case you might ever have, which will result in a huge amount of redundant code. I already explained this in my previous post. - Violation of the Single Responsibility Principle (SRP). Stick with SRP at all costs and make sure one class always is responsible for doing one and only one task. Returning the widget which the mouse is pointing to is not the responsibility of a widget! - Improper constructor usage. 2-step initialization like you're applying here can be a dangerous practice as your class invariant is violated until you call the setup function in your EditorObject class. You only need to forget to call the setup class once after creating an EditorObject and you get sent straight to undefined-behaviour-land, which is not the happiest of places. Posted 21 August 2012 - 12:26 PM Edited by Radikalizm, 21 August 2012 - 12:29 PM. I gets all your texture budgets! Posted 21 August 2012 - 01:38 PM f you were to add an addChild() method to your EditorObject class which accepts another EditorObject, and if you were to maintain an actual list of children inside an EditorObject you could easily update your entire gui with only a single update call on the root widget. Within each update call in a widget you would traverse the list of children and do an update call on each of them individually, which gives you a nice recursive way of updating the gui. Managing your gui in such a tree structure also makes your gui much easier to traverse from a programmer's point of view, as having access to a parent widget means having access to the entire subtree which that parent is root of. I remain with my statement that using those super-methods is pretty much a hack. Maybe I'm misinterpreting the way you use your update function in your gui elements, if that's the case just let me know. Right now, since I don't see any other way how you're updating your actual logic to manipulate your back-end data (eg. how does your scrollable window know that your scrollbar has been updated?), I'm assuming you're doing this in your update function. If you wanted to do all of this purely with inheritance you'd have to create a button class which would handle this entire process in its update system. Also, if you wanted your button to be able to control and represent multiple sets of data at once you'd have to create a separate case for that as well, whereas MVC allows a single controller to manipulate and a single view to represent/observer multiple models. EditorButton* pButton = m_pToolbar->GetActiveButton(); if(pButton == NULL || !pButton->Pressed() || !pButton->Over(Input::GetMousePos())) return false; switch(pButton->GetID()) { case 0: (*m_ppBrush)->SetErase(); break; case 1: { pButton->Down(); PencilBrush* pPencilBrush = new PencilBrush(**m_ppBrush); delete *m_ppBrush; *m_ppBrush = pPencilBrush; m_pToolbar->GetButton(2)->Up(); m_pToolbar->GetButton(3)->Up(); break; } case 2: { pButton->Down(); RectBrush* pRectBrush = new RectBrush(**m_ppBrush); delete *m_ppBrush; *m_ppBrush = pRectBrush; m_pToolbar->GetButton(1)->Up(); m_pToolbar->GetButton(3)->Up(); break; } case 3: { pButton->Down(); BucketBrush* pBucketBrush = new BucketBrush(**m_ppBrush); delete *m_ppBrush; *m_ppBrush = pBucketBrush; m_pToolbar->GetButton(1)->Up(); m_pToolbar->GetButton(2)->Up(); break; } } Edited by The King2, 21 August 2012 - 01:51 PM. Posted 21 August 2012 - 02:10 PM Say if I where to make my widgets able of registering a controller, to that the button sends the information that it was activated, and let that controller decide how to manipulate the back-end data. My windows knows about it from the return of Update(). If its true, it has been updated, So if m_pScrollbar()->Update() returns true, it calls m_pScrollbar->GetNowValue() to get the actual value and adjusts the content to that. It does that by setting the m_iOffSetX or Y variable, that is used in UpdateSuper() to set the according contents position. I stepped away from this to hard-code the objects and overload the UpdateSuper()-method. This was most definately unevadable due to my design, since without any messaging system, I pretty much depend on specific objects to being certain methods called on directly. I gets all your texture budgets! Posted 21 August 2012 - 02:40 PM That's basically the concept of using a controller yes, the button does not need to know what kind of controller it's maintaining, only that it is a controller, so any type of controller which could control any kind of model could be assigned to this button. In this case a window must explicitly know that it has a scrollbar which is manipulating it, which is not something you want in a flexible gui. What if you wanted to add a button to your window which scrolled down to a certain piece of content? With this method the window object would now also have to poll this button on each update to see whether it was clicked and update itself accordingly. Doesn't sound all too flexible, does it? The same applies for the toolbar example you gave. Adding a button to the toolbar would require you to go in and edit the toolbar code to allow this new button to perform a certain task. With MVC you can add any generic button to any generic toolbar, and you can register a specific controller to that new button which completely defines its behaviour. No need to go in and edit your classes each time you want to add a certain bit of functionality for a specific use case. This is a design flaw, and hardcoding everything in and making these objects which are supposed to be decoupled from one another explicitly know about eachother is not a solution. In the case of a bad design you should modify your design to something that is extensible and which works without hacks instead of adding more hacks to make the original design work. Some form of messaging will be required eventually in a GUI system, so better to design it properly now instead of having to go back and adjust your design later on. MVC can provide a solution here since broadcasting of state changes and events is automatically implied as soon as one occurs. Posted 21 August 2012 - 02:52 PM @CC Ricers: For instance, a clickable menu entry can be an aggregate of a TextEntry and a Button A scrollbar (just the bar itself, not the screen it scrolls) would be a Button and a Draggable entity with vertical/horizontal constraints added to it Thats just how I was planning to handle things, except that my scrollbar still inherits from EditorObject, because, after all, isn't this a "base object" too? This drastically reduces the amount of code needed as well. Maybe I should show you what EditorObject looks like: *snip* So EditorObject describes a general object with variables that apply to every gui element. (position,size, a sprite object). The whole Super-thingy is for traversion, it spares me having to pass the holding objects x/y-coordinates all the time. ProjectPosition() is a helper function that outputs the mouse coordinates relative to the objects position, saves me a lot of math. So I quess everyone would agree that I should at least inherit these classes from that: EditorImage EditorButton If not, why? If yes, why shouldn't I, example given, also inherit the Scrollbar from this? The scrollbar, while being basically a composition of three buttons and a background-image, does have its own coordinates, destinctive size, needs to be drawn in relation to other objects, etc.. so whats exactly wrong about that or, better said: What are the benefits of composition here? What is such a huge improvement from having an extern controller handling the scrollbars usage to just having the Update() method do it? This is what, for example, the inherited scrollbar-class looks like: *snip* Except that Setup() and SetButtons() could/should be moved to the constructor: Again, why would I want to composite instead of inherit here? The scrollbar class uses everything from its super-class, and just extents it. Do I really have such a misunderstanding of OOP-basics or is it some matter of opinion whether you see a scrollbar a base object here? So I know that my EditorWindow->WindowTileset/WindowTilemap-classes are bad and I'll going to replace that with some composited objects here, but I really see to fail the point for such a basic objects as a scrollbar. New game in progress: Project SeedWorld My development blog: Electronic Meteor Posted 21 August 2012 - 02:55 PM Edited by Radikalizm, 21 August 2012 - 03:05 PM. I gets all your texture budgets! Posted 21 August 2012 - 03:42 PM What I don't favor is putting bunch of variables that are sprawling over the place inside the Widget class, when they can be split up and contained in their own classes or structures, which you can then use with more flexibility. For example, width, height and X and Y position can be stored in a Rectangle structure. The extent to how you define the visual appearance is up to you. Do you want the UI system to use one skin, or maybe give the ability to mix several skins, with some taking priority over the "default" skin? Whatever the case may be, this should be separate from the classes that define behavior. Also, you have to see what makes each widget fundamentally unique. What makes a button a button? It's certainly not its size and position because all widgets have those. A button, like all other UI elements, is defined by its behavior. The Button class need not know it's position, just whether it's been clicked on, or not, and if clicked, trigger an event that would be passed up to the UI system to get the proper response. One example of communicating with a controller is letting a widget maintain a list of controllers. When an onClick event occurs (so your button's onClick() method is called) for example you could iterate over your list of controllers and notify each of them that they should perform their designated action. This will automatically start the chain reaction of updating both model and view. Posted 21 August 2012 - 04:13 PM Should I maintain a notify function for all widgets possible actions, like onButtonClick()? I gets all your texture budgets! Posted 21 August 2012 - 04:33 PM class View { public: View(Model* pModel); virtual ~View(void); void OnClick(void); void OnOver(void); void OnRelease(void); void AddChild(Widget* pWidget); void AddController(Controller*); void Update(int x, int y); // traversiallyupdate childs virtual void Draw(void); protected: vector<Controller*> m_vControllers vector<View*> m_vChilds; Model* m_pModel; }; class Controller { public: Controller(Model* pModel); virtual ~Controller(void); virtual void SendMessage(wstring lpString); protected: Model* m_pModel; } class Model { public: Model();//?? virtual ~Model(void); protected: //?? } Edited by The King2, 21 August 2012 - 04:36 PM. Posted 22 August 2012 - 01:38 AM class View { ... void AddController(Controller*); ... }I wouldn't do that, generally the view allows the controller to register "events", the view doesn't know about the controller directly. Well, I think what you want to do is build your own gui framework. This means you build templates for the View. Templates for any controller / model is not a task of the windowing library afaik.Well, I think what you want to do is build your own gui framework. This means you build templates for the View. Templates for any controller / model is not a task of the windowing library afaik. I've got no idea how to design the model in a generic pattern. Really, I can't even come up with any example. How would I design this in a way that I don't have to inherit from this class for every set of data I want to display, and not have to inherit widget accordingly? This would kill the whole purpose, I belive. While I agree that it makes sense to put that in a structure, I don't agree that it gives you more flexibilty. What should be so more flexible about this approach?While I agree that it makes sense to put that in a structure, I don't agree that it gives you more flexibilty. What should be so more flexible about this approach? What I don't favor is putting bunch of variables that are sprawling over the place inside the Widget class, when they can be split up and contained in their own classes or structures, which you can then use with more flexibility Edited by Bluefirehawk, 22 August 2012 - 02:21 AM. Posted 22 August 2012 - 04:43 AM I wouldn't do that, generally the view allows the controller to register "events", the view doesn't know about the controller directly. If possible, use a windowing library, what you are doing here is trying to reinvent the wheel. Well, I think what you want to do is build your own gui framework. This means you build templates for the View. Templates for any controller / model is not a task of the windowing library afaik. This means for the windowing library you need a class design for your gui elements and a messaging system, implementing the MVC pattern is not up to the library. class Model { Model(); virtual ~Model(); protected: int m_X, m_Y, m_Width, m_iHeight; }
https://www.gamedev.net/topic/630007-game-engine-gui-design/
CC-MAIN-2017-04
refinedweb
2,826
56.89
UFDC Home myUFDC Home | Help | RSS <%BANNER%> TABLE OF CONTENTS HIDE Section A: Main Section B: Second Section Section C: Business Section D: Chamber Currents 30,29 Table of Contents Section A: Main page A 1 page A 2 page A 3 page A 4 page A 5 page A 6 page A 7 page A 8 page A 9 page A 10 page A 11 page A 12 Section D: Chamber Currents page D 1 page D 2 page D 3 page D 4 page D 5 page D 6 page D 7 page D 8 page D 9 page D 10 page D 11 page D 12 Full Text EXP 9/1 ;,,, :32 PK YONGE LIB FL GAINESV BFOX 11L 36107 _. ~GAINFSVILLE, FL 326111 WN NEWSPAPER FOR OVER 69 YEARS 69th Year, Number 6 Port St. Joe, FL 3 Sections 36 Pages '." ? ^ ._. \ ,' ^-.[ Co '., yt ou B,-, ' y R .d Cowboys Round Up I1B November 30, 2006 County Jail Operations Revert to County Commission By Marie Logan Star Staff Writer In the county' commission meeting Monday night, Commission chair Carmen McLemore told his fellow commissioners to be "thinking about" the jail, since they would soon be han- dling jail operations. In a letter sent Nov. 17 to each member of the commission, Gulf County Sheriff Dalton Upchurch informed commissioners that he will return the operation of the county jail to the Board of County Commissioners effective Jan. 1. In his letter, Upchurch stated that "with our current budget conditions, the Sheriff's office can no longer extend the courtesy of over- seeing the jail facility." In a cursory discussion of upcoming jail issues Monday night, Commissioner Nathan Peters mentioned dealing with the 12 jail employees, Commissioner Bill Williams spoke of the major costs and lack of resources in terms of deputies to assist with jail administra- tion, and Commissioner Billy Traylor added that it would be the board's "responsibility to see it works in anr efficient manner." The issue of the jail was added to the Dec. 5 special meeting, and McLemore told com- missioners they needed to tour the jail and set guidelines for its operations. The deteriorated conditions at the jail have been a source of major conflict between the (See COUNTY 2A) 6,m. 7 2" .. .. .-. ...,... . OW P; Deteriorated conditions of the county jail are one of the issues the county commission will inherit when jail operations pass to the commission's control January 1. Christmas on the Coast Begins Friday By Despina Williams Star Staff Writer Santa and a surprise grand marshal will highlight Port St. Joe's annual Christmas on the Coast celebration, held this Friday and Saturday. The celebration begins 5:30 p.m. (ET) Friday with a tree lighting ceremony and carol- ing at Frank Pate Park. Food vendors will be on hand selling gumbo and hot chocolate. On Saturday, the events start early, with registration for the Reindeer 5K Run and Fitness Walk beginning at 8 a.m. on the corner of Williams Ave. and Fourth Street. The race starts at 9 a.m. and ends at the same intersection of Williams and Fourth. The flat course is ideal for fast stepping. The first 100 entrants will win long-sleeved shirts, and the fastest finishers will receive cash prizes. The overall male and female run- ners will receive $50 apiece, with additional winners named in 5-year age groups. Registration is $15 early and $20 on race day. Those who prefer sightseeing to running can browse the downtown shops, which will be hosting open houses throughout the two-day celebration. I ( The main event begins at 6 p.m. Saturday, (See CHRISTMAS 2A) Region Poster Child for National Appraisal and Mortgage Fraud By Marie Logan. Star Staff Writer Note: This is thefirst in a series of articles that examine the correlation between high property taxes, fraudulent private property appraisals, and the companion problem of mortgage fraud. The property taxman cometh. The runaway real estate train of 2004- 2005 left large numbers of property owners dancing with glee over record sale prices, and brought unprecedented numbers of developers, speculators, and others to the Forgotten Coast, looking to own, a slice of paradise in. this heretofore little-known area of Florida. But after 24 months of wildly escalating real estate prices, the real estate and construction train derailed in the fall of 2005, and remained so in 2006. Yet property assessments, and consequently property taxes, rose to the point of disbelief in 2004-05 for Gulf County, and in 2006 for Bay County, especially for Mexico Beach, which saw the largest jump in taxable value in Bay County, up 129 percent from 2005. Crippling property taxes are a statewide problem.. According to the FBI,.fraudulent property appraisals and mortgage fraud are a. national problem, particularly in 10 states since 2003.. Florida has made that "top 10" list each year. The idea of inflated property values in this area is not new. Bay County property appraiser Rick Barnett has been quoted in recent months as saying he thinks many Bay County property values are now inflated as much as 40 percent, after years of being undervalued. According .to Barnett, [Bay' County] properties have sold in recent years for more than "double what they are worth," and that the sale prices, even though they are high, determine the property value on that home and homes nearby. Franklin County property appraiser Doris Pendelton lowered her county's .assessments 15 percent across, the board this year, an attempt to reduce.the affected or over-inflated appraisals. She was forced by the state to use the higher assessments for taxing purposes. Yet very few people have picked up on the connection of private appraisal fraud and inflated property taxes. To fully understand the problem, an understanding of appraisals, how they are supposed to be made. what often happens, who is involved, and why bogus appraisals are so dangerous is needed. . Appraisal Basics in Depth What is a real estate, or private property appraisal? A private property appraisal is essentially a comparison of addresses. It is an opinion and state licensed certificaton of value of a described piece of property that must be developed impartially, scientifically and objectively by law, the key words being impartially, scientifically and objectively. " It is supposed to be a detailed report in which private property appraisers analyze comparable sales coupled with information about the property being appraised, the neighborhood and community, and the local and national economy, to support and certify the appraised value. Who performs property appraisals? Licensed independent private property appraisers handle real estate (property) appraisals. Private appraisers can work for anyone who wants a property appraisal. In contrast, real estate agents typically perform a comparative market analysis (CMA) in preparation for a listing by examining sales of properties in the area to arrive at a listing price. The appraisal laws in most states allow real estate agents to perform CMAs without an appraiser's license or certification. The reliability of the CMA depends on the agent's experience and the characteristics of the property. A private property appraisal and a CMA are not the same thing. According to Gloria Salinard, director of the Realtors Association of Franklin and Southern Gulf Counties in Apalachicola, the CMA is not as specific as an appraisal. which is usually done after a property is under contract. "Appraisals can take it one step further and go into greater depth," said Salinard. Realtors collect data from the Multiple Listing Service (MLS) and the property appraiser's office on similar properties as the subject property, said Salinard, and make a comparison of home sales of similar properties in the area to establish a selling price for the (See APPRAISAL BASICS 5A) According to the FBI, fraudulent property appraisals and mortgage fraud are a national problem, particularly in 10 states since 2003. Florida has made that "top 10" list each year. O A Freedom News.paper Business Hours: 8:00 am 5:00 pm ET Real Eilaie Advenising Deadline Thursday 11:00 am ET Display Advertising Deadline Friday 11:00 am ET Classified line-Advertiing Deadline Monday 5:00 pm ET 227-1278 N. vi t School Board ................................ IB Dog Days ...................................... 1C Lister Book................................... 2C Classified Line Ads S Deadline Monday Spm ET 4pm CT t he c:..at 747-5020 Murder Suspect Released ................ 2A Port Closes Deal ............................3B INDEX Opdnons 4 ommfunJillCalendaf --.6..B Lelies lo e Edio .--- 5A Things To Do & See -----B Spos- --- 10 11A Law Enlotemeni ..-.....8B Wealbe[ IIA Sodely News. -2 'B Obiluaiies......--------4B Cburh News ..- ..-..5 ShioolNews- ...- OB Le -- --- -7 Tiddes & Servi(es BC clssledssi ds -....-- ... 910C USPS 518-880 i% %%.eme ra Id coastI'com ~rslf~t~e~ti~B~ As AM I.I.I ... l ... .... FL .. ... No e e 3. 2 6 E h Murder suspect, Esmond, Released By David Angier Florida Freedom Newspapers A Port St. Joe man once charged with first-degree mur- der was released from jail Tuesday after entering into a plea agreement for time served. Joseph Esmond, 27, was indicted in 1999 on charges of first-degree murder and attempted armed robbery. He and an accomplice were accused of stabbing to death Hilton D. Sewell on Oct. 4, 1999, in Gulf County. On Tuesday, Esmond, who spent much of the last seven years in a mental hospital, pleaded no contest to conspir- acy to commit second-degree murder and was sentenced to time served. "He went home today," defense attorney Russ Ramey said after the hearing. "I think we could have prevailed in trial, but we just couldn't pass up that deal." Esmond was charged with killing Sewell during a robbery. His co-defendant, Melissa Ash, was found not guilty by reason of insanity. Her case is up for review Dec. 5 to determine whether she is eligible to be returned to the community. State Attorney spokesman Joe Grammer said Esmond's role in Sewell's killing was minimal. "He went with (Ash) and was on the scene at the time," Grammer said. '"As the evi- dence unfolded in this case, it became clear that Esmond was not involved in the actual killing." Ash, he said, was the kill- er. Grammer said Esmond's mental health issues were a concern in working out a suit- able plea agreement, and in the end Sewell's family approved of the plea. "We felt this was the best resolution," Grammer said. .. For allyour advertising needs... Be Sure to Contactyour Downtown Port St. Joe, Wewahitchka, Cape San Bias and Indian Pass Account Executive Kimberly Pickett 227-7851 135 W. Hwy 98 Port St Joe, Florida: THE arable 129 Commerce Street Apalachicola, Florida The Star Announces Alliance with Monster to Power Online Recruitment in Port St. Joe The Star, a part of Freedom Communications diversified media company, today announced a strategic alliance with Monster, the lead- ing global online career and recruitment resource, to bring industry-leading recruitment services to by November 28, 2006. By partnering with Monster, will provide advertisers with pow- erful recruitment tools that streamline the hiring process and provide access to the world's largest resume data- base ensuring access to top talent nationwide. In addition, will now offer job candidates hundreds of thousands of diversified jobs nationwide with valuable career advice and guidance. This relationship is designed to benefit job seekers and employers alike. Job seek- ers get a complete online solu- tion offering a local focus with industry-leading search and match technology. Consumers will also have quick access to expert advice regarding a range of career-related topics and an array of tools, includ- ing a resume builder and sala- ry center, designed to enhance the search process. Employers benefit from the easy availability of a holis- tic recruitment solution that utilizes print and online adver- tising components. Businesses can also access the industry's leading resume database, which attracts approximately 40,000 new resumes each day from across the country. In addition, the hiring and tal- ent management tools help recruiters and hiring manag- ers save time, allowing them to focus on core operations. Christmas From Page lA with a lighted Christmas parade beginning on Cecil' Costin Blvd. and proceeding north on Reid Ave. Those desiring a snack may purchase food from com- munity and non-profit organi- zations, whose booths will be set up in the empty lot across from City Hall. The parade will be led by a surprise grand marshal well-known in the Gulf County community. Santa will make an appearance at the parade's end, before traveling to Frank Pate Park to greet the young and old alike. The Junior Service League is sponsoring free pictures with Santa, and will also 'be dispensing candy to the little ones. The Kiwanis Club will dis- tribute children's books.- A lighted boat parade will depart from the marina at 7:30 p.m. and journey to the public boat ramp bordering Frank Pate Park. As' of Tuesday, 13 boats had registered, making this year's parade a very special event. First, second and third cash prizes will be awarded for the best decorated floats and boats in the two parades. The Gulf County Chamber of Commerce is sponsoring the event, with additional funding by the Gulf County Tourist Development Council. For more information and additional updates, contact the Chamber at 850-227-1223. County board and the Sheriff's Department for years, with Upchurch telling the commis- sioners early this year that they had been warned multiple times, by him and others, that the jail was in serious trouble. In March, Upchurch gave the commission a 30- day notice that they would. be responsible for the jail. After hurried deliberations, the commissioners decided to "rethink" having the jail in their care, and told Upchurch they did not want it. At a special meeting in March, designed to return the jail to Upchurch's.care, Traylor said he would only vote to do so if the board committed to make all needed repairs and conduct routine inspections every two weeks. At that time the board verbally agreed to Traylor's terms, and the motion .to return the jail to the Sheriff's -Department carried 4-0, with Peters absent. As Upchurch stated in one March meeting with commis- sioners, "I'll tell you what's wrong. It's 20 years of not fix- ing things. It is not my job to maintain your facility. It's my job to administer your facility. I told you that last February." Jail problems include: Crumbling structures, a severely leaking roof and the ensuing problems from that (flooding of the facility, mold, rot); unsanitary inmate facili' ties; plumbing problems; the use of law enforcement dollars to balance the jail budget; lack of transport vehicles in the corrections department; and lack of space for personnel and secure record storage. In other business: County administrator Don Butler reported a cost of approximately $85,56.0 to complete the work site, exclud- ing paving, at the Wewahitchka From Page 14 Health Department cur- rently under construction. Commissioners proposed to take the money for the work * out of upcoming road bond funds. Commissioner Bill Williams amended the motion by adding the recommendA- tion that the additional costs of $85,000-$100,000 for paving be taken from the accumulat- ed half-cent sales tax fund that Gulf County residents have been paying for county health facilities improvements. The amended motion passed unanimously. Williams mentioned that Bay County commission- ers had just voted 4-1 to dis- solve their contract with the Northwest Regional Library System, and that it may qr may not have repercussions for the Gulf County library, specifically in terms of techni- -cal training for librarians. - The board asked Butler.to gather information and report back to them as soon as pos- sible. *, County grant writer Loretta Costin, also a mem- ber of the county's interagen- cy task force, reminded the board of the urgency of signing a memorandum coming their way.. The memo refers to the proposed catalyst site to be operated and marketed world- wide by Enterprise Florida. Eight Northwqst Florida coun- ties, including Gulf, are vying for the site, which is worth $15 million. The upcoming Port of Port St. Joe is the location Gulf County will be offering. I. Neubauer Real Estate, Inc. ER A Always There For You. Each Office naependently Owned and Operated 9446 Hw 98 S599. ; 'i.i BEA(CON HILL GULF Bf\ KIE\\ [-0\%N HlON 3BR.2BA dir d across s froii altr o ith dedicated beach. Family room.nell- equipped eat-in-kierhrn and laundr' room. Double slidin gla~. don on both lt els .'p;ilioand dEck. cr.rt nd S porchl and workshop #111342 102 Coral Dr. $374.000 2 BLOCKS FROM THE BE\CH IN ST JOE BEACH 3BR/2BA homc fe.- tures a living/dining combination, fireplace, wtll-equipped kitchen and master bedtuom rn prarte bath und walk-in leli attached garage. open deck, Iandscaped yard and home warrant. #2011772 Ill 37th Street M44 S315;0001) STEPS AWAY FRO\I MEXICO BEACH AND PIER 2BR/1.5BA fully furnished tpwnhouse w/large sunken family room spa- cious cat-in-kifchen and large deck in back yard. Perfect as weekend get-a-way or as investment. #109522 H420 Reid Ave.. Port St Jo hi.tp.lfiWW.eAI ol .coM (850) 229-9 emai roll C1 i ellmIf0da.cO m I.Toll Fre1%04 118 Heritage Lane $399.U00 -BR-AND NE\\ PORT ST JOE HOME 4BRf3BA fea- turing hardwood floors. ceramic tile, living, dining, breakfast and laundry room,, kitchen u/island. Twio-car garage, covered patio, covered porch, sprinkler s siem and more. #202008 FETUE OM 2007 Garrison Ate. S325.00l0 -CUlSTOM BUILT PORT ST JOF BF .%LT'N - AVI.-awfb.- 3BR/2.5BA has living and dining *rms, plii bedroom fluorplan. ga fielc.cro%%n molding. 'aultcd eLilingi and %%Lll-equipped kivcherA w~breakia~ bar. 2-car garage. co%;' er-ed porch, prihaci fenced 'ard =~~and sprinkler syer.4202261" $75X--&D~oCNiCmdan~lty .#2097,#20098'., *9w-- etmfit v4RBA #201261 K '$42C41eawf HllneamW#201890. 00D-BeafW (titGubd&MIskn#110700'- $245,000-Sp=MmHbon~bmfua'1i-3BM2A.#20061 :$2M,00-W~fsa~dgDiaoioBeh--2R/BA-#1O74:, $115,0M-TaYaicuf~sn~Rnt&Joe -#2MVWl02001-,. 1-888-591-8751 1r,'E 1 k'I l .nI .Ju.i .V a tri '. ~I~a.'1 't-,,.n w'"d "oft r-WVA~. p$fy 263v Ilrttinwit F ,We. Cuv" a'uft9Lfae iof LaWt Model-Cars, Van, SUIPs A Trucks! BUY NOW Before prices begin to-rise. Beautiful, livable homes at very affordable prices I - EW - r II I ,I 11;L FEATI I . 1) % T11~~- -4~1 ~1 ---------~-CC----------~-Y?-----~----~~~ Established 7937 -SrigGl onyadsronigaesfr6 er 2A he ta, PrtSt.Jo, F -Thursday, November 30, 2006 Port Authority Closes Land Deal By Tim Croft Star News Editor More than three years of planting and nurturing finally bore fruit for the Port St. Joe Port Authority on Tuesday afternoon. In a process that could be seen as the climax of more than three years of visioning and negotiations, Port Authority board mem- bers assigned their John Hancocks to a mortgage for a 10-acre parcel of land and a $4 million-plus line of credit from Capital City Bank to purchase that land from The St. Joe Company. Additionally, the Port -i 4- -- .4-' ~ Authority, during a special meeting, finalized paper- work for tax-exempt sta- tus. In signing on the dotted line, the board took a giant leap forward, in its quest to create, a deepwater port - one iof just 14 in Florida - in a city which derives its very name from the con- cept. "This is an extremely important step toward cre- ating an operational port in the City of Port St. Joe," said board chairman Allen Cox, and with it, he added, a boost for economic devel- opment in the county and the creation of many high- paying jobs. Cox noted that the S --3 IL .c x Port Authority has already received notification through the Florida Ports Authority that it is eligible for funding for site prepa- ration, bulkhead engineer- ing and dredging of the shipping channel. The St. Joe Company has also pledged $1 mil- lion to assist in the requi- site permitting needed to accomplish that prepara- tion and dredging. Within the next year, .Cox added, the physical presence of the port should be clear and the first ships could be arriving within two years. Another ace in the Port Authority's pocket is a coop- erative agreement finalized I I . i ', . Tim Croft The tajr Clay Smallwood of the St. Joe Company and Allen Cox, Chairman of the board of the Port Authority seal the deal. earlier this year with the Port of Panama City to act as a satellite or sister port to that steadily expanding facility. Given changes in ship- ping demand and the avail- ability of facilities since a rash of hurricanes devas- tated the Gulf Coast last year, Port Panama City has seen its business explode. The Port of Port St. Joe hopes to capture some frag- ments from that explosion, developing itself into a regional port for intermod- al transportation by high- way, railway and waterway - activity from Washington County south. "We're very encouraged that we'll be moving for- ward quicker through that agreement," Cox said, noting that the land purchase provided the Port Authority with crucial land, highway and water access from which to grow. The agreement finalized on Tuesday was for one of two par- cels the Port Authority and St. Joe had identi- fied in the port's updat- ed master plan as most suitable to expand the physical imprint of the port. Parcel B, the one acquired on Tuesday, was the more attractive in the short-term, for .\ a variety of reasons. It was the less expensive , of the two parcels, was contiguous to existing , Port Authority land and had frontage on the Gulf County Canal. The parcel, on the east side of the canal, is across from Raffield and Woods Fisheries and bounded by U.S. 98, Industrial Road, the sediment pond at the city wastewater treatment plant and the canal. The acquisition of the property provides an open- ing for grants and govern- ment dollars, such as those flowing through the Florida Ports Authority. Tuesday's agreement was an end to three years of visioning among the City of Port St. Joe, Port Authority and St. Joe Company and a begin- ning: to the creation of a operational port. "I thank the members of the Port Authority, the city and St. Joe for the work they have done con- tinuing the move forward to expand our physical foot- print," Cox said. Clay Smallwood, presi- dent of the Gulf region for The St. Joe Company, expressed excitement about the deal, long in coming. "This is a big day for us and for the town," Smallwood said. "This is the culmination of the visioning process and the first step for the port. We're excited." NEW zoneF oRD 2250 gBHRA NDEW 2U06 N MnNEWI N 2007 faRD KING RANCH FORD F150 .. RANGER SUPER DUTY SUPERCHEW4F4 SPORT CREW CAB 4X4 ML '--! MRSP $51,095 'f- RSP $39,530 RS $17,990 S "l4 ':"''" ': i... T 000 .. :,- 5.500 ,$. ...$. 2 1 COO You Pay You Pal 'You Pay ir--,. .. I, -49 fullhouse bundle is available to residential customers for a limited time and subject to change without notification. Eligible customers must sign up for, or already have Home Phone, No Limits or Clear Choice plan to participate in the fullhouse offer. Home Phone: Long distance minutes are for voice service only and apply, to domestic United States (excluding Alaska and Hawaii) and Canada. Additional minutes of long distance use beyond the allotted minutes of your plan are billed at 10 cents per minute. High Speed Internet Service: Free installation. Subscription to stan- dard high speed Internet required. Additional terms and conditions may apply. DIRECTV Service: DIRECTV service provided by DIRECTV and sub- ject to credit approval. PROGRAMMING OFFERS& (Offers end 2/5/07) IF, AFTER 12 CONSECUTIVE MONTHS, CUSTOMER DOES NOT CONTACT DIRECT TO CHANGE SERVICE, THEN ALL PROGRAMMING TO WHICH CUSTOMER IS SUBSCRIBING WILL AUTOMATICAL- . LY CONTINUE ON THE 13TH MONTH AT THE THEN-PREVAILING RATES, INCLUDING THE $4.99/MO. LEASE FEE FOR THE 2ND AND EACH ADDITIONAL RECEIVER. To qualify for the DVR service or DIRECTV HD package discount, customer must lease an advanced receiver. Offers may not be combined. In certain markets, programming/pricing may vary, P& s ,ae ,.,.:.r. ji Ji, -i ,r ..j, L 'iELC T .. System has a feature that restricts access to channels. Visit directv.com or call 1-800-DIRECTV for details. Programming, pricing, terms and conditions subject, to change at any time. Pricing residential. Taxes not included. Receipt of DIRECTV or.T..ur-r.;n. .b...It.,: i JIRE'CT' C, .- ,jJ,..r Agreement: copy provided at directv.com/legal and in first bill. ,42006 DIRECTV. Inc. DIRECTV, the C, .i..'.- D- -. l.:., .. -. TCT^al. Cm-.ir'E c registered trade- marks of DIRECTV, Inc. All other trademarks and service marks are property of their respective owners. G2006 GTC Communications, Inc., 502 Cecil G. Costin Sr Blvd., Port St. Joe, Florida 32456. S. a _ TheStr, or St Je, L ThrsayNoembr 0, 00 -3A Establish 797 -Serving Gulf county and surrounding areas for 69 years ~LIF~ i i. I 4A The Star, Port St. Joe, FL Thursday, November 30, 2006 Call We have long supported the creation of an operational port along the Port St. Joe waterfront, so we applaud the closing on Tuesday of a land deal between the Port Authority and The St. Joe Company. Coming after years of visioning and negotiations between the city, Port Authority and St. Joe, the deal is a culmination of sorts for a process which has been often maddeningly slow to come to fruition. The tough work, though, is about to begin and that is the creation of a port facility. The importance of that venture can not be overstated. For much of this decade the county has seen skyrocketing land prices serve as its economic engine, an engine that, fortunately or unfortunately, depending on your position in the equation, has not provided forward momentum for the majority of residents. Too many are buckling under property taxes in the stratosphere while the real estate market softens beneath them. Too many were left behind as the speculators and land-flippers pocketed their dough and waltzed away. Leaving in their wake families struggling to get by even on two and three incomes, folks on fixed incomes fiscally trapped within homes they can no longer afford, home prices out of reach of the working class in the county and an economy which has all but imploded because of the fluidity of real estate. What that real estate -roller coaster has underscored, in turn, is that the fuel that a mill once provided must arise in' order for most to be lifted up; to keep children taught in good schools from leaving the community, to provide jobs which translate into living wages and, ultimately, the maintenance of community roots. In short, the words must turn into action. This is a county-wide' issue, from the discussions about expanding the boundaries of the Port St. Joe Redevelopment Agency to the affordable housing coalition to the interagency council advising the County Commission. There is no shortage of good ideas, folks willing to volunteer time and energy and meetings and certainly no shortage of, will but substantive action seems to require a leap across a chasm wider than the Grand Canyon. to k 1Xv STAR YOUR 1OMEilTO.VAEI'SPAP'ER FOR OVER 69 YE.RS Established 1937 Serving Gulf county and surrounding areas for 69 years K Action And too often that leap has been weighed down by turf tussles, egos, competing agendas, not to mention the wherewithal from those who could provide the spring. A new hospital and its high-paying and plentiful jobs, a community land trust that would ensure affordable housing in perpetuity, the elimination of railroad tracks, both real The tough work, though, is about to begin and that is the creation of a port facility. The importance of that venture can not be overstated. and symbolic, which divide communities and prospects for upward mobility, have all been much parsed in the past few years with little forward motion. Likewise, the port, which has been years in discussion and debate, years in the rendering on paper by planners, but to date little more than a tantalizing possibility lacking real. form. And now the county has the opportunity to turn that prospective port into a "catalyst" for county, and regional development, a magnet for state funding aimed at helping a county deemed one of critical economic concern in Flprida to turn a corner, stand on its feet. As detailed in this paper a few weeks ago, the county is among eight in the region competing to be selected as the site of a pilot program to kick start the regional economy, the prospective port combined with existing home-building component manufacturing by Taunton Industries providing a platform. For the county to have any chance at selection for that pilot project, and the state grant funding which would accompany it, the Port Authority must move quickly beyond the glee of finally having land to creating the facility and securing promised customers. And what will be critical are more public/ private partnerships such as the one ultimately brokered between the Port Authority and The St. Joe Company, between Sacred Heart, the county Health Department and The St. Joe Company. As is evidenced again and again from the flip-flops over county-wide voting and election cycles to the hot potato game surrounding the county jail local government's most appropriate role, a fictional role at this time, seems to be to lend consistent support and stay the heck out of the way. Commissioners have. proven adept at creating parks and deluding voters into casting ballots against their own interests if there is a better case study against single-member districts than what two decades of leadership have produced in North Port St. Joe, let us know but the long-term vision thing seems to plum elude them. At the same time, the majority of residents in the county can't afford much more talk while the few await another rise in .the real estate roller coaster to take substantive action, or,, more pointedly, to use the slowdown, as an excuse for the status quo. Talk, as has been demonstrated again and again in the past few years in the county, is best swallowed with a boulder of salt. Residents are hungry, downright starving, to see at least a portion of all those words and promises come to fruition, to see action attached to talk about health care, affordable housing and high-paying jobs. \Vith the closing of its land deal on Tuesday, the Port Authority is presented with a golden opportunity to take a lead role in doing just that. I've Got To Graduate Sometime! I need to get out of this coaching business. I'm only in it for the money. And I don't really know all that much about football anyway..... I know Pat Bailey stopped in the hole once back -when he was in the ninth grade. We had a polite discussion on pulling guards NOT STOPPING in the hole! I did most of the talking. Pat was pretty quiet back in those days. His twin brother, Byron, talked a lot more. I played baseball with Mike Byrd's grandfa- ther. That makes Mike awful young....or me very, very old. Mike has a smile as big as all outdoors. And, pound for pound, he's about as tough as they come. Ashley Davis shook my hand at every prac- tice and before every game for four years. And he acted like he was truly glad to see me. And he appreciated that line about "wishing it was three o'clock and we were just getting here!" Andy Canington was near 'bout as quiet as, Patrick. And he can take a lick, I guarantee you that. Coast showed up a couple of years ago from California. I asked him about the surf and why his hair wasn't long and shaggy. Warren Floyd stopped telling me how "we" ought to be doing it about halfway through his junior year. I was eternally grateful. Brian missed a couple of seasons and that sure hurt. Randy Myricks was in the same boat. I would have liked to have had those guys around for the last four years. Mike Quinn would sulk, when I got on him about not running hard. I loved it! His dad did exactly the same thing when he played. And Austin Peltier was always good for a little base- ball talk between kicks..... Seniors There is something very special 'about them! We had eleven on this year's team. Five of them. Pup, Honk, Pat, Sapp and Mudcat, have been together for all four high school years. That is fairly significant to me---it was exactly four, years ago that Coach Palmer called me back into active duty. I figure we all experienced a few moments of trepidation when we first stepped on that practice field in August of 2003. It sure was hot. ST Newspaper Association HUNKER DOMW )IJWITH KES Kesley Colbert Contributing Writer 'Course, I was just standing there. I didn't have' to do the running. Or the blocking. Or the tack- ling. Or. the bleeding. Or the moaning. I admired the ones that did. And I was in awe the next.day when they came back for more! "Coach,. did they have those leather helmets back when you played?" Everybody wants to be a comedian. "No, Sapp, I'm not that old!" Pup would ask about his older brother who played on a good football team here in 1984. "He wasn't afraid like you are. And he was much prettier!" I can be a comedian too! Mike would frown his face up in thought when I'd give him the choice between Tennessee ,and Florida. "I'll take Florida and ten." I reckon he would the young rascal! We'd bet a meal or two on the college gaines as the season pro- gressed. 'Course, it wasn't much of a bet and we never kept up with who was, winning..... only one of us was sucker enough to pay for dinner anyway. "Coast, what is the Joaquin Valley like? And have you ever been swimming in the Kern River?" Terry's eyes would get big. He couldn't believe I could have a thought that didn't revolve around him blocking the back side linebacker Warren and I talked about John Milton. Longfellow's "The Children's Hour". And a rather obscure poem by William Ernest Henley. ' Pelt liked the Cardinals o. k. And he was proud for ,me when they won the World Series. But I suspect, deep down, he's a Braves fan at heart. POSTMASTER: . Send Address Change to: THE STAR Post Office Box 308 Port St. Joe, FL 32457-0308 Phone (850) 227-1278 PERIODICAL RATE POSTAGE PAID AT PORT ST. JOE, FL 32457 WEEKLY PUBLISHING As Pat grew into a football player.. ...he still didn't say much. Byron had to do the talking for both of them. He didn't do the eating for both! Pat would come over to the house as a sophomore and eat pizza or lasagna or Mississippi mud cake like there wasn't going to be no tomorrow. Warren would bring the Gatorade. Cat would show up. "Cat, this meal is for the "0" line." "Coach, I've got to check on my boys." When these guys first started coming to the house, they would reach out to hug and thank Cathy for the meal. The last couple of years they've had to reach down to her.... You think I'm the only one who is going to miss this group. And listen to me, in between the. pranks, -the eating, group therapy, the roaring laughter and the mass mayhem these guys played foot- ball. Boy howdy, did they ever! If Coach Palmer could draw it up in the dirt, they could make it work on Friday night. When Coach Gannon came out and said this is the way we're going to stop'em....they put their hunkering-down caps, on! When the other coaches barked and yelled and screamed and ranted they trudged on with the heart of a champion..... I have stood by and watched this senior class unfurl and stretch and reach for four years now. You have honored me, guys, -by letting me hang around. I thank you from the bottom of my heart. These bright young seniors will move on to bigger and better things. I 'will remember the pizza, a pat on the shoulder, a smile after a big hit, 30 wedge, some bonding time in the chutes, a rowdy meal at Peppers, a bad day on the sled, a quiet talk walking off the practice field and a heartfelt "thanks coach" long after the cheering stops.... You see now why I've got to get out. It gets harder each year to let them go. A lot of folks will proudly look back on the wins, the rural state trophies, the state cham- pionship and all the football trappings.... I am fortunate to have so much more....so much more.... Respectfully, Coach. K I' -~aV Friedman Gracious, Tenacious Commentary by TIBOR R. MACHAN Freedom News Service When I began my involvement with the libertarian movement in America in the early 1960s, I was brought in by reading the novelist- philosopher Ayn Rand, but quickly discovered there were several others who had been making significant contributions to the study of the free society. One of them was the economist Milton Friedman, who died earlier this month at age 94 and was eulogized by so many as one of the most influential thinkers of the 20th century. He was, among other things, a founder of the Mt. Pelerin Society, the international association of classical liberal intellectuals founded back in the late 1940s as a rather humble antidote to the massive left- wing academic, intellectual and literary movement in the West. In the course of his long life, I had the privilege of meeting and talking a number of times with "Uncle Milty." Permit me a few reminiscences. In the early 1970s, I helped found Reason Magazine as a monthly publication of accessible yet in-depth analyses of society from the libertarian perspective. One of the features of the magazine was to be lengthy, probing interviews with important thinkers. And so, in February, 1974, I drove to Chicago to meet and interview for the magazine Milton Friedman at his apartment. I had along professor Ralph Raico and we were joined also by one of Friedman's students, Joe Cobb. The interview went on for several hours, When we finished we were exhausted from an exhilarating exchange with an intellectually agile and superbly educated-scholar. In the course of the interview we explored various approaches that one might take to understanding human affairs and ,the best economic system that would serve people anywhere and everywhere. While in broad agreement, there were matters on which there were some differences among us. I especially had an intense exchange with Friedman on the topic of whether it is possible for people to know what is right or wrong ethical conduct. Friedman made this memorable point: ." Friedman, of course, also. held that no one could know when another sinned or did something morally wrong. I disagreed, and we went a few rounds before moving on to other topics. Over the years that i have taught and written quite extensively on the subject of business ethics. I have always presented my students with one of Friedman's widely reprinted essays from 1961; - from The New York Times Magazine, addressing the topic of corporate moral responsibility.-His essay put on record one of the most uncompromising defenses of economic. liberty, rejecting the notion popularized by Ralph Nader and John Kenneth Galbraith, among others, that business corporations, must serve various social purposes and not the goals of those who own them. Friedman held that managers must serve no other goals but those the owners designate which is mostly to pursue the prosperity of the enterprise, or profit - and to do otherwise is to betray a trust the owners extend to managers who voluntarily come to work for them. (Friedman told me later that this essay of his brought him more royalties that any other piece he wrote in his long career.) For all our disagreements, for some reason Friedman still seemed. to find some of my contributions to the .struggle against statism worthwhile. In time he and I would exchange views, in person or by mail or at some conference. At one of the latter, which he himself directed at the Silverado Ranch in Napa Valley, Calif., we spent three intense days discussing numerous aspects of the free society. We also revisited our earlier debate on ethics, and things become quite agitated when I once again argued that moral knowledge is possible to human beings, and he disagreed, calling this a view that lacks humility. When I noted that his claim was itself pregnant with moral overtones, something of a mini-volcanic eruption occurred. But very soon after the conference I received a copy of the Hungarian translation of one of his books, on price theory, with a wonderful note from him saying that ,despite our differences, what matters most is to keep up the good fight. What all my encounters with Friedman taught me with considerable poignancy is how important ,it is. to keep disputes civilized, how to keep one's emotions in check as one examines even the most emotional topics in human affairs. In all his writing and public appearances, he always displayed exemplary conduct, the kind that too many who take part in public disputation nowadays seem to have cast aside in favor of character assassination, speculation about motivation, and imputation of Ill wifi. When Friedman produced his PBS lecture series, "Free. to Choose" (1980), by the way, something important emerged in how the design of the show compared with the series by Galbraith, "Age of Uncertainty" (1977). Both programs focused on economics and both prominently featured the views of their hosts. However, whereas Friedman ended each installment with a half hour of debate, inviting several adversaries to challenge him, leaving the resolution of the disputes ultimately to the audience, Galbraith pointedly did not and closed with yet another reiteration of his position. I do not believe too many public intellectuals and academics can reach the level of decency attained by Dr. Milton Friedman. Luckily for us he left a large paper and media- trail and millions of people here and abroad will be able to learn from it and maybe improve the quality of intellectual life everywhere. I I_ SITUIl 1 970/ds u n e f -or 6 ears The Star, Pr S.JeF Th da, o mbi Appraisal Basics property. "It doesn't happen often at all that CMAs and appraisals are very different," said Salinard. "I have not seen many cases where appraisals are that far off from CMAs." What is the role of an independent private property appraiser? The role of any private property appraiser is to provide impartial and unbiased opinions about the value of real property that are developed in conformance with the To en U n i f o r m the value Standards of Professional audited h Appraisal to whethi Practice rates. (USPAP). When appraising a building, the independent private property appraiser 'is supposed to look at the house being appraised as if the house were empty, without the current owner's furniture and decor influencing the appraiser's judgment. When appraising vacant land, the appraiser applies a similar set of unbiased criteria to the land to reach, an objective conclusion. According to the Uniform Residential Appraisal Report, in. defining. the scope of work for an appraisal, states that a opinions, and conclus this appraisal report." On the report Appraiser's Certi states, among other th that the aj developed his/her of market value thro sales comparison ap using adequate comparable; that he/she and used comparab that were locaa' physically, and fun( - From Page 1A analysis, can be substantiated. This sions in is particularly true in terms of comparable sales and the rt, the resulting price placed on the fiction appraised property. lings: appraiser What is the difference opinion between private property ugh the appraisers and county )proach, property appraisers? market Private property selected appraisers and county le sales property appraisers are not tionally, the same. ctionally An independent private sure that the property appraiser is properly a of property, the property appraiser's assessme by the State Department of Revenue (DOR) with er the assessed values reflect values at current the most similar to the subject property;" that he/she verified "from a disinterested source" all information in the report provided by anyone with a financial interest in the sale or financing of the property; that the appraisal and subsequent compensation were not based in any way on a predetermined value or the approval of a pending mortgage loan application in other words, the appraiser was not told to "hit the numbers" in order to get paid for the appraisal or to receive future work from the lender. By signing the Uniform Residential Appraisal Report, the appraiser certifies, by law and under oath, that he or she completed the appraisal to the letter of the requirements, and that all the statements and figures are true and Florida Appraisal Calendar The Florida Property Appraisal. March 1 This is the deadline for filing Homestead Exemption and Agricultural Classification for the ,current tax year. April 1 This is the deadline for filing Tangible Personal Property returns with the Property Appraiser's .Office. On or about July 1 This if your disagreement concerning value cannot be resolved with the Property Appraiser's Office. On/about November .1 the mailing date when the tax collector mails tax bills to property owners. property business in either appraiser is a person employed the government, or private sector, who determines the value of real property for a specified purpose. A county property appraiser is a government official elected by voters. The county property appraiser does not create value; People create value by buying and selling real estate in the open market place. The property appraiser is responsible for studying these' transactions, interpreting the market, and appraising each 'property accordingly for tax purposes. Each county's taxing authorities (such as the school board) use the county property appraiser's appraisals as a base .for setting the county millage rate. According to information on the Bay County Property Appraiser's website '(www. public net hay-real), the county property appraiser is responsible for locating, identifying. and fairly.valuing all real and personal property in the county for tax-purposes. SDetermining lair and equitable Values is the only role this office performs ui the taxing process. The property appraiser also tracks ownership changes. maintains maps of parcel boundaries, keeps descriptions of buildings and. property characteristics up to date. accepts and approves applications from individuals eligible for exemptions and other forms of property tax relief, and analyzes trends in sales prices, construction costs, and rents. to best estimate the value of all assessable proper ty. At least once every five years a county property appraiser is required by Florida law to visit and inspect each property. However, individual property values may be adjusted between visits in light of sales activity or other factors affectmg real estate' values ui neighborhoods. Each transaction must be checked to guarantee it was an arms-length transaction, meaning that a willing seller sold to a willmig buyer without any undue pressure or special incentives (such as family relationships), and that the property was on the market for "neither an excessive nor short period of time." Once this determination is made by the county property appraiser's office, that office& determines the value: of the property from sales of comparable properties.. This is the sales comparison, or market, approach to valuation. To ensure that the property appraiser is properly assessing the value of property, the property appraiser's assessment roll is audited by the Florida Department of Revenue (DOR) with respect to whether the assessed values reflect values at current market rates. The same roll is also audited to ensure that there is equity in the values established, such as like properties being similarly valued. When the ratio of level of assessment to actual sales falls below the state required level, the property appraiser must adjust the assessed value or the state DOR will not approve the assessment roll. Therefore, value changes from year to year because the market place is dynamic, causing the values ofproperties to change, which the property appraiser must account for every year, as of Jan. 1. If the assessment roll is not approved by the state DOR, taxing authorities c a n n o t proceed with ssessing their annual nt roll is budgets. The role i respect of setting the it market amount of taxes to be paid, as a result of the |appraised value of a property, rests with the various taxing authorities in each county, including the county commission, school board, local municipalities, port authorities, parks and recreation departments, etc. These taxing authorities use the property appraiser's appraisals as a base for setting the millage rate. The value of real estate fluctuates because of many factors. Generally, growth of population and development drive values upward in most areas. Factors influencing value include property use, the size and condition of improvements on the site, and the local real estate market. The Florida Constitution requires Florida counties to assess, property based on its market value. Market value is the typical price a willing buyer would pay to a willing seller. In addition to the market approach (sales of similar, properties), two other minethods are used to assess property; the cost ;approach and the income approach. The cost approach is based on how much it would cost today to build a replacement structure on a parcel. If the property is not new, the appraiser must also estimate how much value the building has lost over time (depreciation). The appraiser must also estimate the value of the land without buildings or any improvements. The income approach is typically applied to income producing 'commercial, properties. It requires a study of how much revenue the property would generate if it were rented for various businesses. The \ appraiser must consider operating expenses, taxes, insurance, maintenance costs, and the return (profit) most people would expect for that type of property. In estimating value for any property, Florida Statutes 193.011 requires that the property appraiser consider eight factors connected to the property: 1. The present cash value 2. The highest and best use 3. The location 4. The quantity or size 5. The cost 6. The condition 7. The income 8. The net proceeds of the sale of the property What qualifications must appraisers private and public have?' All states are required to conform to the licensing and certification requirements established by the Appraisal Foundation, a Congressionally- approved organization dedicated to this purpose. The Appraisal Foundation requires that .appraisers pass a Foundation-approved state examination, as well as meet education and experience (See APPRAISAL BASICS 6A) Florida Property Tax Definitions (source: MyFlorida.com) Ad valorem tax = a tax based upon the assessed value of property The lerm "property tax' may be used interchangeable with the term "ad valorem tax " Ad valorem tax roll = the roll prepared by the property appraiser and certified to the tax collector for collection Assessed value of property = an annual determination of the just or fair market value of an item or property, or the value of the homeslead property as limited pursuant to s.4tc), Art VII of the State Constitution or. if a property is assessed solely on the basis of character or use or at a specified percentage of its value, pursuant to s 41a) or kb) Art VII of the State Constitution its classified use value or fractional value. County property appraiser = = the county officer charged with the collection of ad valorem taxes levied by the county, the school board, any special taxing districts within the county, and all municipalities within the county. Mill = 1/1.000 of a United States dollar Procedure = The [county] property appraiser is the elected constitutional officer responsible for determining and listing the value of all property in each count six months is presumed to be used for commercial purposes. Real property = means land. buildings, fixtures, and all other improvements to land. The term "land," "real estate," "realty," and "real property" may be used interchangeably. Real property includes all other permanent improvements on the land and is broadly classified, based on land use, as follows: a. Single family and mulli Imill = the assessed value of property minus the amount of any applicable exemption provided under s.3 or s.6, Art VII of the State Constitution and chapter 196. Tax certificate = = the tax bill sent to taxpayers for payment of any taxes or special assessments collected pursuant to this chapter, or the bill sehnt to taxpayers for payment of the total of ad valorem taxes and non-ad valorem assessments collected pursuant to s. 197.3632. Tax millage rate = is set by the taxing authority for the governmental unit within which the property is located. The Florida Constitution directly authorizes counties, school districts, and municipalities to levy ad valorem taxes. It also provides that special districts may be created and authorized by.law to levy ad valorem taxes. The total tax rate is the combined tax rates (millages) of all taxing authorities having jurisdiction over property in the county. That part of the rate for general county operations and maintenance is constitutionally limited to a maximum of 10 mills and is set by the county commissioners. The remainder of the county tax rate consists of various referendum-approved debt service millage for bonds and millage required by state law. Also, school districts and municipalities are limited to a maximum of 10 village applicable to the particular property. The tax bill also includes the related taxes due for all the taxing authorities having jurisdiction over the property. Tax receipt = the paid tax notice. Tax rolls, assessment rolls = synonymous phrases meaning the rolls prepared by the property appraiser pursuant to chapter 193 and certified pursuant to s.193.122. Taxpayer = the person or other legal entity in whose name property is assessed, including an agent of a timeshare period titleholder. rP-"i~lgra~llPI~ll111~1 TheSta, ortSt Jo, F -Thusdy, ovebe 30 206 S Established 7937 Servinq Gulf county and surrounding areas for 69 years L I um Tke 3Ta-, Pr+ TOTInU FL Th,,rIdnv Nove 3 0t s 9r G o a r d r r a Appraisal Basics requirements. The education requirements include a course and examination on the Uniform Standards of Professional Appraisal Practice (USPAP), set forth by the Appraisal Foundation. At minimum, all states require appraisers to be state licensed or certified in order to provide appraisals to federally regulated lenders. A federal law requires that any appraiser involved in a federally-related transaction with aloan amount of $250,000 or more must have a state- issued license or certification. Although federal standards do not require an appraisal license for those appraisers valuing real property with loan amounts of less than $250,000, many states require any practicing appraiser to obtain a license or certification, regardless of transaction value. In addition, many states have different, more stringent requirements for licensing than the Appraisal Foundation. What are appraisal licensing requirements in Florida? According to the Division of Real Estate at www. MvFlorida.com, Florida - From Page 5A licensing requirements for appraisers are: 1. An applicant must be at least 18 years old; 2. Hold a high school diploma; 3. Fulfill the requirements for each of the designated levels of appraiser, which are: Registered Trainee Appraiser successful completion of 100 classroom hours of Board-approved courses covering the topics Gulf Coast Medical Center Primary Care in Port St. Joe ,..a... .. .F -. "... 5T..._ - p \' IN I '1 .I fHE ALTH, More DOCTORS. More Hours. Gulf Coast Medical Center Primary Care in Port St. Joe welcomes Gulf County native Kimberly Cooper-Dunn, MD. Dr. Cooper-Dunn is now seeing patients. Our new office hours are 8:00 a.m. 5:00 p.m. Monday through Friday. For an appointment, call 229-8288. We accept all insurance. Walk-ins welcome., / Kimberly Cooper-Dunn. MDN / -. Pre-Kindergarten: Faith (Chririan Schoi lI / / Elementary: Port Si. lie Elemen[;ir School ,- / l Junior High School: Port >. Ioe Middle School /- High School: ladies Rickards Hiigh ctihoul, Medical School: NMorehouie School ol Mediine --: Residenq: fallaha'.aee Memorial H-Ipial "" .Faium\ Praciice Residenc% Pro rain N o. 300 Long Avenue Port St.Joe. FL 32456 (850)229-8288 Considering Eyelid Surgery? required by the Florida Real Estate Appraisal Board in subjects related to real estate appraisal, plus electronic fingerprinting; Certified Residential Appraiser successful completion of 120 classroom hours of Board-approved courses, plus pass the Florida Certified Residential Appraiser examination with a grade of at least 75, plus provide evidence of 2,500 hours of real property appraisal experience obtained over a 24- month period in real property appraisal by furnishing, under oath, a detailed statement of the experience for each year of experienced claimed. The experienced claimed must have been acquired in no less than 24 months. Upon request, the applicant must provide the appraisal board, for its examination, copies of appraisal reports to support the claim for experience. Certified General Appraiser successful completion of 180 classroom hours of Board-approved courses, plus pass the Florida Certified General Appraiser Examination with a grade of at least 75, plus provide evidence of 3,000 hours or real property appraisal experience obtained over a 30- month period in real property appraisal by furnishing, under oath, a detailed statement of the experience for each year of experience claimed. The experience claimed must have been acquired in no less than 30 months. At least 50 percent (1,500 hours) of the claimed experience must be in non-residential appraisal work. Again, upon request, the applicant must provide the appraisal board copies of appraisal reports to support claims of experience. Appraiser Instructor - additional experience and abilities, as with most teaching positions. In Florida, all appraisers renew on the same date, in a two-year cycle set by rule, and must successfully complete continuing education requirements in order to renew any registration, license or certification. What are the components. of an appraisal report? Broad, basic components of an appraisal report generally consist of: 1. A description of the property and its locale; 2. An analysis of the "highest and best use" of the property; 3. An analysis of sales of comparable properties "as near the subject property as possible." Blountstown 20331 WEST CENTRAL AVENUE (HWY. 20 W. 1 BLK. WEST OF BURGER KING) MIKE WHITFIELD DAVE PETTY Program and off Lease Cars Trucks SUVs -Vans Good Credit, Bad Credit, No Credit... Give us A Call 850-674-3307 1-800-419-1801 TFftE! Paul E. Garland, MD Bay,County s Only Fellowship-Trained Oculoplastic Surgeon THE NCE'I'ER of North Florida PANAMA CITY PC BEACH CHIPLEY PORT ST. JOE 784-3937 234-1829 638-7333 227-7266 TOLL FREE 1-800-778-3937 AkmJ0. P,'lE alnM .-Mr .Jns 0-Jh .WlrM efe .Pn,0 Plus Sales Tax and Tag 72 mo Financing " Home Town Boys with Home Town Service WMMY 4. Information regarding current real estate activity and/or market area trends. agent will suggest a selling price to the seller based upon the CMA analysis (See Who performs property appraisals?). However, neither the seller nor the agent? A negotiated price of 10 percent less than the listed price on a property that was listed at 20 percent above its value is not a bargain. The agent cannot, by law, tell the purchaser that the , offered price is higher than the value, or even higher than , their own CMA. In most states, the agent must submit the , offer to the seller. The seller of a property . may want to order an appraisal before listing the property. The cost of the appraisal is usually a deterrent, especially if the seller knows that a buyer will pay for it when applying for a loan. But the appraisal is often justified. The seller could lose a sale if the property , .appraises for less than the sale price when appraised by the appraiser. Why do people order real estate (property) appraisals? The most common reason for ordering an appraisal is to '- obtain a mortgage. Other reasons include: to reduce property taxes - and appraisals to counter an assessment by the county property assessor; probate;. - estate planning; divorce ". settlements. Most lenders are required by federal and state laws and current banking regulations to obtain an appraisal for most loans secured by r6al estate. As of Jan. 1, 1993, all appraisals made for mortgage loans from -federally insured lenders and other federally related transactions must be made by-a licensed or certified 2 appraiser. Significantly,' individuals applying for a loan are usually only interested in obtaining the loan and are not worried about the prudence of buying the property at the agreed-upon price. In fact, many purchasers will try to encourage appraisers to increase the appraised value so that they can purchase the - home regardless of its value. . The majority of private real estate appraisals are "- requested by mortgage companies to validate the. property's purchase price for loan purposes. Except for periods of very low interest rates when everyone is refinancing, most loans are for the purchase of (See APPRAISAL BASICS 7A) Research shows that purchasers mistakenly assume that mortgage companies are looking after their interests in the purchase transaction, insuring via an impartial private appraisal that the value paid is not inflated. However, the law states that if the mortgage company orders the appraisal, the private appraiser is responsible only to the mortgage company. - ,I_1,. .-1 Established 1937 Serving Gulf county and surrounding areas for 69 years. 6Al TheSar ot t Je L husa, oeme 0,20 FI__tn __ hl'e 193 Sevn Gul conyadsroni ra o 9yasTeSa, otS.Je L TusaNvme 0 06.7 Appraisal Basics FromPage 6A real estate and ordered after a sale price is negotiated. Research shows that purchasers mistakenly assume that mortgage companies are looking after their interests in the purchase transaction,. insuring, through an impartial private appraisal, that the value paid is not inflated. However, the law states that if the mortgage company orders the appraisal,. the private appraiser is responsible only to the mortgage company. People expect the mortgage company to be prudent, but being prudent is protecting their interests, not necessarily the purchaser's interests. The mortgage company's position is: It has two sources of repayment: the purchaser's income and the property. The responsibility to repay the loan is not based on percent of the value, a to use sales of comparable, competitive properties: same size, age, room count, condition, similar amenities and external influences. This rarely happens though, so adjustments have to be made, assuming the price is not affected by undue stimulus. Implicit in this definition is the consummation of a sale as of a specified date and the passing of title from seller to buyer under conditions portion of the loan may be insured by a private mortgage insurer. There is no decrease in risk for the purchaser regardless of the loan-to-value iatio. The investment by the purchaser is the same, a mix of personal cash and a loan that must be repaid. . How is a home's market value established? As the appraiser compiles data pertinent' to a report, lie or she may spend only a short time inspecting the property, because this is, only the beginning. 4 Considerable research- and collection of general and specific data must be conduct ted before the appraiser gan arrive at a final opinion of ,'alie. Ideall\. appraisers want earning power will support, are the most important considerations in the valuation of real property. In other words, any properties can be, compared; the vital question is, are the' ,properties a competitive comparison, are the addresses competitive addresses in ter ms of location and other qualifying factors. or are the properties being compared really apples and oranges? The Uniform Residential Appraisal Report, the official appraisal report form intended to be used -by all private 'property appraisers, defines market value as: "The most probable price. which a property should bring in a .competitive and .open market- under all conditions requisite to a: fair sale, the buyer and seller, each acting prudently. knowledgeably and special or creative financing or sales concessions* granted by anyone associated with the sale." What is the connection between property appraisals and property taxes? Ad valorem property Ad valorem property taxes are based on fair market property estates, as determined by market transactions. But if those market transactions have been corrupted (inflated) property appraisals, then those assessments may be wrong. *, ,,-o a., ...,. ,. .. . ." - based on what people will pay extra for. Examples: extra square- footage, bedrooms, fireplace, upgrading, parking facilities, swimming pool, lot size, 'location, and so on. To help get a better picture, the information is entered on a form, a value for differences is established, and comparisons are made to the subject property. A minimum of three verified closed sales with photographs are required to establish a value. The value indicated by the most recent and factually comparable sales of competitive properties, the current cost of reproducing or replacing a building, and the value that the property's net taxes are based on fair market property values of individual estates, as determined by market transactions. A local tax assessor applies an established assessment rate to the fair market value. By multiplying the tax rate by the assessed value of the property, a tax due is calculated. But if those market transactions have been corrupted (inflated) by fraudulent private property appraisals, then those assessments may be wrong. The taxing authority requires and/or performs an appraisal of the monetary value of the property, and tax is assessed in proportion to The assessment is made up of two components: the improvement or building value, and the land or site value. that value. The assessment of an In the United States, individual piece of real estate property tax on real estate may be according to one or is usually assessed by local more of the normally accepted government, at the municipal methods of valuation (income or county level. approach', market value, or replacement cost). Assessments may be given at 100 percent of value, or at values of individual some lesser percentage. In most, of not all, by fraudulent private assessment jurisdictions, the determination" of value made by the assessor is subject to some sort of administrative or judicial review, if the appeal These taxes are collected- is instituted by the property by municipalities such as owner. cities, counties, and districts in many locations in the U.S. They fund municipal budgets for school systems, sewers, parks, libraries, fire stations, hospitals, etc. (The next article in this series will examine the types of bogus private property appraisals and how the schemes work.) The value of a house is based on recent sales of similar, neighboring homes in the market, as well as rentals and listing data. TRANSPORTATION PLANNING MEETINGS (THE PUBLIC IS INVITED) Bay County Transportation Planning Organization (TPO) Wednesday, December 6,2006 at 3:30 p.m. Panama City City Hall Commission Chambers The agenda will include the following topics: 1. PUBLIC HEARING Approval of 2030 Long Range Transportation Plan (LRTP) 2. Endorsement of FDOT Tentative Five Year Work Program 3. Approval of Amendment to FY 2007 Transportation Improvement Program (TIP) 4. Endorsement of Concept of,the North Florida Transportation Alliance 5. Support Legislation to Expand Items Included in the Strategic Intermodal System (SIS) 6. Support Legislation to Create Transportation Bond Financing Program 7: Authorize Cointract with Downtown Improvement Board (DIB) for Trolley Shelters 8. Approval of Letter of Interest Property for expansion of Public Transportation Facilities 9. Appointment of TPO Member and Alternate to Serve on the Metropolitan Planning Organization Advisory- Council (MPOAC) for 2007 10. Approval of New TPO Letterhead 11. 'Public Forum. This is an opportunity for the public to address the TPO regarding transportation issues. The TPO's Advisory Committees will meet as shown below on Wednesday, December 6,2006 in the Panama City City Hall: . * Technical Coordinating Committee (TCC) 10:30 a.m. * Citizens' Advisory Committee (CAC) 1:30 p.m. * Bicycle Pedestrian Advisor\ Committee (BPAC) 12:00 p.m. Agendas are available on the TPO's website at. Direct questions or comments to Mr. Nick Nickoloff at 1-800-226-8914, ext 212, or nickoloffn@ wfrpc.dst.fl.us. The TPO will make reasonable accommodations for access to the meetings in accordance with the Americans with Disabili- ties Act and for language requirements other than English. Please notify Ms. Ellie Roberts of access or language require- ments at 1-800-226-8914, ext 218, at least 48 hours in advance. Announcement: The Bay County Intergovernmental Coordination Committee for Roadway Concurrency Manage- ment will meet Wed nesday, December 6, 2006 at 9:00 am in the Panama City City Hall Conference Room behind the Commission Chambers. Contact Mr. Jason Pannanen at 784-4025 for additional information. The county property appraiser does not create value. People create value by buying and selling real estate in the open : market place. The property appraiser is responsible for studying these transactions, interpreting :the market, and appraising each property accordingly for tax purposes. . TheStrPor S. oe FL- husda, ovmbr 3, 00 -7A Establish 197 -Serving Gulf county and surrounding areas for 69 years 8A The Star, Port St. Joe, FL Thursday, November 30, 2006 Established 1937 Serving Gulf county and surrounding areas for 69 years PICKS Rutgers Louisville Navy California I Clay Keels 73% (96-34) 5. USC 6. Hawaii 7. Troy, 8. Florida *.f-tals by the Bay .Le ,4 t An.rd's jlorist and Gifts Your Floral & Tuxedo Specialist 2. (850) 227-1564 208 Reid Ave, Port St Joe, FL B Mel SMagidson S.^ 71% (92-38) 1. West Virginia 5. USC 2. Louisville 6. Hawaii 3. Navy 7. Troy 4. California 8. Florida Mel Magidson, Jr., ATTORNEY AT LAW 528 6th St. Port St. Joe, FL 850-227-7800 h" Ralph Roberson 75% (98-32) 1. West Virginia 5. USC 2. Louisville 6. Hawaii 3. Navy 7. Troy 4. California 8. Arkansas ROBERSON & FRIEDMAN, P.A. CERTIFIED PUBLIC ACCOUNTANTS (850) 227-3838 214 7th Street, Port St Joe, FL 1. West Virginia 2. Louisville 3. Navy 4. California First Floridian - A Travelers Company Andy Smith '2% (94-36) 5. USC 6. Hawaii 7. Troy 8. Florida Hannon Insurance 850-227-1133 221 Reid Avenue. Port St. Joe Steve Kerigan 70% (91-39) 1. West Virginia 2. Louisville 3. Navy 4. California 5. usc 6. Hawaii 7. Troy 8. Arkansas COAST 2 COAST PRINTING & PROMOTIONS, INC. One Source f6r ALL of your Printing and Promotional needs! (850) 229-2222 David Warriner 74% (97-33) k Rutgers Louisville Navy California USC Hawaii Troy Florida PORT INN PORT ST.. JOE, FLORIDA (850) 229-7678 501 Monument Ave. Port St. Joe Tim DePuy onwrn 72% (94-36) 1. 2. 3. 4. Rutgers. Louisville Navy California 5. USC 6. Hawaii 7. Troy 8. Florida (850) 229-7665 408 Garrison Ave., Port St Joe, FL Mark / Costin 0% (91-39) 5. USC 6. Oregon State 7. Troy 8. Arkansas Port St. Joe St. Joe Ace Hardware - #00844 201 Williams Avenue 850) 227-1717 or 229-8028 1. West Virginia 2. Louisville 3. Navy 4. California The helpful place. ( 1. West Virginia 2. Louisville 3. Navy 4. California Gulf Coast Realty 1. West Virginia 2. Louisville 3. Navy 4..California Jay Rish r0% (91-39) 5. USC 6. Oregon State 7. Troy 8. Arkansas (850) 227-9600 252 Marina Drive Port St Joe, FL Norton ;9% (90-40) 5. uSCe 6. Hawaii 7. Troy 8. Florida S(OASTALCOMMUNITY BANK n206 .ornum-.n A t-corI '-I Joe, Florida 32456 850-227-7722 www coastalcommunltybank.com 1. 2. 3. 4. Dina Parker 7. 69% (90-40) West Virginia 5. USC Louisville 6. Oregon State Navy 7. Troy, California 8. Arkansas PROSPERITY B13ANK I -Suddk Oar CoMw",ity Port St. Joe 528 Cecil G. Costin Sr. Blvd. 850-227-3370 Ralph Rish 69% (90-40) 1. West Virginia 5. USC 2. Louisville 6. Hawaii 3. Navy 7. Troy 4. California 8. Florida (850)227-7200 324 Marina Drive PREBLE-RISH INC Port St Joe, FL CONSULTING ENGINEERS & SURVEYORS West Virgi Louisville Navy California rJi F-east Megan Burkett 69% (90-40) inia 5. Usc 6. Hawaii 7. Troy 8. Florida S(850') 227-7775i S P.106 Reid Avenue. .U Port.St Joe, FL fl Dusty & Daniel May S68% (89-41) 1. West Virginia 5. USC 2. Louisville 6. Hawaii 3. Navy 7. Troy 4. California 8. Florida FRANK D. MAY, DMD, PA Dental i lre uia'" O gonle s. iOdv .adrnced (850) 227-1123 319 Williams Avenf Port St. Joe -vw.doctormay.coan M Jim 'r Established 7937 Serving Gulf county and surrounding areas for 69 years 8A The Star, Port St. Joe, FL-ThrdyNoebr3,20 I Esalse 193 evn ufcut n urudn ra o 9yasTh tr otS.Je L*TusaNvme 0 06 Tim Kerigan 8% (89-41) 5. USC 6. Oregon State 7. Troy 8. Arkansas Nautical 0.R MORT GAG E 229-LOAN Patti Blaylock 1 67% (87-43) 1. West Virginia 5. USC 2. Louisville 6. Hawaii 3. Navy 7. Troy 4. Stanford 8. Florida S(850) 227-7900 602 Monument Ave Coastal Grill Hwy 98 -_ .Port St Joe, FL po.rl ,f. io, floida 1. Rutgers 2. Louisville 3. Navy 4. California Joan Cleckley 65% (85-45) 5. USC 6. Oregon State- 7. Troy, 8. Florida (850) 229-822 529 Cecil G. Costin Sr. B] Port St Joe, FL 1. West Virginia 2. Louisville 3. Navy 4. California, Gulf Coast Realty 1. West Virginia 2. Louisville 3. Navy 4. California Bo Datterson 36% (86-44) 5. USC 6. Oregon State 7. Troy 8. Arkansas Bo Knows Pest Control (850) 227-9555 402 3rd Street, Port St Joe, FL 1. West Virgin 2. Louisville 3. Navy 4. California N SFarnsle W E Providing. 6 [vd Aaron Farnsley 65% (85-45) iia 5. USC 6. Hawaii 7. Troy 8. Arkansas yTB Person, Financial Consultants onalized Financial Guidance (850) 227-3336 202 Marina Drive, Port St Joe, FL Darius Chambers 66% (86-44) 1. West Virginia 5. USC 2. Louisville 6. Oregon State 3. Army 7. Troy 4. California 8. Florida % piggly wiggly (850) 229-8398 125 W Hwy 98, Port St Joe, FL Keith "Duke" 64% (84-ones 64% (84-46) 1. West Virginia 5. USC 2. Louisville 6. Hawaii 3. Navy 7. Troy 4. California 8. Arkansas AUDIT, ACCOUNTING, TAX & CONSULTING SERVICES America Counts on CPAs 411 Reid Avenue Port St. Joe, FL 32456 850-229-1040PH 850-229-9398 FX 1. West Virginia 2. Louisville 3. Navy 4. California 1.Ru 2. Loi 3. Na 4. Ca (850) 4 908 ,Cap( Port tgers uisville vy lifornia 229-9703 e San 'Bias Rd St Joe, FL Boyd Pickett 4% (83-47) 5. USC 6. Oregon State 7. Troy' 8. Arkansas 5. USC 6. Hawaii 7. Troy 8. Florida Dockside Cafe (850) 229-5200 342 West 1st Street Port St Joe, FL 1. West Virginia 2. Louisville- 3. Navy 4. California Bill Williams 63% (82-48) 5. USC 6. Oregon State 7. Troy 8. Arkansas IINTEGRA THERAPY WCLLHNCE (850) 647-9170' 190 Lightkeepers Drive, St Joe Beach, FL PICKS Brett Lowry 60% (78-52) 1. West Virginia 2. Louisville 3. Navy 4. California Gulf Coast Realty 5. USC 6. Oregon State 7. Troy 8. Arkansas (850)227-9600 252 Marina Drive Port St Joe, FL Week of November 30,, 2006' PREDICTIONS Circle the teaminame you are preicting to w iforeach game listed 1. Rutgers at West Virginia 's anaeasy IK e winners in e games iste 2.Connecticut at Louisville I by the team you think will win. (One entry per person If more than one entry is entered,you will be 3. Army at Navy disqualified. Must be 18 or older to play. 4. Stanford at California Employees of Star Publications and -T5BtS C a t"CL their family members are not eligible 5. USC at UCLA to participate in the Pigskin Picks. I I Bring, fax or mai. your 6. Oregon State at Hawaii entry to: r 7. Troy at Florida Int. I 135The Star98 Port City Shopping Center Tie Breaker: (SEC Championship at the Georgia Dome) I Port St Joe, FL 32456 I PickScore I S Fax: 227-7212 PickScore Name | Entries must be brought in, Arkansas Address mailed or faxed no later than noon Friday prior to games. Daytime Phone Last Week's Winner: Ralph Pittman, Port St. Joe, FL: Missed 3 out of 10 S (Random drawing will determine,winner in case of a tie) L -. -. -. .- -m .. m -..- - ...-.- .- -..-.-.-.--- ..-.-.-..- -- 1. West Virginia 2. Louisville 3. Navy 4. California ; FINE WINE & SPIRITS (850) 229-2977 202 W. Hwy 98 Port St. Joe Matt N Trahan 55% (71-59) Blake Rish )8% (88-42) 5. USC 6. Oregon State 7. Troy 8. Florida (850) 227-9600 252 Marina Drive Port St Joe, FL Michael Hammond 67% (87-43) 1. West Virginia 5. USC 2. Louisville 6. Hawaii 3. Navy 7. Troy 4. California 8. Florida a Go Noles! ~a3~-~l-_ ~ur--~s&-----dlsr~-Irrrr--P~is9s~.~ 7k;B_'~YII*llll&tajIPac Ir~I-~LPI~DP~PI I--2-"~~L;lkl"BDPO~.~t Established 7937 Serving Gulf county and surrounding areas for 69 years TheStr, or S. JeFL Turday Nvemer30 206 9 IAA rT... e-... .-' C;f+ ,ln iL Th.,rscl, MNovember .0 92006 North Florida Christian Holds C By Tim Croft Star News Editor North Florida Christian coach Casey Weldon admon- ished his celebrating play- ers to gather and prepare to shake the hands of the visitors before enjoying any of the fruits of victory. After shaking hands with each player and cheer- leader, Weldon then faced the visiting stands and gave them a thumb's up, for their support of the van- quished and as a salute to the team they had followed )ff Port St. Joe to Tallahassee. Port St. Joe coach John Palmer thanked his players for their season of effort and then pulled his seniors - "In their four years here they have elevated the pro- gram," Palmer said after- ward together for an emo- tional, and final, huddle. Those were the two sides of the scale last Friday night after North Florida Christian had survived a scare it hadn't encoun- tered since September and earned the right to play for the state Class 1A foot- ball title from the team which won the ring last December. ' Port St. Joe held near- ly every numerical advan- tage last Friday night in Tallahassee save the most important on the score- board. The Sharks (9-3) out- gained host North Florida Christian (11-2) and con- trolled much of the clock but came out on the short end of an 18-13 score and thus denied a chance to ,.... .. - ,. ... S Tim Croft/The Star Port St. Joe's Ashley Davis, receiving the handoff from quarterback Mike Quinn, had 65 yards and scored the Sharks' first touchdown. Langston Tournament Slated fi I The Norris D. Langston Youth Foundationr Basketball Classic will feature a new look on;Dec. 15-16, with a full slate .of high school hoops action in dte offing. ' SThis year the tournament is strictly a prep affair, with Dr. David Langston, president and CEO of the foundation, decid- ing to focus on high school basketball instead of the junior college line-up which has char- acterized past tournaments. Port St. Joe and Wewahitchka high schools are among a dozen or so schools partici- pating For the second-straight year, the tournament will be or Dec. 15-16 .held at Chipola Junior College, as the foundation continues its goal of exposing youngsters to the college environment as a way of broadening horizons. The, tournament is spon- sored this year by the Florida Department of Lottery. Following is the slate of .games. All times, noted are Central Standard Time: Friday' 1 p.m. West Gadsden ver- sus Bay High (girls); 2:30 p,.m. Vernon versus Quincy Carter Parramore;. 4 p.m. West Gadsden versus Tallahassee Godby; 5:30 p.m. Ocala . Shores Christian versus East Gadsden; 7 p.m. Malone versus East Gadsden (girls); 8:30 p.m. Port St. Joe versus Daytona Beach Seabreeze. Saturday. 10 a.m. Wewahitchka versus Vernon' (girls); I1:30 a.m. Carter Parramore versus Bay (girls); 1 p.m. - Godby versus Seapreeze; 2:30 p.m. East Gadsden versus Cottondale (girls); 4 p.m. Shores Christian versus West Gadsden; '5:30 p.m. Blountstown versus Cottondale; 7 p.m. Malone versus West Gadsden (girls); 8:30 p.m. Port St. Joe versus East Gadsden. 4' - 4,,. 1.. I Tim Croft/The Star Port St. Joe's Patrick Bailey gives NFC tailback Dayne Read no room to run. defend their :Class 1A state title Friday isi Miami. Remove a slow start and a critical fourth-quar- ter score after Port St. Joe took its lone lead of the night and the Sharks played with I characteristic toughness and could have emerged victorious. "We had' our chances and we just didn't quite get it done," Palmer said. "I was pleased that we were right there with them, but disappointed we won't get a chance to defend our title." The Sharks rushed for 246 yards and held the high-scoring Eagle offense, which rang up 49 points last weekend against Jacksonville University Christian, to 31 fewer points and 294 total yards. Port St. Joe had entered the game with a few new wrinkles in their defensive scheme aimed at corralling North Florida Christian's passing attack by playing deeper and blitzing less. For the most part it worked, thanks to tremen- dous work at the corners by Mike Quinn and Jordan, McNair and consistent pres- sure from the front four which limited the Eagles' big-play. capabilities. Eagle quarterback Chris Walley was 10 of 17 for just 133 yards and no touchdowns. The Sharks even' unveiled some aerial fire- works of their own, includ- ing a key 52-yard pass late in the first .half, to run up 317 total yards. "They have .a great team and played with a lot of heart," said Weldon, ' the former Florida State University. and NFL quar- terback in his first year at North Florida Christian. "It was an.incredible game. We were fortunate to come out on top." Port St. Joe dug a hole in the first 6:30 of the game from which they only brief- ly emerged. The Eagles took the opening kickoff and marched 78 yards in nine plays primarily behind the legs of Dayne Read (99 yards rushing, 60 receiv- ing), who plunged over from the 1 for the touchdown. Walley also converted a key third-and-11 to keep the drive alive. The extra-point kick was wide and the Eagles were up 6-0. Three plays late, McNair fumbled a pitch while sprinting on a sweep to the right and the Eagles recovered at the Shark 33' Two plays later Walley found Read for a screen pass which went for 20 yards to the Port St. Joe 3. Read barged over left tackle for the touchdown, the pass for two points was broken up and the Sharks were down 12-0. But they would not fold, steadily winning the field position battle through the rest of the half thanks to defense and Austin Peltier's consistent punting before an exchange of turnovers - Port St. Joe quarterback Mike Quinn was intercept- ed and Read fumbled on the ensuing play gave Port St. Joe the ball at its 30. From there, Quinn guid- ed a 10-play march that. culminated in his 52-yard completion to McNair who was running a post pattern to set up Ashley Davis' 1,- yard touchdown run. ' Peltier was barely wide (See SHARKS on- Page 11 A) Dixie Youth Annual Meeting The Dixie Youth Girls Softball League will be holding its annual meeting on Thursday, Nov. 30 at 6 p.m. at the Tenth St. Ball Field. Any person interested in becoming a board member must attend. All persons interesting in coaching should be present. Any question or for more informa- tion, please contact Steve Brinkmeier aft 648-8352. W SPORTS SCHEDULE SWEWAHITCHKA GATORS 2006 Varsity. Basketball Schedule Team Place Pre-Toumey Blountstown - Pre-Tourney Blountstown Sneads Home' Port St. Joe Away Bethlehem Away Liberty County Home, Altha Away Blountstown Apalachicola Langston Presentation Carrabelle Langston Tourney Poplar Springs Blountstown Tourney Home Home Away Away Chipola Home Blountstown Time 6:00 7:30 6:00 5:00 4:00 5:00 5:30 6:00 5:00 6:00 5:00 12:30 5:00 6:00 Emerad Coast - Federal Credit Union PORT ST. JOE 530 Cecil G. Costin, Sr Blvd., Port St. Joe, FL 32456 emeraldcoastfcu.com EMERALDCOAST@GTCOM.NET 850-227-1156 WEWAHITCHKA 101 East River Road Wewahitchka, FL 32465 850-639-5024 0p, STAR PLAYER OF THE WEEK t Wewahitchka High School. WNo Results Provided. | Coaches call 227-7827 or email timc@starfl.com ,' SUPERIOR BANKING MORTGAGE INVESTMENTS Alth 2. 2546 .a.n S.* 850-762-3417 Bristol 10956 NW Stare Rd 20 850-643-2221 SApalac oa a 58-thSt. *850-653-9828 Carrabelle 912 Northwest Avenue A 850-697-5626 iBdntstownh 20455 Certral Ave. W 850-67415900 Mexico Beach 1202 Highway 98 850-648-5060 V Port St. Joe 418 Cecil G. Costin, Jr. Blvd 850-227-1416 I M Fw ember FDIC ww -Ieriorbank.com 'a w s:-''^ '.'"'*{:-' :* '* i *- ^?T; '*':*' *~ ** '* ** ~ ~ *;sv:~~fr is^ ^sp s~n ^ 21T11" Date Nov. 14 Nov. 16 Nov, 21 Dec. 1 Dec. 2 Dec. 5 Dec. 7 Dec. 8 Dec. 12 Dec. 14 Dec. 15 Dec. 16 Dec. 18 Dec. 20-22 IU etr oTw.j e L In UU Y 14v lltlo v Established 1937 Serving Gulf county and surrounding areas for 69 years -'- -~ The Star, Port St. Joe, FL Thursday, November 30, 2006 11A Established 1937 Serving Gulf county and surrounding areas for 69 years Sharks right with the extra-point kick and the Sharks went into the locker room at halftime within 12-6 and with momentum. "We did hurt ourselves a couple of times on offense but the kids did a great job coming back from 12 points down," Palmer said. The Sharks averted more disaster early in the third quarter when a Peltier - From Page 10A punt was blocked and NFC took over at the Port St. Joe 25, but the defense held and a 39-yard field goal attempt barely made it past the line of scrimmage after a poor snap. "The kids played terrif- ic defense all night," Palmer said. ' The missed field goal seemed to fuel the Sharks, who marched 80 yards in 11 plays behind the rush- ing of Chaz Byrd (95 yards) and Davis (65 yards), con- suming nearly five minutes of increasingly precious time. McNair covered the final 28 yards on a sweep around right end and Peltier's extra-point gave the Sharks a brief 13-12 lead. Brief because the Eagles answered immediately, with Walley passing and running the Eagles over 63 yards in 11 plays, sneaking over Tim Croft/The Star Shark quarterback Mike Quinn passed for 71 yards, including a key 52-yard post pattern to Jordan McNair to set up the Sharks' first points. Tim Croft/The Star Mike Quinn wheels to pitch to Chaz Byrd, who led Port St. Jot with 95 rushing yards against North Florida Christian. Sharks Split Two for Week By Tim Croft Star News Editor A district win and a lesson in what it will take to advance in the playoffs provided the bookends for the Port St. Joe High School boys' soccer team this past week. The Sharks (5-1 overall) remained undefeated in the district with a 6-0 victory at Freeport last Monday night. in, game .which allowed the Sharks to provide their entire roster some playing time. I Freeport, in its first year of .soccer, was fielding a co- ed team, which must compete against boys' teams from other schools. Mica Ashcraft, with an assist from John Larsen, Kurtis Krum, with an assist from Jimmy Curry, and Sam Ellmer, who netted a penal- ty kick, scored in the first 10 minutes of the game and Coach Tom Curry pulled most of his starters. "They reminded me of us in the early days before we even had a luhi school team and played just recreational soccer," Tom Curry said. "This game gave .up an opportunity to get some players experience, which is important since we do not have a jayvee team." Samuel Van Dam on anl assist from Carlos Castillo made it 4-0 Port St. Joe before Chris James scored the final two goals, the first on an assist from Krum, the second unas- sisted. Monday, Nov. 27 Wakulla 1, Port St. Joe 0 The Sharks played, one of those contests which will prove valuable come playoff time. Having won its district each of the past two years only to bV eliminated in the open- ing regional playoff game, the Sharks need the experience of facing some of.the best teams in the area. Wakulla beat the Sharks 4-0 in a preseason match, but Monday it was a much closer affair. "It was a great game, the kind of game we need to play in order to advance in the region come playoff time," Coach Curry said. "They played very well, we played very well, it- was a great defensive game." Wakulla scored the lone goal roughly five minutes into the second half on a play In which the ball bounced among players in the box before being knocked into the net. "We had our opportunities, six good opportuni- ties, to scored and - just didn't get it done," Coach Curry said. "We learned that when we get those opportuni- ties against good" teams, we have to score." Zeke Stephens V came in. for spe- cial praise. having E1 spent the entire game marking Wakulla's top play- er, midfield Patrick Stewart, who grew . increasingly frus- ". treated as the game wore on. .. - Goalkeeper. Hunter Garth, Kevin Quaranta, Philip Fuze. and Adam Footlick helped Stephens anchor a defense which was nearly impenetrable. "They did a great job,"' Coach Curry said. from the 1 with the go-. ahead score with just under nine minutes remaining. It was the one drive in which Walley had any con- sistent success in the air, but it was a critical one. The run for two points was stuffed and it was 18- 13. "That was an unbeliev- able drive, to answer back like that," Weldon said. "We thought we had balance; that we could pass and we could run and we proved it on that drive." The Sharks never really threatened after that, the product, arguably of a pass- ing game that was inconsis- tent all season,. but also an Eagle defense schemed' to stop McNair sweeps to either side. Port St. Joe was also constrained when Mike Quinn hurt his knee for at least the third time in the game and had to come to the sideline on a fourth- and-three at the NFC 40 with six minutes remain- ing. With Quinn 'available, the Sharks would have almost certainly gone for the first down. But it was no time to, insert a reserve cold off the bench. And though the Eagles missed on another field goal attempt, this from. 42 yards, they ate up all but 45 seconds of the clock. This answered the ques- tion of whether Port St. Joe would have the opportu- nity for one last ground- gobbling march with a resounding no. PSJ 0 6 7 0 13; NFC- 12 0 0 6 18 First quarter NFC Read 1 run (kick failed) NFC Read 3 run (pass failed) Second quarter PSJ Davis I run (kick " failed) Third quarter PSJ McNair 28 ruin (Peltier kick) Fourth quarter NFC Walley 1 run (run failed) A TASTEFUL BITE OF INNOVATION The BestQuality. The Best Price. Whirlpool KitchenAid Roper Estate St. Joe Hardware Port St. Joe's Appliance Source Since 1960. .-Jonat;an D- idson e Star". Jonathan Davidson/The Star FREE DELIVERY PSJ, CAPE, & BEACHES. WE WILL HAUL THE OLD APPLIANCE OFF. ACE :ST" JOE HARDWARE CO. .201 Williams Avenue, Port St. Joe 229-8028 Hardwaare Monday-Friday 8:00-5:30 EST Closed Sundays STAR PLAYER OF THE WEEK Port St. Joe High School Game 1.: . 5 3. 4. 5. SPORTS SCHEDULE PORT ST. JOE SHARKS 2006 J.V. Football Schedule Date 8/18 8/24 9/7 9/14 9/21 6. 10/5 Team Vernon Bfountstown Wewahitchka N.F.C. Florida High Wewa Place Time (A) 8:00 (H) 7:00 (A) 7:00 (A) 7:00 (H) 7:00 (H) 7:00 9/8 Chipley 9/15 *Freeport 9/22 *Wewahitchka 9/29 *Sneads (Homecoming) *Liberty County (A) OPEN *Jay (H) (Senior Night) 'West Gadsden (A) Apalachicola (A) 8. 10/6 10/13 9. 10/20 2006 Varsity Football Schedule Game Date Team Place Time 1. 8/18 Vernon (A) 8:00 Congratulations to the 2006 Sharks on a regional title, a trip to the state Class 1A football semifinals and another season of great memories. BANKING MORTGAGE INVESTMENTS Alt.a 25463 N. M-lain St. 850-762-3417 Bristol 10956 NW Stare Rd 20.. 850-643-2221' . Apalachicola 58 4th St. 850-653-9828 Carrabelle 912 Northwest Avenue A 850-697-5626 Blountkown 20455 Central Ave W 850-674-5900 Mexico Beadc 1202 Highway 98 850-648-5060 Pore St. Joe 418 Cecil G. Costin, Jr.Blvd 850-227-1416 - ,, . 11, M e .... .... WA\ SL _rl-l'Ih I .C :;_I , 2. 8/25 Blountstown (H) 3. 9/1 Marianna (H) 10/27 11/3' 7:30 7:30 Advertise Here and Support Your Team! Reeves Furniture & Refinishing 234 Reid Ave. 229-6374 All Wood Furnture. Gifts. Wicker, Kitchen Cabinets The Star Come Visil Us At Our NeN Locanon 135 W. Hwy. 98. Port City Shopping Center 227-1278 8:00 8:00 8:00 8:00 7:30 8:00 8:00 7:30 * * District 1 Games/Class A All timeT are Eastern Bayside Lumber 516 First Street 229-8232 Your Building NMaterials Headquarters Gulf Coast Real Estate Guide Give Us A Call To Place Your Ad Today 227-1278 or 653-8868 -:~~~~~~~""~Bfh)l~nkl (IrsDtcn or . . IIA Ine 3Tar, t orT OT. JOe, L "- IInuisuuy, iUv iluVie e v/, .vw THE FORECAST Established 1937 Serving Gulf county and surrounding areas for 69 years WEATHER Temps for November 30 RECORD High: 79" (1931) Low: 27 (1979) TODAY 330 Partly sunny with a few sct. thunderstorms High: 770; Low: 650 TOMORROW Showers and thunder- storms High: 710; Low: 550 SATURDAY 2I- Z Mostly cloudy and cooler High: 690; Low: 520 SUNDAY Continued mostly cloudy. High: 690; Low: 450 MONDAY Sunny to partly cloudy and cooler High: 640; Low: 410 TUESDAY Sunny to partly cloudy skies High: 630; Low: 42 WEDNESDAY Sunny to partly cloudy skies High: 64*; Low: 44* Todj,,' rhugh and torlngnt's low temperatures -Enlerprise- itban ' 62 62 '.-- -- '- "- .. Bainbrildg I efijnijk Springs iceville ., ; ,' ' c-WC6--. CrystalLake ". rist . .... 7 8 i 6 6 W ew- t"'I'" I l ...W.wa"i'iika- Panama City, 78/6 Pensacola ... ." :"'.' "';" :.' -... 7 6 6 1 : " Port St. Joe - '" r "' Apailahicola - 78,65 .... LAST 7 DAYS Monday 11/27 75/51/0.00 Sunday 11/26 70/48/0.00 Saturday 11/25...................... 71/48/0.00 Friday 11/24 68/41/0.00 Trur';dav' 11,23 63 42- 0Ul Wadrinsday 11 22 64/36/0.00. Tuesday 11/21 58/38/0.00' SUN & MOON Sunrise Sunset Trursda 11 '30 .7 18 a.ri .5 41 p.n, Friday 12 1 .'.7:19 a.m.. .5:41 p.m. Saturday 12.2....7:20 am.. .5:41 p m Sunday 12'3 ....7:21 a.m.. .5:41 p.m. Monday/ 124....721 a m. .5:41 p.m. Tuesday 12/5.... .7:22 a.m.: .5:41 p.m. Wednesday 12 6 7 23 am .5:42 p m Moonrise Moonset Triursdjy 11.30. 2 31 pm..2273 m. Friday 12'1 ......3-04 pm .333 3 rm Saturday 122 .. 3:42 p.m 4.41 anm Sunday 12 3 ...426p.m 551mrr Monday 12'4 ... .5:16 p.m.. .7:02 a.m. Tuesday 12 5 ..6 14pm S 11 3 m Wednesday 12'6 .7.16 p.m .9 12 am. APALACHICOLA RIVER Site Flood Stg. Stage Chg. Woodruff Tailwater 66,.0 43.93 -0.22- Chattahoochee 43.92 -0.29, 31ouril-;liwn 150 6412 0 23 vewhiljrnir n170 .042 OCHLOCKONEE RIVER Thirima'vdlie? Concord Havana. Bloxham .', Moderate 1 23 4 5 150 206 25.73 25.0 11.94 22.0 3.42 Tl LIU |'l i I f., number the more risk of sun damage to your skin. 6 7 8 9 10 11 12 [ru 14 tc1ri, 1i,. Hif Full Dec 4 Last New .First Det 12 iEcrU D Dc, 2T Friday Hi Lo Albany 69 50 Apalachicola 72 56 Bainbridge 70 51 Bristol 70 50 Columbus 64- 44 Crystal Lake 68 49 Defuniak Sp. 68 49 Dothan 68 48 Enterprise 68 48 Ft. Walton Bch.66 49 Gainesville 75 53 Jacksonville 75 53 Marianna 69 49 Mobile 64 40 Montgomery 60 39 Newport 71 53 Niceville 66 49 Panama City 70 53 Pascagoula 58 41 Pensacola 67 46 Port St. Joe 71 .55 Tallahassee 71 55 Valdosta 73 56 Wewahitchka 71 51 Wilm-i 71 51 Thursday High .Low Friday High Low Saturday High Low Sunday High Low Monday Hih Low Tuesday High Low Wed. Hirh Low ST. JOSEPH BAY A.M. 3:57 12:20 A.M. 7:06 3:03 A.M. 7:02 3:55 A.M. 7:24 4:46 A.M. 8:04 5:42 A.M. 8:53 6:45 A.M." 9:48 7:55 All forecasts, maps and graphics @2006 Weather Central, Inc. For a personalized forecast, *,. u I,: Saturday Hi Lo. Otik 67 46 s 69 52 c 68 47 pc 68 48 c 64 42 s 66 45 pc 65 45 pc 67 44 s 67 43 pc 67 51- pc 73. 51 pc 68 49 pc 67 46 pc 61 43 pc .60 38 pc 67 50 c 66 47 pc 68 52 pc 62 43 pc 64 46 pc 69 52 c 69 50 pc 68 48 pc 69 50 c 69 ,50 c P.M. ft. 7:59 0.9 P.M. ft. P.M. ft. P.M. ft. P.M. ft. P.M. ft. P.M. ft. - K I A A storm system will produce showers and thunderstorms from the lower Mississippi River Valley north into the eastern Great Lakes on Thursday. Colder air will change the rain to freezing rain and snow through the south-central Plains. High pressure will spread a chilly air mass through the north-central U.S. while the next storm system will produce rain and snow in the Northwest. Seattle A? - EXTREMES MONDAY: Hottest: 85 Laredo. " Coolest: -9 Cui Bank Today City Hi Lo Albuquerque '33 17 Arncihorr ge 21 1., Atlanta. 69 55 Baltimore 68 53 Billings 25. 16 Birmingham 74 50 Boise 34 22 Boston 64 51 Buffalo 63 54 ,.re.-enrne .24 11 CnLi'.go 42 28 Cn nirinri 66. 43 ilevelrind 61i 44 D:avincri 63 14 Denver 28 12 Des Moiri.. 27 12 Detroit 55 39 Arjpuiic AmTre'rdam Athens Baurdad Baringkok Beijngg Berlin Bru B' Air' . Cairo. S Calgary Dublin , Today Hi Lu 87 72 52 41 61 51 68 49 92 76 42 333 55 40 c5) 41 .8 58 20 5 56 43 Tomorrow Otlk Hi Lo Otlk p.: 44 24,s pi. 27 19 rs sh 59 39 :h pc E. 68 36 r pc 27 11 pcr shr, 53 36 pc pc 36 21 .pc c 61 39 r p.1 61 30 rr *s 33 11 p: r- 34 24 rn i.ri 4 5. -". r I.h 48 28 re rh 46 27 15. pc 39 17 s c 31 15 pc r 42 29 r. , ',V .. :0 " Tomorrow Clll Hi LO llll PI 85 70" pc S 51 43 si ,pc 59 50 s 67 46 F s p: 93 73 pr: pl 43 29 p: s 51 .8 .3 r 51 10 in 80 62 pc: p. 63 45 s c 21 5* sf r 48 37 sh city El P) Fair.-int'., H-oCiiiulu lrinianjrp,:,h Kansas City. Litnl RR o' L,:'. Arge-lr, Memphis Miiami i [Jashville New Orleans rjnw iork Oimarh Orlandio Today Hi Lo Otlk -45 24 2 *13 79 64 ' 60 :". r 28 18 sn 50 28 s 61 27 t 70 45 s 66 42 sh 84 73 pc 38 26 r.., 25 10 p . -73 48 pc 79 5, pc 67 55 pc 24 9 c 80 65 pc Today C Iry, Hi LO G, nevj 51 37 Hlsnr-ni 48 37 Ho,.ng Kong 77 66 Jrujaitlem 71 53 Kabul' 42 28 Lmn, *74 63 London 56 45 I'iaidrd 6i ;9. Meo.ic' City 74 52 Monireal 57 51 Moscow i 40 30 [l:w Delhi 76 55. Tomorrow Hi Lo Otik 53 29. s 9 -5 sn 80 66 s 37 23 rs 33 18 pc 54 37 s 43 25 pc 71 52 s 47 31 pc 84 73 pc 34 22 .sn 26 16.s 48 32 sh 59 .42 pc 69 41 r 32 17 pc 83 64 pc Tomorrow Hi L l-) Olll, 52 36 pc 46, 35 pL 76 67 pc 6.4 50 pc 40 25 C: 78 61 p.: 5.3 42 ..sh 61 48 'pc 63 45: ,h 56 43 sh 41 33 sh 73 53 s City Philadelphia Phoenix Pinisburgh Portland, ME Portland, OR Reno Richmond Sacramento St.:Louis Sal LI' City San Diego Sain Frjn. Seanie SplAr-'in S Tuis.on . Wash.D O.C. Wic ila CisI,' Paris Rio Rome Seouli S.irigapore Toroni Vancouver Vienna VVJI'wwlv Today Hi Lo Otlk 64 52 pc. 57 37 s, 66 51 ;sh 57 45 pc 39 37 rs 37 20 s 72 56 pc 57 36 s 41 23 r 30 16 s 67 42 s 58 45 s 42 34 rs 21 14 sn 55 .30. s 69 55 pc 28i 16 *sn Today Hi Lo 48 39 55 41 81 ,70' 60 44 37 26 88 78 77 56 52 42 59 49 39 36 54 37 52 40 Bangor 54,42 Tomorrow Hi Lo Otik 69 38 r. 65 42 s, 54 30 rT 55 35 r 142 33 Dp 39 20 s. 73 37 sh 53 37 s 34 20 sn 31 16 pc' 67 52* s'. 60 47 S: 41 33 pr 25 19 pc 62 35 s 68 37 r 37 20 s, Tomorrow , Hi Lo Olik 47 37 sn 54 42 sh 79 67 pd 59 42 s, 38 25 pc 89 77 I 84 65 po 53 41 po 58 45 sh 39 36 c 52 38 s: 50 36 s. i:p.,. 4 121 .' -'' : ''* '^ '* ';-,. *' .. <'' i ,' ; : :** *i ; -- ,; ',. ,. .- ". *'l ':5 '. ' ^ '*, .* ., '^ .- w * .., \, l . It4, - .. .,, ris tmnas..a -.T R I 'G G .E .. S. . f21 West Highway 98Port St Joe,,FL-U32456"*1 850-229. 1 00 1 "Everything For Your Outdoor Advnt r" , ~l e-,; .. m & .w~l~~wt J i oscr .! , PSE Ranger Youth Bow Set .22# Draw Weight $69.99 iUPC-0429584407 Knight Holiday Value Pack Gun Case, Hat, Bullets, Cleaning Supplies $100.00 Retail $49.99 Sale UPC-72718961869 Tasco World Class 3-9x40 Scope . With FREE Field Bag .Reg. $89.99 Sale $64.99 'UPC-04616208040 SPSE Pistol Crossbow $29.99 UPC-0429584223 CVA Wolf Muzzle Loader Breakopen Action 209 Primer $159.99 Rapture Bow by Diamond/Bowtech 60# Bow Reg. $549.00 Sale $499.99 Bowtech Allegiance 70# Bow 335FPS Reg. $749.99 Sale $699.99 Any Browning Special Order Shotgun/ Rifle 5% Off Order by December 24, 2006 Doghouse Ground Blind Camo Model 814 UPC-76952400814 Reg. $79.99 Sale $69.99 Piano 52" Gun Case UPC-02409901501 Reg. $19.99 Sale $15.99 Selected Mirror Lures 25% OFF Selected Zoom Worms 25% OFF Florida State & University of Florida Game Day Flag 25% Off Evan Lloyd Jewelry 25% Off Selected Ladies Columbia Sweaters, Vests and Shirts 25% Off. Hook & Tackle Shirts Men's Long Sleeve 25% Off Cowhide Thick Hair Rug Reg. $479.00 Sale $359.00 Dosko Bow Case UPC-0269510632 Reg. $59.99 Sale $49.99 yIa y Prices On.'..Shotgun Shells, Rifle Ammo, Boots, Tents, Sleeping Bags and More... We are full line dealers for these.and more.... vning, PSE, Browning Archery, Bowtech Bows, Diamond Bows, CVA, Knight, Shimanb and Penn NO rain checks* Some Items Limited Quantity* All Items While Supplies Last i' - - i'viw~i ~ ~ N~W' I 1 ~ t~'L,.T ,.~ IL. 7~ NORMAL High: 68 Low: 48 . ; . , .'' : *, . ." ):. "L .." KEI TO N IM M ONS cm..l.,..j.i ar=.j--::'..r * i R.ORG +. ,2CM "' PAGE 5 DECEMBER 2006 VOLUME 4, ISSUE 12 Over the past few years, an increasing number of pundits have warned about a bursting housing bubble causing a broader economic downturn or even a recession. Well it looks like they are finally right. or at least half right. SThe physical side of the market-construction J and sales-has taken a drubbing; but despite the decline, there is little or no evidence that the drop has affected consumption to date. With interest rates holding firm and the most recent new home sales figures showing the faintest flicker of life, we may yet get out of this downturn without it spreading to the broader economy. Let's take a look at the bad news first. This year we are witnessing clear evidence of the end of the housing boom. Mortgage interest rates have risen steadily since June 2003, with the 30-year conventional mortgage rate rising from about 5.2% in mid-2003 to around 6.5% currently, a 25% increase. Consequently, existing home sales have been falling for the past nine months and in August were down 12.3% from a year ago. This was the largest year-over-year decrease in existing home sales since April 1995. New home sales have followed a similar pattern and are currently down 17.4% from August 2005. The decline in sales has prompted a sharp jump in the inventory of unsold homes, which rose to 7.3 months of supply in August, the highest level since April 1993. Builders are quickly reacting to the decrease in housing demand, and housing starts have plunged nearly 17% since the beginning of the ear Home prices are reflecung the niurkert do do'.'.n with theAugust median exaing home price recording its first year-over-tvar decline I'down 1.'0'i1 since April 1995. according to the National Association of .R rors iiNRi. Another source of home price data is the Office of Federal Housing Enterprise Oversight (OFHEO), which publishes a quarterly house price index. The OFHEO index, which tracks same-home repeat sales, is considered a more accurate measure of changes in home valued. The OFHEO index has never,dropped year-to-year since its inception in 1975. In the first half of 2006, the index was up 6.8% in real terms versus the same period last year. However, a weakening in inflation-adjusted home prices will likely be forthcoming as the market softens further to work off the inventory of unsold homes. The steady increase in home prices over the previous decade, together with rising mortgage rates in the last year or so, has eroded the affordability ofhomes..Thisis shown by the NAR index of housing affordability having dropped steadily since early 2004, currently standing at 102.8. While this is the lowest level'since mid- 1986, it nevertheless remains above 100, the value at which the median income family can afford the median priced home. 1While the weaknesses are clear, how severe will this housing market slump be? Looking at home sales again, 2006 will likely be the third best in history, with sales dropping below only 2004 and 2005 levels, but standing higher than 2003. In fact, 2006 home sales will likely rise 25% above their level at the beginning of this decade. Homeowners will certainly not appreciate future declines in their home values. However, the vasst majority of them have already realized enormous gains in the equity of their homes. For example, the Federal Reserve reports that net home equity extraction reached well over $700 billion in 2005, compared with an annual average ofjust under $200 billion between 1991 and 2004. Moreover, total residential net worth (i.e., the difference between the value of owner- occupied real estate and outstanding home mortgages) has nearly tripled since 1990, rising from $4 trillion to almost $11 trillion. While the recent rise in mortgage rates.has been pronounced, interest rates are still low by historical standards, and it seems that they will not change dramatically in the near future as the Fed appears to be on hold regarding further interest rate hikes. So much for those with fixed-rate mortgages.. But what about those holding adjustable-rate mortgages (ARMs)? ARM interest rates are tied to short-term rates and tend to increase much faster than the fixed-rate category, especially for homeowners who acquire mortgages with teaser rates. To this point, recent Mortgage Bankers Association (MBA) data show an increase on the delinquency rates for both prime and subprime mortgages, with the increase driven primarily by ARM delinquencies. Specifically, prime ARM delinquency rates rose from 2.19% in the second quarter of 2005 to 2.70% in the same quarter this year. Even more troubling, subprime ARM delinquency rates'jumped from 10.0% to 12.2% in the same period. Similarly, new foreclosure rates rose to 0.43% in the second quarter of this year from 0.39% a year ago, driven by a rise in subprime mortgages (up from 1.26% to 1.79%), a large share of which are ARMs. It's important to realize that while some homeowners will suffer the brunt of higher interest rates, a large majority won't be affected, as only about a fifth of outstanding loans are financed with ARMs. Furthermore, only a portion of those loans are subprime and therefore most susceptible to interest rate changes. To put it in perspective, about 60% of subprime loans are ARMs, compared with less than 20% for prime mortgages. Consequently, broad indicators of the quality of the mortgage market appear to be sound by. historical standards, including the loan-to-value ratio, which this year will be about 76%, just about the average since 1990. So what can be expected of the housing market for the next year or so? If we are correct that interest rates are near their cyclical peaks and job and income growth will remain subdued but positive, we believe that the market-both sales and starts-will stay weak for the remainder of this year and the first part of next year before beginning a slow recovery. Residential investment as a share of GDP will likely continue to drop from a high of 6.3% toward its long- term average of about 4.0%. Home prices in real terms will probably drop this year and in early 2007. However, considering the outstanding run-up in home prices since the late 1990s (right through the 2001 recession), such declines will not be catastrophic. Overall homeowner wealth will be protected by the fact that most outstanding loans are prime mortgages with fixed interest rates. Nevertheless, those geographic areas that have experienced super-normal home price appreciation, such as Florida, California, and Arizona, and were also overexposed to exotic option-ARM financing will be subject to a much more severe adjustment process. Originally published Nov. 06. Reprinted by .permission uschamber.com Dec. 06. Copyright 2006, U. S. Chamber of Commerce I lAR T N G A NE\ (COURSE If you are thinking of a 2nd home or An Investment in your Future consider Real Estate in Our Area Mexico Beach, Port St J6e, Cape San Bias, Florida We are a full service Real Estate Agency With two offices to serve you Port St Joe, FL 1-866-418-6100 or. Mexico' Beach, FL 1-888-385-1844 We also do Vacation Rentals! 1 BAY ANTIQUES l J|l Port St. Joe ' Original Art, Antiques, Curios 301 Reid Avenue 9 850-229-7191 0 S Thursda Friday & Saturday Thursday, Friday & Saturday DECEMBER 2006 VOLUME 4, ISSUE 12 BU INCS AFTER HOURS Dedication Ceremony Alfred I. DuPont Florida History & Genealogy Center b, h r r Le, L Jr. and Robert Nedley before unveiling ( ~ ri~, r .~ 4>. ~- Steve Meadows, State Attorney and Jim Norton, Chamber President Sponsored by Coastal Chamber of Commerce Community Bank, Sunset Coastal Grill & Gulf County Dead Lakes Kecreation I'ark KFbbon Iutrlng Urand Re-opening George Lore delighted large group with early history of the Health Dept. WIWW.GULFCHAMBE R.ORG PAGE 6 PAGE DECEMBER 2006 VOLUME 4, ISSUE 12 Please get all upcoming events and ribbon cuttings to the Chamber by December 11th. Grand Opening & Ribbon Cutting for Billy Bowlegs Grog & Grill ^ISI~~~tfe ^ 1 :, Chamber members and friends enjoy music and fantastic food. I I 1,1., ,' .) I f 1 4_Q 4%, R. r : 11 (.) 0,\ T r ----------------- -- PARADE ENTRY FORM I S ..: .. : : i d,, proceeding north on SEhIIR DEADLINE iS No. 310 2006 S .T'.hi I I. J.. S :... Fax : I Email address: What are you entering? S a ePlease circle one: Band of members ___ I i ...;I ,,d ',,[,, .. Please return entry form to: Gull County Chamber ol Commerce S P.O. Box 964 I PaPort St Joe, FL 32457 Or bring to: Chamber Office at 155 Capt. Fredh Place (formerly 4th SL) I I 227-1223 - -- --e ---- r-------------------------------- i Boat Registration I Name I Address i Phone Cell ___ Name of Boat Length Power or Sail? Require slip? Will you require a generator? Need help finding one? Please return registration to: I Gulf Counly Chamber of Commerce 155 Captain Fred's Place, Port St. Joe, FL 32456 For more information call: 00-239-9553 227-1223 I For Judging Use Only . Slip I Line up Placement Notes: 1. -- ----- -- -- --J November 28 Lulu's Sweet Expectations First Anniversary Celebration 5:00 7:00 p.m. EDT Port City Shopping Center November 29 Front Porch Bed & Breakfast Grand Opening/Ribbon Cutting 5:00 8:00 p.m. CT Wewahitchka November 30 Business Before Hours Sponsored by Gulf County Senior Citizens Grandma's Kitchen 8:00 p.m. 0:00 p.m. EDT Music by the Bay -Wonderful music in a relaxed setting. Come join us on the porch of The Thirsty Goat (Port Inn), Port St. Joe, for great local music, delicious food and beverages. Starting time is 7:00 p.m. EDT November 30: Sponsored by Farnsley Financial Musical Entertainment by John Mazzanovich December 1 Agape Animal Center Grand Opening/ Ribbon Cutting 1336 Hwy 22 Wewahitchka Aline's Merle Norman Studio Christmas Open House 315 Williams Ave. 9:00 a.m. 5:00 p.m. Christmas on the Coast Tree Lighting Ceremony 5:30 p.m. Stage Area Frank Pate Park December 2 - 5K Reindeer Run 9:00 a.m. Corner of Williams & 4th St. Lighted Christmas Parade 6:00 p.m. Reid Ave. Pictures with Santa Stage area Frank Pate Park After Parade/Before Boat Parade" Lighted Boat Parade 7:30 p.m. St. Joseph Bay December 5 A & A HomeCare Christmas Open House- 4:00 6:00 CDT Wewahitchka December 15 Main Stay Suites Grand Opening/Ribbon Cutting 4:00 6:00 p.m. Hwy 98 Next to Gulf-Franklin Center PAGE 8 DECEMBER 2006 VOLUME 4, ISSUE 12 -i. . 'l ' ; : '- ", .-., -'' ,? :. - ;- ^ '' ,+,- :_ 2 '2 . --' .-' '* '' '-I . ;_- 1..i--._ I t t .. .* ..-* ^ '' .* -. -.--* '** .. -. '* - DECEMBER 2006 VOLUME 4, ISSUE 12 .. .. Historic Downtown Port St. Joe, Florida December 1-2, 2006 SchediLde of Events All Times Eastern) Friday, December 1 5:30 RIM. Tree Lil,,htiri, Cercmony Candieli,.ht and Caroling Frank Pate Park Saturday, December 2 9:oo A. N4. 5K Reindeer R,,in Long-,zleeved shirts to the I st 100 entraqts' Registration will begin at 8:00 A.,'-,I Comer of V'illiams ,AvenLie & 4th Street 6:00 P.M. Christil"as Parade lZr-id Avenue Ji-inior Service League v"111 Sponsor Picalres vidn anta In Frank Pate Park after the Lighted ("]-iristmas Parade 7: 3 0 P. N4, Boat Parade St Ioseph Pay Come browse (be da77jing array of uniqLie shops and stores in Hi,toric Downto\vn Port St. joc dtiring this 2-da" event PAGE 9 THE APPLIANCE SOLUTION ELECTRIC & GAS APPLIANCES Kitchen Appliances / Grills / Gas Logs / Space Heaters / Fireplaces Chimeneas / Gas Lights / Home Generators / Culinary Center STEPHEN SHOAF wshoaf@theappliancesolution.com 303 Long Avenue Port St. Joe, FL 32456 tel 850.229.8217 ext. 210 cell 850.227.4091 fax 850.229.8392 Brian Robinson Assistant Vice President SuNTRUST MORTGAGE 1 I \F\1 ( flU lt\r( A Nrw S (oiwiF Ii SunTrust Mortgage, Inc. 9722 Front Beach Rd Panama City Beach, FL 32407 Tel 850.230.6684 Cel 850.866.0071 Fax 850.230.0242 Toll Free 888.669.7263 brian.robinson@suntrust.com Carolyn Chapman Holman B.S., M.S., J.D. REALTORC" Cell: 850-867-0371 or 619-916-8420 Office: 850-229-6100 Fax: 850-229-6101 Toll Free: (866) 481-6100 Email: carolynholman@BlueWaterRealty.net Web: 155 West Highway 98, P. 0. Box 218, Port St. Joe, FL 32457 ANi otgraphy H, PA Al i, Your membership benefits ... Asking So the Answer's Yes Property Tax Increases Hurting Business and Jobs Florida's property tax crisis, characterized by double-digit property tax increases, is limiting job creation and negatively impacting Florida's business climate. In a recent Florida Chamber survey of the business community: Ninety-seven percent said their property taxes have increased, Of those, 81 percent had increases of more than 10 percent and 67 percent indicated increases greater than 20 percent, Eighty-four percent said property taxes are increasing more than their revenues, and Many said they have had to make significant changes t -gach as price increases, hiring freezes and office closures to cover the increases. There are many proposals attempting to address this issue, but they tend to focus on the symptoms rather than the problem. The bottom line is that local government ",*spending is out of control. Statewide, skyrocketing propernr values are giving local governments millions more to spend each year and have led to tax increases paid for by ,businesses. Even with this huge revenue windfall, tax reductions by local government have been minimal to non-existent. Some local government officials are playing a shell game they say they are lowering your -axc s but they are actually collecting more in revenues because of increasing property values. (The "rate" may be lower but you are paying more.) Local governments claim they need the additional revenue to cover increasing costs for insurance. energy, and the new minimum wage. Rahcir than adjusting their budgets to reflect increased costs like businesses do when faced with the same cost increases, they are sending the bill to you. If we can cut back to balance our b local governments? For the business property tax increases are burdensome by the shift burden to business owner ,time homebuyers, and residences whose proper are not capped. In 2005 19 percent higher prope cover out-of-control sp governments while the S amendment limits resides increases to just three per Cha for prove tax busit inclh to: go 0 mord for prop and reigr Please joining s fight to Frank Ryl, r., ann proc and Cap property local government at growth a condition of participating sharing. h Florida can'tber afford t property taxes slow job diversification of our eco work together to redu tax burden on the busi Please join the Florida fight to bring equity and government spending an Frank Ryll, Jr., P Chamber of Commerce Copyright C 2006 A Florida Chamber of Com udgets, why can't By Craig Harrison Many times in your life you will community, the make requests of others: to join a group, made even more committee or team, to perform a task or to fting of the tax assist with a project. This month's question: ers, renters, first- How do you make the ask? Often the key those changing to getting to "yes" involves.how you make :ty tax increases your request. , businesses paid Whether you are building aboard of arty taxes just to, directors, forming a committee, enrolling ending by local others in your team or workgroup, seeking ;ave Our Homes volunteers for a project or anything else that ntial property tax involves asking others to do what you want cent. them to, follow these 10 tips to hear those The Florida magic words: "YES, I'd be glad to!" mber is fighting Making "The Ask": legislation to 1. Phrase your request in terms of the 'ide property benefits to the listener. Speak to "what's in relief to Florida it for them." Why will they benefit from nesses. This saying yes to your request? ides legislation 2.Bepositive.Don'tfocus on why someone shouldn't say Hold local yes or the negative aspects of v e r n m e n t s their accepting your request. e accountable Focus on the positives. Will extraordinary the experience be fun? High erty tax increases profile? Build new skills? Lead require them to to a promotion? Add to one's n in their growth resume? Give all involved a g i pending, sense of accomplishment and * Revise TRIM satisfaction? Will it make the ith in Millage) world a better place? Focus on positives. -equire online 3. Show respect and appreciation ouncement of for your prospect. When you recognize erty tax increases, their skills, past track record, personality or other qualities they in turn feel special. tax increases' by It's flattering and affirming to be asked to h plus inflation as participate. ig in state revenue 4. Give accurate and clear expectations of what the position or role requires. It's o let skyrocketing tempting to tell people what they want growth and the to hear, or only emphasize what is easy nomy. We must or fun or undersell the time commitment ce the property required. Don't! Give a fair explanation of ness community. your request. You don't want them agreeing Chamber in the under false pretenses. accountability to 5. Make sure to listen to the issues d property taxes. or concerns of the listener. What are they 'resident, Florida worried about? How will they base their decision? Strive to understand their needs, l Rights Reserved their fears and their constraints. merce he or she is able to. 10. Thank them either way for their time and willingness to consider your offer. By treating them with respect and care, they are more likely to say yes in the future.!" Author Craig Harrison is a professional speaker corporate trainer and founder of Expressions Of Excellence! which provides solutions through speaking. Contact Harrison at (510) 547-0664 or through craig@craigspeaks.com or www. ExpressionsOfExcellence.com. PROSPERITY BANK Baildd' Oaur Caw iwty TONYA D. NIXON Senior Vice President/Business Development Officer P.O. Box 609 (850) 227-3370 528 Cecil G. Costin, Sr. Blvd. Fort St. Joe,-FL 32457' Fax (850) 227-3396 wnw.prosperirtbank.com TNixoh@prdspeftiybank.com' MemberFD FDIC M LAiLCH REAL t ci U U.I Vft it tw 4975-A Cape San Bias Rd. Port St. Joe, FL 32456 Office Fax: 850-227-9111 10U HAKE THE CALL tw l a* tuW Nrs DECEMBER 2006 VOLUME 4, ISSUE 12 PAGE 10 DECEMBER2006 VOLUME 4, ISSUE 12 Difference Makers: Everyone Matters - Everyone Makes A Difference By Mark Sanborn, CSP, CPAE I don't think everyone knows that. Most people grew up being told they could make a difference, not that they do make a difference. As a result, some people believe they can choose to be neutral. Making neither a appositive not a negative difference. In practice, that just isn't so. Have you recently encountered a person who didn't seem engages? Perhaps he or she seemedwrapped up in his own private worked, and you were left with the impression that you weren't important enough to gain admittance. Don't you hate to be ignored that way? If you were to press that person, he might tell you he was simply being "neutral!" He might not have been helpful or interested 'in you, but he wasn't doing you any harm. To me, that kind of rationalization is akin to the bystander at a mugging who chooses not to get involved. The fact is he has acted, in this case negatively, by not getting involved. In practical terms, neutrality is a myth. The greatest insult in business or in life is indifference. You can't engage the world in a meaningful way by being "neutral". The perception on the part of others will be that they don't matter enough for you to engage with. My point is that everyone makes a difference. The choice we all have is whether we want to make a positive difference or a negative one. The important question isn't, "Did you make a difference today?" The important question is, "What kind of difference did you make?" For instance, have you made a positive or a negative difference to: Your client or customer, who was in a pinch and needed immediate attention? Your son or daughter, who wanted you to read to him or her when you were busy preparing for the next business day? The stranger on the way to work who said good morning to you without getting a response? The positive or negative impact you have on each person above varies only in magnitude. The principle is: the same. When you'choose not to make a positive difference, you almost always make a negative Our actions and- behaviors matter more than we realize. What we choose to do can improve, even if only in some small way, the quality of another person's day or life. Are you building a resume or a legacy? Our culture is obsessed with success. We assume that if we become really good at what we do, we will earn the material benefits and accolades that come with success. But Richard Halverson, former chaplain of the U.S. Senate, points out that our goal in life. shouldn't be just to "be good," but rather to "be good for something." If that "something" is limited to merely personal success, our impact on the world around us will be limited. To put it another PAGE 11'. EMPLOYERS: Plori as minimum wage is $6.67 per hour effective- January 1, 2007 for all hours worked in Florida. Employers must pay their employees a wage not less than the amount of the hourly state minimum wagefor all hours worked in FL. .The definitions of "employer," "employee," and "wage" for state purposed are the same as, those established under the federal Fair Labor Standards Act (FLSA). For "tipped employees" meeting eligibility requirements for the tip credit under the federal Fair Labor Standards Act (FKSA), employers must pay a direct hourly wage of $3.65 as of January 1, 2007. Beginning in 2007, each employer who must pay the Florida minimum wage must prominently display a poster. (at least 8.5" x 11") in a conspicuous, accessible place to employees. The poster can be downloaded from the Agency for Workforce Innovation's website at :. floridjobs.org/resources/flmin_wage.html. Because the Florida minimum wage does not apply unless the employee would first be entied to the federal minimum wage, a Florida employer required. to pay employees the federal minimum wage must post both. the .federal poster and the Florida poster. The federal posters can be downloaded from the USDOL v.ebsiteat: hrrp://\ww.dol.go\ /lsa/regs/ compliance/posters.flsa.htm., IUKJh 4LEU 2775 Garrison Ave Port St Joe, FL 32456 (850) 227-3285 Located at the comer of Garrison and Madison Ave, next to the Health Department 190 Lightkeepers Drive St Joe Beach, FL (850) 647-3285 Located across from Beacon Hill Park offof Hwy 98 * Physical Therapy * Massage Therapy (MA29475) * Certified Personal Trainer on site and by appointment * Personalized Exercise Plans * Body Master Equipment * Cardiovascular Programs ; Wide Variety of Exercise Classes * Hot New Tanning Beds and Tanning Lotions * Nutritional Supplements * Daily, Weekly, & Monthly Rates For All Our Snowbird Friends, &X Other Out Of Town Guests * Fitness Classes Now Being Offered -J,^ ii.-',l ..yA- -k. ... 1 1 '1 f \ .i i f. ^... ., t- .. 'Ad Cost B&W Per Issue 1 6 12 . | BACK PAGE.......-$260 --.... $210 .-. -$185.. FI LL PAGE --- -$210 .....--$160 -- -$150. SHALF PAGE .--...$130 -... 110 -$90- QUARTER.PAGE. -- $75- .... $60--.. -$50- BUSINESS-CARD- ..-. $45 ..- $35 $30- Color is an additional $50 aer Issue S AD SIZES I Back Page 9.75" Wide X 9.5" Tall Full Page 9.75" Wide X 11.5" Tall Half Page 9.75" Wide X 5.625" Tall Half Page 4.7917" Wide X 11.5" Tall Quarter Page 4.7917" Wide X 5.625" Tall Business Card 3.1389" Wide X 2" Tall., Fun Fitness for Kids Children's ballet/jazz a8 creative play classes Children's B-Day Parties -* We Now Offer Parent's Night (call ahead to reserve your spot) . <* 1* *I. -**l*, I q ; I I f If *-* ,( l.t ', l l ( t i 1 \ l 1 ..* DECEMBER,2006 ',VOLUME'4, ISSUE 12 SDeveloper FL KV 's Closeout on Old Inventory Welcome to Century 21 G(ulf Coa~t Realty anrid Florlda's ino.tI drcl ire-able (c.oa tilne. As 4 native of Port St. Joe and this area'b only third-pgenerations realtor. I can help you find ainy property arid will give yu OLy beet advice On selling your pfrOoerty. Call me. Jay Rish : Broker Oirner Wholesale Price on Lots and Developable Acreage, and Entitled Projects in and around Gulf County, Florida -------------------------------- Bayfront ------------------ Waterfront Inland Properties ------------- Commercial Property ---------- Call Jay Rish for details: 850-227-5569 No Reasonable Offer Refused jay@c21 gulfcoastrealty.com Possible owner financing on some properties A Pr..a~I ~na G-F l pofIMdl ruulIlIIII ul u The Gulf County Chamber Of Commerce CHAMBER OF COMMERCE CHAMBER OF COMMERCE NON PROFIT ORG PRSTD STD US POSTAGE PAID Port St. Joe, FL Permit #180 LL7-IZZJ 800-239-9553 ' . 155 Cap Port St. it. Fred's Place Joe, FL 32456 I ''BER-0RG PAGE '12 "----'R S Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2011 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Powered by SobekCM
http://ufdc.ufl.edu/UF00028419/00929
CC-MAIN-2017-34
refinedweb
22,155
65.01
Python’s GIL — A Hurdle to Multithreaded Program Impact of Python’s GIL on multithreaded program explained! Threads are a common programming construct. A thread is a separate flow of execution. This means that our program will have two things happening at once. In Python, by default programs run as a single process with a single thread of execution; this uses just a single CPU. It’s tempting to think of threading as having two (or more) different processors running on our program, each one doing an independent task at the same time. That’s almost right. In Python, the threads may be running on different processors, but they will only be running one at a time. Python’s Global Interpreter Lock (GIL) CPython (the standard python implementation) has something called the GIL (Global Interpreter Lock); the GIL prevents two threads from executing simultaneously in the same program. The Python Global Interpreter Lock or GIL, in simple words, is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter. The GIL limits parallel programming in Python out of the box. Since the GIL allows only one thread to execute at a time, even in a multi-threaded architecture with more than one CPU core, the GIL has gained a reputation as an “infamous” feature of Python. (Refer here to know more about it) In this article we’ll learn how the GIL affects the performance of our multithreaded Python programs. Because of the way CPython implementation of Python works, threading may not speed up all tasks. Again, this is due to interactions with the GIL that essentially limit one Python thread to run at a time. Problems that require heavy CPU computation might not run faster at all. This means that when we reach for threads to do parallel computation and speedup our Python programs, we will be solely disappointed. Let’s use a naive number factorization algorithm to perform some computation intensive task. def factorize(number): for i in range(1, number + 1): if number % i == 0: yield i>>> list(factorize(45)) [1, 3, 5, 9, 15, 45] Above method will return list of all the factors of the number. Factorizing a set of numbers in serial takes a long time. from time import timenumbers = [8402868, 2295738, 5938342, 7925426] start = time() for number in numbers: list(factorize(number)) end = time() print ('Took %.3f seconds' % (end - start))>>> Took 1.605 seconds As above, executing serially took ~1.6 secs. Using multiple threads to do above computation would make sense in other languages because we can take advantage of all the CPU cores. Let’s try the same in Python and log the time again. from threading import Threadclass FactorizeThread(Thread): def __init__(self, number): super().__init__() self.number = number def run(self): self.factors = list(factorize(self.number)) Above code will create a thread for factorizing each number in parallel. Let’s start a few threads to log time of computation. start = time() threads = [] for number in numbers: thread = FactorizeThread(number) thread.start() threads.append(thread)# wait for all thread to finish for thread in threads: thread.join() end = time() print('Took %.3f seconds' % (end - start))>>> Took 1.646 seconds What’s surprising is that, it took even longer than running factorize in serial. This demonstrates the effect of the GIL on programs running in the standard CPython interpreter. Therefore it’s not recommended to use multithreading for CPU intensive tasks in Python. (multiprocessing is the fair alternative) Having said that, we should not treat GIL as some looming evil. It’s a design’s choice. The GIL is simple to implement and was easily added to Python. It provides a performance increase to single-threaded programs as only one lock needs to be managed. Removing GIL would complicate the interpreter’s code and greatly increase the difficulty for maintaining the system across every platform. If not for CPU intensive tasks, Python threads are helpful in dealing with blocking I/O operations including reading & writing files, interacting with networks, communicating with devices like displays etc. These tasks happen when Python make certain types of system calls. Tasks that spend much of their time waiting for external events are generally good candidates for threading. Key Highlights: - Python threads can’t run in parallel on multiple CPU cores because of the global interpreter lock (GIL). - Use Python threads to make multiple system calls in parallel. This allows us to do blocking I/O at the same time as computation.
https://medium.com/python-features/pythons-gil-a-hurdle-to-multithreaded-program-d04ad9c1a63
CC-MAIN-2021-49
refinedweb
755
64.61
Jitendra Nath Pandey created HDFS-13074: ------------------------------------------- Summary: Ozone File System Key: HDFS-13074 URL: Project: Hadoop HDFS Issue Type: New Feature Components: hdfs Reporter: Jitendra Nath Pandey Assignee: Jitendra Nath Pandey This jira splits out the Ozone's Key Value namespace out of HDFS-7240, leaving that jira to focus on the block layer Hadoop Distributed Storage Layer (HDSL). HDFS-10419 focuses on the traditional hierarchical namespace/NN on top of HDFS while this jira focuses on a flat Key-Value namespace call ed Ozone FS on top HDSL. [~owen.omalley] suggested the split in HDFS-7240 in this comment. Ozone provides two APIs: * A KV API * A Hadoop compatible FS (Haddop FileSystem and Hadoop FileContext), on top of KV API. Ozone FS serves the following purpose * It helps test the new storage layer (HDSL) * It can be directly used by applications (such. Hive, Spark) that are ready for cloud's native storage systems that use a KV namespace such as S3, Azure ADLS. Ozone's namespace server scales well because of following reasons: * It keeps only the working set of metadata in memory - this scales the Key-Value namespace. * Ozone does not need to keep the equivalent of the block-map; instead the corresponding container-to-location mapping resides in in the SCM - this leaves additional free space for caching the metadata. This benefit is also available to NN that adapts to the new block-storage container layer as explained in Evolving NN using new block container layer attached in HDFS-10419. * It does not have a single global lock - this will scale well against a large number of concurrent clients/rpcs. * It can be partitioned/sharded much more easily because it is a flat namespace. Indeed a natural partitioning level is the bucket. Partitioning would further scale the number of clients/rpcs and also the Key-value namespace. -- This message was sent by Atlassian JIRA (v7.6.3#76005) --------------------------------------------------------------------- To unsubscribe, e-mail: hdfs-dev-unsubscribe@hadoop.apache.org For additional commands, e-mail: hdfs-dev-help@hadoop.apache.org
http://mail-archives.apache.org/mod_mbox/hadoop-hdfs-dev/201801.mbox/%3CJIRA.13134186.1517027971000.53992.1517028001848@Atlassian.JIRA%3E
CC-MAIN-2020-45
refinedweb
342
52.09
A common way of representing small integers in pure object-oriented languages is by storing them inside a pointer. Pointers to objects, in most implementations, will be word-aligned. Even on a 16-bit system, a word is two bytes, and so pointers will always have their low bit, or low bits, set to zero. Small integers can be stored in the remaining bits. On a typical modern system, this provides 31-bit or 63-bit integers. If we use the top bit to represent the sign, this gives a minimum range of around two billion, centered on zero; more than enough for a large number of programs to be able to avoid the need for boxed integers. Unlike low-level languages, such as C, where integer overflow can cause undefined results or wrap around, object oriented languages tend to treat integers as arbitrary-precision numbers. Any integer operation with a result which does not fit in a small integer is expected to be silently turned into a real object. This short essay describes efficient addition and multiplication routines for use with small integers implemented in this way. These algorithms are used in LanguageKit. Note that this is not peer-reviewed. I would be very surprised if I am the first person to invent this technique, but to my knowledge I am the first to document it. I have done so in the hope that future language implementers do not have to. The canonical mechanism for adding two small integers together is, in C-like pseudocode: a >>= 1; b >>= 1; c = a + b; { Check for overflow } return (c << 1) | 1; Checking for overflow is typically done by seeing if the sign bit on a flipped. Note that this only checks for 32-bit overflow. We also need to check whether the result will fit into a 31-bit small integer, because the lowest bit is reserved for the flag indicating that this is not an object pointer. A lot of comparisons are needed to determine this. The other problem with this approach is that it performs three shifts. This has recently become a problem. Shifts are very uncommon in most programs. Until around 2000, most shift instructions were generated by compilers, which optimised constant multiplies into a sequence of shift and add operations. When hardware multipliers reached a certain level of performance, this became slower. Now, shifts are very uncommon instructions and so CPU manufacturers no longer focus any effort on making them fast. A modern CPU can frequently perform two multiplies while it performs a single shift. It turns out, it is possible to add two small integers without needing any shifts, using this approach: b = b & ~1; return a + b; The first line clears the low bit on b, and the second line adds the two together. The two low bits will therefore be 0 and 1, respectively. Adding these together gives 1, setting the low bit on the result. This translates into, at worst, two loads, a bitwise and, an add, and a store operation; five CPU instructions for the entire operation. The main advantage in this version, however, is that we are now performing 32-bit adds. This means that the result will always overflow when the result will not fit into a small integer, and will only overflow when the result will not fit into a small integer. Testing for overflow is now a simple matter; just check the carry or overflow flag in the CPU. Note that subtraction can be implemented in exactly the same way, by negating the second operand. This does not add any overhead; the bitwise and operation can be replaced with a bitwise exclusive-or and will simply toggle the top and bottom bits (the sign bit and the small integer flag). Because the second operand is still a constant, it will exactly the same number of instructions. Multiplication is similar, but slightly more complicated. When multiplying two small integers, we are effectively dividing both by two, then multiplying them together, then multiplying them by two and adding one. The first obvious thing to notice is that we can get rid of the multiply at the end if we also remove one of the divides, because multiplication is commutative: (a / 2) * (b / 2) * 2 + 1 = a * (b / 2) + 1 It is not quite this simple, of course, since the division by two is an integer division which rounds downward, and small integers always have the low bit set. We can still eliminate the multiply (the left-shift) as long as we replace the divide (the right-shift) with a bitwise and operation clearing the low bit. This leaves something a lot like this: a = a & ~1; b >>= 1; return a * b + 1; The low bit in this will always be cleared, because the low bit in a is 0, and so the result of multiplying the low bit in b by it will always be 0, with no overflow (and therefore no impact on the rest of the result). Adding 1 at the end sets the flag indicating that this is a small integer. Once again, the multiplication will cause a 32-bit overflow if, and only if, the result will not fit in a 31-bit value. This is very important, because without hardware overflow checking the only reliable way of determining if a multiply has overflowed is to perform it at double the required word size (e.g. 62-bit for a 32-bit system with 31-bit small integers) and then see if the result will fit in the real word size, which is very costly. Using these two algorithms, LanguageKit achieves good performance on integer arithmetic and provides transparent overflow, whereby any arithmetic operation with a result that does not fit into a small integer is transparently promoted to an arbitrary-precision integer object.
http://www.cl.cam.ac.uk/~dc552/unreviewed/SmallInt.html
CC-MAIN-2014-42
refinedweb
978
57.91
09 March 2011 14:29 [Source: ICIS news] TORONTO (ICIS)--Dow Chemical and ?xml:namespace> The fluids are used in transformers and other electrical applications. ,” said Tim Laughlin, general business manager of Dow’s wire and cable business. Under a non–binding letter of intent, Dow may obtain up to 20m gallons of Solazyme’s oils for use in dielectric insulating fluids and other industrial applications in 2013 and up to 60m gallons in 2015, the companies added. Financial terms were not disclosed. Last year, San Francisco-based Solazyme said the US Navy bought 1,500 gallons of its algae-based jet fuel for testing as part of an effort to run 50% of the Navy’s fleet on renewable fuels by 2020.
http://www.icis.com/Articles/2011/03/09/9442329/dow-chemical-and-solazyme-plan-to-develop-algae-based.html
CC-MAIN-2014-35
refinedweb
123
60.85
Last modified: January 04, 2012 Applies to: SharePoint Server 2010 In this article About InfoPath Forms Services Topics and Resources InfoPath Forms Services Namespaces Inf Forms Services requires a server capable of running SharePoint Server 2010, and a license to access the form publishing and rendering functionality. Here are some points to quickly familiarize you with the capabilities of InfoPath Forms Services: There is a subset of InfoPath 2010 features that do not work in the browser. For more information, see the Design-Once Feature Compatibility topic. Designing form templates with custom code, or those without custom code but needing Full trust, requires Administrator deployment. While Domain trust form templates without code can be directly published and are immediately available on a SharePoint site, form templates with custom code require additional steps in order to work as browser-enabled forms. For more information about deploying a form template with code, see How to: Deploy Form Templates That Contain Form Code That Requires Full Trust. Forms work on a variety of Web browsers on multiple platforms. Start with the Developing and Deploying Form Templates for InfoPath Forms Services topic. After you have an InfoPath form template working in the browser, you may want to create one that has custom code. To learn more about deploying a form template with code, see the How to: Deploy Form Templates That Contain Form Code That Requires Full Trust topic. To create a custom Web Part page that can host an InfoPath form in the InfoPath Form Web Part, see Working with the InfoPath Form Web Part To create a custom Web page that can host an InfoPath form, see Authoring Custom Web Pages That Contain the XmlFormView Control. To migrate InfoPath 2003 form templates for use with InfoPath Forms Services, see Migrating an InfoPath 2003 Managed Code Form Template. For a list of step-by-step topics covering a variety of scenarios, see How Do I...in InfoPath Forms Services. For more articles and resources for learning about InfoPath and InfoPath Forms Services, go to the InfoPath Developer Portal and the InfoPath Forms Services Resource Center on MSDN. InfoPath Forms Services provides an object model that contains three namespaces: The classes and members of the Microsoft.Office.InfoPath.Server.Administration namespace enable developers to automate form template administration from code running on the server. The Microsoft.Office.InfoPath.Server.Controls namespace contains the XmlFormView class and its associated classes that provide an ASP.NET control used for rendering a browser-compatible form template in a custom Web page on the server. The classes and members of the Microsoft.Office.InfoPath.Server.Controls.WebUI namespace implement and support the InfoPath Form Web Part.
https://msdn.microsoft.com/en-us/ms540731
CC-MAIN-2015-18
refinedweb
448
50.77
The AutoCompleteField widget supports the following parameters: of AutoCompleteField can be used on the same form or page. These are referenced distinctly on the form or page by the id. This is also the name of the field which is passed into the form on the server side. autocomplete values using HTTP GET request. JSON request. If specified as true it tries to interpret the returned data as JSON. (Default: fetchJSON = False) user must enter before the list is shown. (Default: minChars = 1) For example the widget is instantiated as: from tw.jquery.autocomplete import AutoCompleteField autoField = AutoCompleteField( id='myFieldName', completionURL = 'fetch_states', fetchJSON = True, minChars = 1) Once the Widget is instantiated it can be added to an existing form: from tw.forms import TableForm myForm = TableForm(id='myForm', children=[autoField]) This form is of course served up to the user via a controller method like this: @expose('mypackage.templates.myformtemplate') def entry(self, **kw): pylons.c.form = myForm return dict(value=kw) And your template form would display your form like this: ${tmpl_context.form(value=value)} And here is the resulting field when viewed from a browser: The template generates the necessary javascript code to fetch values from the controller using the completionURL. The controller code for generating the json response would be something like: @expose('json') def fetch_states(self): states = ['ALASKA', 'ALABAMA', 'ARIZONA', ..........., 'WYOMING'] return dict(data=states) The method should return a dictionary with data as key and a list as value. In this example the list is populated manually. The list would, in most cases, be obtained from a database. Here is how you retrieve data from the form once it has been submitted by the user. Notice that this is not any different from how it is normally retrieved from forms.: def retrieve(self, **kw): do.something() return dict() We add a @validate decorator to the data retrieval function which redirects us back to the original form if the user enters something that does not match that which is in our list. @validate(myForm, error_handler=entry) def retrieve(self, **kw): do.something() return dict() and here is what the widget looks like when the validation fails: Todo Difficulty: Medium. document the answer to this question: What about if someone is using this widget for a select field, and the value they want returned is the value of the id of an object of select values in a database?
http://www.turbogears.org/2.1/docs/main/ToscaWidgets/Cookbook/AutoComplete.html
CC-MAIN-2014-15
refinedweb
402
54.93
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards Boost.MPI provides an alternative MPI interface from the Python programming language via the boost.mpi module. The Boost.MPI Python bindings, built on top of the C++ Boost.MPI using the Boost.Python library, provide nearly all of the functionality of Boost.MPI within a dynamic, object-oriented language. The Boost.MPI Python module can be built and installed from the libs/mpi/build directory. Just follow the configuration and installation instructions for the C++ Boost.MPI. Once you have installed the Python module, be sure that the installation location is in your PYTHONPATH. Getting started with the Boost.MPI Python module is as easy as importing boost.mpi. Our first "Hello, World!" program is just two lines long: import boost.mpi as mpi print "I am process %d of %d." % (mpi.rank, mpi.size) Go ahead and run this program with several processes. Be sure to invoke the python interpreter from mpirun, e.g., mpirun -np 5 python hello_world.py This will return output such as: I am process 1 of 5. I am process 3 of 5. I am process 2 of 5. I am process 4 of 5. I am process 0 of 5. Point-to-point operations in Boost.MPI have nearly the same syntax in Python as in C++. We can write a simple two-process Python program that prints "Hello, world!" by transmitting Python strings: import boost.mpi as mpi if mpi.world.rank == 0: mpi.world.send(1, 0, 'Hello') msg = mpi.world.recv(1, 1) print msg,'!' else: msg = mpi.world.recv(0, 0) print (msg + ', '), mpi.world.send(0, 1, 'world') There are only a few notable differences between this Python code and the example in the C++ tutorial. First of all, we don't need to write any initialization code in Python: just loading the boost.mpi module makes the appropriate MPI_Init and MPI_Finalize calls. Second, we're passing Python objects from one process to another through MPI. Any Python object that can be pickled can be transmitted; the next section will describe in more detail how the Boost.MPI Python layer transmits objects. Finally, when we receive objects with recv, we don't need to specify the type because transmission of Python objects is polymorphic. When experimenting with Boost.MPI in Python, don't forget that help is always available via pydoc: just pass the name of the module or module entity on the command line (e.g., pydoc boost.mpi.communicator) to receive complete reference documentation. When in doubt, try it! Boost.MPI can transmit user-defined data in several different ways. Most importantly, it can transmit arbitrary Python objects by pickling them at the sender and unpickling them at the receiver, allowing arbitrarily complex Python data structures to interoperate with MPI. Boost.MPI also supports efficient serialization and transmission of C++ objects (that have been exposed to Python) through its C++ interface. Any C++ type that provides (de-)serialization routines that meet the requirements of the Boost.Serialization library is eligible for this optimization, but the type must be registered in advance. To register a C++ type, invoke the C++ function register_serialized. If your C++ types come from other Python modules (they probably will!), those modules will need to link against the boost_mpi and boost_mpi_python libraries as described in the installation section. Note that you do not need to link against the Boost.MPI Python extension module. Finally, Boost.MPI supports separation of the structure of an object from the data it stores, allowing the two pieces to be transmitted separately. This "skeleton/content" mechanism, described in more detail in a later section, is a communication optimization suitable for problems with fixed data structures whose internal data changes frequently. Boost.MPI supports all of the MPI collectives ( scatter, reduce, scan, broadcast, etc.) for any type of data that can be transmitted with the point-to-point communication operations. For the MPI collectives that require a user-specified operation (e.g., reduce and scan), the operation can be an arbitrary Python function. For instance, one could concatenate strings with all_reduce: mpi.all_reduce(my_string, lambda x,y: x + y) The following module-level functions implement MPI collectives: all_gather Gather the values from all processes. all_reduce Combine the results from all processes. all_to_all Every process sends data to every other process. broadcast Broadcast data from one process to all other processes. gather Gather the values from all processes to the root. reduce Combine the results from all processes to the root. scan Prefix reduction of the values from all processes. scatter Scatter the values stored at the root to all processes. Boost.MPI provides a skeleton/content mechanism that allows the transfer of large data structures to be split into two separate stages, with the skeleton (or, "shape") of the data structure sent first and the content (or, "data") of the data structure sent later, potentially several times, so long as the structure has not changed since the skeleton was transferred. The skeleton/content mechanism can improve performance when the data structure is large and its shape is fixed, because while the skeleton requires serialization (it has an unknown size), the content transfer is fixed-size and can be done without extra copies. To use the skeleton/content mechanism from Python, you must first register the type of your data structure with the skeleton/content mechanism from C++. The registration function is register_skeleton_and_content and resides in the <boost/mpi/python.hpp> header. Once you have registered your C++ data structures, you can extract the skeleton for an instance of that data structure with skeleton(). The resulting skeleton_proxy can be transmitted via the normal send routine, e.g., mpi.world.send(1, 0, skeleton(my_data_structure)) skeleton_proxy objects can be received on the other end via recv(), which stores a newly-created instance of your data structure with the same "shape" as the sender in its "object attribute: shape = mpi.world.recv(0, 0) my_data_structure = shape.object Once the skeleton has been transmitted, the content (accessed via get_content) can be transmitted in much the same way. Note, however, that the receiver also specifies get_content(my_data_structure) in its call to receive: if mpi.rank == 0: mpi.world.send(1, 0, get_content(my_data_structure)) else: mpi.world.recv(0, 0, get_content(my_data_structure)) Of course, this transmission of content can occur repeatedly, if the values in the data structure--but not its shape--changes. The skeleton/content mechanism is a structured way to exploit the interaction between custom-built MPI datatypes and MPI_BOTTOM, to eliminate extra buffer copies. Boost.MPI is a C++ library whose facilities have been exposed to Python via the Boost.Python library. Since the Boost.MPI Python bindings are build directly on top of the C++ library, and nearly every feature of C++ library is available in Python, hybrid C++/Python programs using Boost.MPI can interact, e.g., sending a value from Python but receiving that value in C++ (or vice versa). However, doing so requires some care. Because Python objects are dynamically typed, Boost.MPI transfers type information along with the serialized form of the object, so that the object can be received even when its type is not known. This mechanism differs from its C++ counterpart, where the static types of transmitted values are always known. The only way to communicate between the C++ and Python views on Boost.MPI is to traffic entirely in Python objects. For Python, this is the normal state of affairs, so nothing will change. For C++, this means sending and receiving values of type boost::python::object, from the Boost.Python library. For instance, say we want to transmit an integer value from Python: comm.send(1, 0, 17) In C++, we would receive that value into a Python object and then extract an integer value: boost::python::object value; comm.recv(0, 0, value); int int_value = boost::python::extract<int>(value); In the future, Boost.MPI will be extended to allow improved interoperability with the C++ Boost.MPI and the C MPI bindings. The Boost.MPI Python module, boost.mpi, has its own reference documentation, which is also available using pydoc (from the command line) or help(boost.mpi) (from the Python interpreter).
http://www.boost.org/doc/libs/1_53_0_beta1/doc/html/mpi/python.html
CC-MAIN-2015-11
refinedweb
1,395
59.09
Consuming APIs from Clojure When getting results from API calls, its very common to recieve data in JavaScript Object Notation (JSON). Once we have the JSON data, it is converted to a Clojure data structure to use the hundreds of functions in clojure.core that can readily transform the shape of that data. We can process this with the clojure.data.json library and community projects including cheshire and transit. Clojure has several ways to get any web resource, from a simple function call to slurp, via clj-http and httpkit clients. There are useful tools to help you test APIs, such as Postman and Swagger. <!– more –> Creating a project By creating a project you can keep all your code and results of executing code too. You can also just run all this code in the REPL if you wish. If you have clj-new installed, then run the following in a terminal clojure -A:new app practicalli/simple-api-client Otherwise, simply clone the practicalli/simple-api-client repository. Getting content The slurp function is a convenient way of getting content from the web, or from local files too. Slurp is defined in clojure.core so is always available in Clojure. For example, we can get a book from Project Guttenberg very easily. (slurp "") This returns the whole text of "The Importance of Being Earnest" book as a single string. Getting an API A simple scoreboard API was deployed in episodes 16 and 17 of the Clojure study group. All the API documentation is published within the website and provides an interactive dashboard to test API calls. This is provided by the Swagger library. A random score is returned by calling the game/random-score URL. This generates a random player-id and score and adds it to the scoreboard. current scoreboard can be viewed at: scores are saved into an Clojure atom, so each time the application restarts the scoreboard reset to empty. If the application is not used for 30 minutes, then Heroku will shut down the application (the application is not on an Heroku paid plan, just on free monthly credits). Using slurp the data returned from the API is placed into a string, which is not a Clojure collection (although some Clojure functions will treat a string as a collection of characters). As its a string, any special characters contained within are escaped using the ‘ to ensure the string can be processed correctly. For example, where the data returned contains a double quote, "player-name"`, then each double quote is escaped. This is adding a transformation to the data that isn't very useful. Converting to Clojure In the simple server we used clojure.data library to generate JavaScript Object Notation from a Clojure data structure, specifically a Clojure hash-map. We can use clojure.data.json to turn our JSON string into a Clojure data structure. Add clojure.data.json as a dependency to the project. Edit deps.edn and add org.clojure/data.json {:mvn/version "0.2.7"} to the :deps map. :deps {org.clojure/clojure {:mvn/version "1.10.1"} org.clojure/data.json {:mvn/version "0.2.7"}} Then add clojure.data.json to the project namespace. Edit the src/practicalli/simple-api-client.clj and require the clojure.data.json namespace (ns practicalli.simple-api-client (:gen-class) (:require [clojure.data.json :as json])) Now use the read-str function to read in the JSON data that was returned by the response as a string. Write the following function call in src/practicalli/simple-api-client.clj or start a REPL using clj or clojure -A:rebel if rebel readline is installed. (json/read-str (slurp "")) ;; => [{"player-id" "0724e6cc-5c04-4a61-b3b6-d10624feed0e", "score" 41726706} ;; {"player-id" "36b521b2-078a-4581-9705-fa54fc1e89b6", "score" 70622257} ;; {"player-id" "2e9da877-4911-4658-b964-b5684b858921", "score" 92581379} ;; {"player-id" "2c044a04-772f-41cf-a4f5-19e8e8d76e8c", "score" 4338875}] From the value returned you can see that this is a Clojure data structure. It is a vector of 4 hash-maps. This data is much nicer to work with. GET requests with clj-http or httpkit client clj-http and httpkit client are libraries that send a http request and return all the values of the http response. httpkit client uses the same API at clj-http, so the following code should work with either library. Both these libraries provide access to the full http response information using the ring approach of putting http data into a hash-map. So we can use more than just the body of the response give by slurp. As we used httpkit library to build a simple API server, then we will use httpkit client namespace as its part of the httpkit library that was downloaded when we built the simple API server (if you didnt build the server, the library will download when you run the repl for this project). Edit the deps.edn file and add the httpkit dependency :deps {org.clojure/clojure {:mvn/version "1.10.1"} org.clojure/data.json {:mvn/version "0.2.7"} http-kit {:mvn/version "2.4.0-alpha4"}} Edit src/practicalli/simple-api-client.clj and add the httpkit client namespace to the project (ns practicalli.simple-api-client (:gen-class) (:require [clojure.data.json :as json] [org.httpkit.client :as client])) Lets start with using httpkit client to get a web page, in this case the front page of the Practicalli blog. Write the following function call in src/practicalli/simple-api-client.clj or start a REPL using clj or clojure -A:rebel if rebel readline is installed. (client/get "") ;; => #org.httpkit.client/deadlock-guard/reify--5883[{:status :pending, :val nil} 0x55598167] What has happened here? client/get returns a promise, so we have to dereference it to get the value. deref resolves the promise and we get a hash-map as the result (deref (client/get "")) @ is the short form syntax for deref, its commonly used for promises, atoms, refs, etc. @(client/get "") If you were scraping the web, the :body key would give you the html from the web page (get @(client/get "") :body) As we can use a keyword as a function we can simplify the code (:body @(client/get "")) @(client/get "") ;; => {:opts {:method :get, :url ""}, :body "[{\"player-id\":\"e8603a88-379f-44a9-8e70-7c822228e8f4\",\"score\":7044673}]", :headers {:connection "keep-alive", :content-length "70", :content-type "application/json; charset=utf-8", :date "Fri, 29 Nov 2019 19:22:56 GMT", :server "Jetty(9.2.21.v20170120)", :via "1.1 vegur"}, :status 200} This gives a lot of information about the response. If we just want the JSON packet, its in the :body (:body @(client/get "" {:accept :json})) ;; => "[{\"player-id\":\"e8603a88-379f-44a9-8e70-7c822228e8f4\",\"score\":7044673}]" Creating a simple API status checker With http client we retrieve all the data of the response. In that data is a :status key that is associated with the HTTP response code, eg. 200 for response OK. The keys function in clojure.core shows all the top level keys of a hash-map. So we can use this on the response to see the available keys. (keys @(client/get "" {:accept :json})) :status is a top level key in the response hash-map, so we can use :status as a function call with the hash-map as an argument, returning just the value of :status (:status @(client/get "" {:accept :json})) Now we have the HTTP code from the :status key, we can use it to check if the API is working correctly. Create a -main function to check the status and return a message (defn -main [& args] (println "Checking Game Scoreboard API") (let [status (:status @(client/get "" {:accept :json}))] (if (= 200 status) (println "Game Scoreboard status is OK") (println "Warning: status: " status)))) The project can then be run by clj -m practicalli/simple-api-client. To use the project as a simple API monitor, you can run this command as a cron job or other type of batch process that runs regularly. Trying APIs with Postman If you are working with an unfamiliar API or one that is not self-documented with the Swagger library. Tools like Postman are a useful way to experiment with API's without having to set up any code. Summary Using slurp is quite a blunt tool and only returns the body of the request. slurp is useful for unstructured content or data you can easily work with as a string, such as the text of a website or book. The enlive library has many useful functions if you are scraping the web for content. hickory is a library for parsing HTML into Clojure data structures, so is also useful for processing HTML content. ClojureScript does not implement the slurpfunction. Using clj-http and httpkit client, we can work with the whole HTTP request and have access to the meta-data of the request as well as the body. Using clojure.data is a simple way to transform JSON into Clojure (and Clojure into JSON). Libraries such as Cheshire and Transit offer more transformation tools and may be more useful for highly nested data transformation. Once the data is in Clojure we can use all the functions in Clojure core (and community libraries) to manipulate and transform that data and run our queries and logic over them, making it really easy to get the results we are looking for. References - ring-swagger - compojure-api - extending compojure to make schema based APIs - spec-tools - Clojure/Script utilities on top of clojure.spec, including spec-swagger. - most common word from a novel - code example of using slurp to access a Project Guttenberg book. - httpkit client - with example code - clj-http library - an HTTP library wrapping Apache HttpComponents client. Project page and documentation.
https://practicalli.github.io/blog/posts/consuming-apis-with-clojure/
CC-MAIN-2021-17
refinedweb
1,633
64.71
One of the best professional decisions I ever made was switching to a dark text editor theme. I suffered from horrible headaches for years, partially caused by late night coding sessions with blindingly bright computer screens. Recently Apple implemented a dark OS theme which helps my eyes, and thinking in a command line state of mind, I was wondering if there was a way to change dark or light mode via command line…and I found out how! Switching between light and dark mode via command line is done via a boolean flag: sudo defaults write /Library/Preferences/.GlobalPreferences.plist _HIEnableThemeSwitchHotKey -bool true The good news is that switching between color preferences can be done with one command; the bad news is that you need to restart your machine for the new theme to take effect. For years I switched to dark themes on iPhone apps and text editors; I’m so thankful that Apple has afforded us this feature on laptops and desktops. Your eyes are important — protect them! Creating Scrolling Parallax Effects with CSS… Create Namespaced Classes with MooTools MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does. Many developers create their classes as globals which is generally frowned up. I mostly disagree with that stance, but each to their own. In any event…
https://nikolanews.com/mac-dark-mode-from-command-line/
CC-MAIN-2021-04
refinedweb
230
59.23
Details Description Hi I am writing an aplication that has to create XML documents on the fly for interprocess communications. The problem that I have is that the memory is not being released when I use the DOMDocument (documentType) constructor. I have played around with various different ways of releasing the memory including using the DOMDocumentType->release() method but alas no luck. I appreciate that this may not seem like a huge issue but as I am looking memory everytime I create a new document I feel that this is an issue to be resolved. I have also found a few excepts on the web talking about this issue and there also seems to be a few people who believe this issue to be a case of bad API use: .. this is followed up by a gentleman named Gareth Reakes from PathenonComputing describing that this is to do with the way that the release methods have not been called .. I do not believe him: "Nope, not a real leak. When you free the document the memory pools that were used to new things from are deleted so it cleans up all the things like the attribute list from the creation of an element." The below example shows how this is not the case. I have created the following example code thaqt fully replicates the issue including taking stats of the memory usage (RSS) after each document creation and deletion. Please note that in main() I have a commented out version of the call to create the document as this shows how the standard constructor for the domdocument creates without any memory leaks /////////////////////////////////////////// #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> // to get the xmlstring #include <xercesc/dom/DOM.hpp> #include <iostream> #include <fcntl.h> #include <unistd.h> ///////////////////////////////////////////////////////////////////// // pre decl XERCES_CPP_NAMESPACE::DOMDocument *createNewDoc(); XERCES_CPP_NAMESPACE::DOMDocument *createNewDocWithType(); int getMemorySize(); ///////////////////////////////////////////////////////////////////// int main() { std::cout << "**************** starting" << std::endl; XERCES_CPP_NAMESPACE::XMLPlatformUtils::Initialize(); for( int i = 0; i < 1000; ++i ){ //XERCES_CPP_NAMESPACE::DOMDocument * doc = createNewDoc(); XERCES_CPP_NAMESPACE::DOMDocument * doc = createNewDocWithType(); std::cout << " - Doing something with the document" << std::endl; delete doc; usleep(100000); std::cout << "* Memory (rss): " << getMemorySize() << std::endl; } XERCES_CPP_NAMESPACE::XMLPlatformUtils::Terminate(); std::cout << "**************** ending" << std::endl; return 0; } ///////////////////////////////////////////////////////////////////// XERCES_CPP_NAMESPACE::DOMDocument *createNewDocWithType() ///////////////////////////////////////////////////////////////////// XERCES_CPP_NAMESPACE::DOMDocument *createNewDoc() ///////////////////////////////////////////////////////////////////// int getMemorySize() { char fileName[64]; int fd; snprintf( fileName, sizeof(fileName), "/proc/%d/statm", (int)getpid() ); fd = open(fileName, O_RDONLY); if( fd == -1 ) char memInfo[128]; int rval = read( fd, memInfo, sizeof(memInfo)-1 ); close(fd); if( rval <= 0 ) { return -1; } memInfo[rval] = '\0'; int rss; rval = sscanf( memInfo, "%*d %d", &rss ); if( rval != 1 ) return rss * getpagesize() / 1024; } ///////////////////////////////////////////////////////////////////// Activity - All - Work Log - History - Activity - Transitions Hi, I cannot see anything wrong with your code. I have had a quick look at the implementation and that looks fine at first look. I will take a more in depth look tomorrow. Can you confirm that this happens with 2.7? Also, have you tried creating the document type via the factories in the document rather than the implementation? Does that make any difference? Cheers, Gareth Hi, I have not tried with the 2.7 implementation. Was there a specific fix for this issue in that version? I have not tried using the factories from the document class. I have had look around the header files for another way around this but I have not found one that will allow me to set the sys and pub ids as I am trying to do above. The non standard extensions in the DOMDocument header file only show a reference back to the virtual DOMDocumentType *createDocumentType(const XMLCh *name) = 0; method. If there is a more correct way to approach the document type construction through the domument API then I am willing to give it a go and feed back any results (please advise). This still does not resolve the underlying issue of a memory leak in there. Realistically there should be a way to release this object once we have finished using the document implicitly through the DOMDocument destructor/realease mecahnsim. Destroying the type when the document is in existence breaks your model of memory management. Thank you for the swift response in this matter. Sincerely Peter Suggitt Hi, >>I have not tried with the 2.7 implementation. Was there a specific fix for this issue in that version? There were many fixes in 2.7, I don't know if this was fixed. The first thing that I will have to to is try with the latest version and I was hopeing you would do that >>The non standard extensions in the DOMDocument header file only show a reference back to the ... The non standard extensions are overriden in the implementation (DOMDocumentImpl). Its not that its more correct, but it would be interesting to see if the same behaviour occurs. >>Destroying the type when the document is in existence breaks your model of memory management. This should not happen. When you set the documentType on the document, it takes resposibility for deleting it when release is called. Take a look at in DOMDocumentTypeImpl::release() (this is called from the DOMDocumentImpl::release). If you have the source code then I would suggest you put some debug in void DOMDocumentTypeImpl::release() { if (fNode.isOwned()) { if (fNode.isToBeReleased()) { // we are calling from documnet.release() which will notify the user data handler if (fIsCreatedFromHeap) } then you will see if the DocumentType is being deleted. If it is not then we are nearer to working out what is going on. >> There were many fixes in 2.7, I don't know if this was fixed. The first thing that I will have to to is try with the latest version and I was hopeing you would do that I do not have a 2.7 version available at the moment. And after taking a while to get the 2.6 version running (had to download some extra source code for compilation) I would rather not. Do you have a verion of 2.7 that this test app (see attachment) can be run against? I take it this is something that you will be looking into? (The above comment suggests that you may we waiting for some confirmation from me). Based on the code i have supplied can you suggest an alternative approach to the construction beyond the following: XERCES_CPP_NAMESPACE::DOMImplementation *imp = XERCES_CPP_NAMESPACE::DOMImplementation::getImplementation(); // create the document type and the doc XERCES_CPP_NAMESPACE::DOMDocumentType *type = imp->createDocumentType( tName, pub, sys ); XERCES_CPP_NAMESPACE::DOMDocument *tmp = imp->createDocument( NULL, name, type ); I do not actually see an alternative that allows me so explicitly set the type, public id and system id. perhaps I have missed something. I can get download a version of 2.7 and see what happens. Are you intending to put the debug in I suggested? The poorly documeted virtual DOMDocumentType* DOMDocument::createDocumentType ( const XMLCh * qName, const XMLCh * , const XMLCh * ) [virtual] does what you want I think. Hi I have added in the debug output as described and still have a leak in there. Even with all the debug in there the docType->release() method is just not being called at all when you simply delete the doc as in the attached test harness. Looking at the DOMDocumentImpl::~DOMDocumentImpl() destructor it seems that there is absolutely no mention of the document type in there. However there is a DOMDocumentImpl::release() method that does free up the document type but again just calling that will result in leaks. This kind of suggests that there is more than one leak in there. Would it not be better to have a constructor for the document that simply takes in the parameters of the document type instead of the document type pointer so that the document can be fully responsible for the doc type memory allocation? Sincerely Pete Suggitt Hi Gareth One thing I did forget to mention was that I did have a play with the DOMDocumentType* DOMDocument::createDocumentType but I do not think this helps much with the test harness illustration due to the fact that you need a document in place to then create the document type .. eg 1) create an empty document 2) create a document type from that document 3) use the document type to create a new document. ---> abort! One thing that I have not seen anywhere is a doc type accessor (setter) so that I could do: doc *d = imp->createDocument(); d.setDocumentType( d->createDocumentType(name, sys, pub) ); Obviously you want the doc type when you instantiate the doc rather than after the fact. .. or am I off keel here? Your thoughts will be greatly appreciated. Sincerely Pete Suggitt I have had a good look at the code now and interestingly the doctype is only deleted in the document->release method, not in the destructor. Release does however delete the document. Calling release should solve your problem for now. I will move the deletion of the DT into the destructor and document the difference in behaviour of calling each one (that is that release will also call the user data handlers and therefore be slower). Please give this a try and report back so I can see if this is fixed. Cheers, Gareth Gareth hi This was what I saw when I was looking at it too. What I also found was that when the release method is called we also have a memory leak. My gut feel on this is that there is an identified leak in the delete doc approach and an unidentified one in the doc->release approach. I tried both ways last night and even changed it so that the code first calls release and then delete. In this second 'test' I saw that the call to free threw issues. Either way (the/a) leak remains. Have you run the above test harness in your investigations. I believe you will find it quite a useful incite into this issue. Sincerely Pete Hi, What you see there is not a memory leak. It seems more memory is being taken up because we use a global document to create things in the DT. This is then released when we call terminate. If you call terminate at the end of your test program and then the memory usage call again you will see that is drops to a constant value no matter how many times the loop in the test program is called. I agree that this is not desirable. I also agree that the model of the DT does not fit our memory model. Can you confirm that what I say fits with what you see? I will have a think about and talk to others about the best way to make this nicer. Cheers, Gareth Hi Gareth Terminate .. as in XERCES_CPP_NAMESPACE::XMLPlatformUtils::Terminate()? This would certainly not fit in with any design that requires an ongoing parsing function. In the implementation that I have been using I create a singleton for xerces that manages all xml functionality. I create 1 parser and 1 writer and utilise them throughout the lifespan of the application (intended to be in the scale of days/months). This will only release the memory when the singleton calls the std::atexit() method (thus cleaning the singleton object and calling terminate on the platform). This is (I believe) how this should be implemented. If I were to follow your above suggestion, I would have to create a new parser (pls associated objects) for every parse that I perform (I may as well render it to static functionality) so I do not see this as a viable work around. I think the solution lies in the management of the DT address space, as you have stated above. For the record I will change the test-harness above the test with the terminate function to prove that terminate will release the memory and come back to you. But I will state that this is not a valid workaround for the issues I am seeing. I look forward to the feedback from your discussions. Kind regards Pete Gareth hi I have indeed tried out the suggested approach and have changed the main method of the test-harness as below: std::cout << "**************** starting" << std::endl; for( int i = 0; i < 100; ++i ){ XERCES_CPP_NAMESPACE::XMLPlatformUtils::Initialize(); XERCES_CPP_NAMESPACE::DOMDocument * doc = createNewDocWithType(); std::cout << " - Doing something with the document" << std::endl; doc->release(); usleep(100000); std::cout << "* Memory (rss): " << getMemorySize() << std::endl; XERCES_CPP_NAMESPACE::XMLPlatformUtils::Terminate(); std::cout << "* Memory (rss): " << getMemorySize() << std::endl; } std::cout << "**************** ending" << std::endl; This turns out to be rock-solid when executed, as you have suggested One thing that I have noticed is that if instead of calling release on the document I simply delete the doc (replacing 'doc->release' with 'delete doc') from the heap then there is a leak ... ????? The memory size increases from 2620 -> 2644 over 100 iterations. This kind of suggests that there is a wider issue here with the way that memory is allocated and released (as we have both agreed above). I do not think there is a great deal more that I can add to this now, if there is pls do let me know and I will do my best to help. I look forward to your thoughts in this matter. Kind regards Pete Hi I was wondering if there was any progress with this issue since the last communication? Sincerely Pete Hi Pete, Yes there has been. Alby and I had a think and I am implementing a fix where the DT is just stored normally in the memory manager rather than being in a global document. Looking at the code there are several problems, including threading issues and lack of use of a user memory manager. I am on a sales run at the moment so don't have much time but hope to have this fixed in the next couple of weeks. If you would like to help out the give us a shout. Gareth Hiya Thank you for the kind invitation to participate in the implementation of this fix. Unfortunately I am going to be very busy completing a Masters Dissertation (it was in the implementation of this that I actualy found the issue) for the next month. I not be able to look at this until the new year but after which I will gladly lend a hand if the bug is still outstanding and becoming budensome. Thanks again Pete This bug is still present in 2.7.0 and latest nightly build (xerces-c_20070518224153) I ran a few more tests, but I think you guys have a handle on it. Here's a quick summary: Leak: impl->createDocumentType()->release() Leak: impl->createDocument(0,0,impl->createDocumentType())->release() [DOMDocumentType->release() *IS* called] No Leak: doc = impl->createDocument(0,0,0) doc->createDocumentType() doc->release() Terminate: doc1 = impl->createDocument(0,0,0) docType = doc1->createDocumentType() impl->createDocument(0,0,docType) [I even tried to trick the above with cloneNode, to no avail.] Segfault: docType = impl->createDocument(0,0,0) doc1 = impl->createDocument(0,0,docType)->release() doc2 = impl->createDocument(0,0,docType)->release() (kaboom) So it looks like there is some hybrid of keeping the part of the ownership of docType with the document, and part in the DOM implementation global document? I looked at the source briefly and it was too invovled for me to figure out. Anyone have any bright ideas for a workaround? I still do not understand how to create a Document with a DocumentType without memory leaks (on Solaris 10 with 3.0.1). My process produces many many XML documents. As it is "resident", its memory is growing more and more. Is there any workaround? Any patch to apply? Any help would be really appreciated. Thanks in advance. I chatted to Alberto about this. Here is the log of our conversation. My understanding is that it is better to use doc->createDocumentType() than impl->createDocumentType(). The same conclusion as Hal Black arrived at in his last comment. (06:45:40 PM) boseko_1278: Any thoughts on this: (06:47:12 PM) Alberto: the DOMDocument expects the DTD to come from its pool (06:47:21 PM) Alberto: so it doesn't delete it (06:47:46 PM) Alberto: but if the user allocates the DTD from the DOMImplementation object, it simply points to it (06:48:14 PM) boseko_1278: So why the memory leak then? (06:49:50 PM) Alberto: from what I recall, the leak doesn't exist; the owner of the DTD is the DOMImplementation, and will be freed only when shutting down Xerces (06:54:19 PM) boseko_1278: HM, and if we call release() on DocType, it is still not released? (06:55:37 PM) Alberto: when you release a node, you are simply putting it in a list for being recycled later (06:55:43 PM) Alberto: you are not deleting anything (06:56:05 PM) Alberto: DOMDocument::release deletes all the memory in one shot (06:56:19 PM) Alberto: but if the DTD didn't come from that memory pool, it is not deleted (06:56:33 PM) boseko_1278: Yes, I understand (06:57:16 PM) boseko_1278: It just seems to me that DOMDocument and DOMDocumentType are the same "kind" of objects. They are created by DOMImplementation (06:57:40 PM) boseko_1278: But DOMDocument you can release with a call to release() while DOMDocumentType you cannot. Strange (06:58:10 PM) Alberto: the issue is that a DTD can be created both as part of a document, and as a standalone object (06:58:26 PM) boseko_1278: We are talking about different things. (06:59:16 PM) boseko_1278: Let me put it this way: If I explicitly call release() on DOMDocumentType object that was created by DOMImplementation, will the memory be freed/reused? (07:07:59 PM) Alberto: it's middle way (07:09:12 PM) Alberto: if you call release on a DTD created by DOMImplementation, it will delete itself, but the memory used to store the lists of entities and elements comes from a static DOMDocument (07:09:25 PM) Alberto: that is deleted at shutdown (11:01:09 AM) boseko_1278: So you are saying that some parts of DOMDocumentType will be released and some won't (11:02:34 AM) boseko_1278: Are those lists of entities and elements shared among all DOMDocumentTypes? (11:10:46 AM) Alberto: the lists are per DTD (11:10:46 AM) Alberto: but yes, the major part of the memory will not be released (11:12:41 AM) boseko_1278: so, that's a bug then (11:13:27 AM) boseko_1278: and there doesn't seem to be any workaround (11:23:20 AM) Alberto: well, it's more a design issue (11:23:20 AM) Alberto: who wrote it assumed that the DOMImpletation::createDTD was not an often used API (11:23:20 AM) Alberto: and that was acceptable to delay the deletion of the memory at shutdown (11:23:20 AM) Alberto: so, the workaround is to use the createDTD method of the DOMDocument (11:25:13 AM) boseko_1278: Hm, that's sounds easy. Any idea why people don't do it? (11:51:25 AM) Alberto: the ones who complain about the problem probably have chosen that approach (11:51:25 AM) Alberto: but I don't know what they find valuable in using it Yeah!!! It works!!! Many thanks Boris. As a reminder, the following code leaks: impl->createDocument(0,0,impl->createDocumentType())->release(); It's equivalent code is: doc = impl->createDocument(0,0,0) dtd = doc->createDocumentType() doc->appendChild(dtd) doc->release() Note the "append" to have the same behaviour. This is a design issue so I am changing this from Bug to Improvement. Valgrind output: ==28513== TRANSLATE: 0x4073E610 redirected to 0x40617F1E ==28513== ==28513== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) ==28513== malloc/free: in use at exit: 680 bytes in 10 blocks. ==28513== malloc/free: 302 allocs, 292 frees, 731898 bytes allocated. ==28513== ==28513== searching for pointers to 10 not-freed blocks. ==28513== checked 8877280 bytes. ==28513== ==28513== 680 bytes in 10 blocks are still reachable in loss record 1 of 1 ==28513== at 0x4002CC6B: __builtin_new (in /usr/lib/valgrind/vgskin_memcheck.so) ==28513== by 0x4002CCC2: operator new(unsigned) (in /usr/lib/valgrind/vgskin_memcheck.so) ==28513== by 0x403AB3C3: xercesc_2_6::DOMImplementationImpl::createDocumentType(unsigned short const*, unsigned short const*, unsigned short const*) (DOMImplementationImpl.cpp:205) ==28513== by 0x804A4EA: createNewDocWithType() (play.cpp:47) ==28513== ==28513== LEAK SUMMARY: ==28513== definitely lost: 0 bytes in 0 blocks. ==28513== possibly lost: 0 bytes in 0 blocks. ==28513== still reachable: 680 bytes in 10 blocks. ==28513== suppressed: 0 bytes in 0 blocks. ==28513== - 28513- TT/TC: 0 tc sectors discarded. - 28513- 2680 chainings, 0 unchainings. - 28513- translate: new 4903 (83024 -> 1091150; ratio 131:10) - 28513- discard 0 (0 -> 0; ratio 0:10). - 28513- dispatch: 100000 jumps (bb entries), of which 99608 (99%) were unchained. - 28513- 110/17695 major/minor sched events. 7761 tt_fast misses. - 28513- reg-alloc: 818 t-req-spill, 203724+4429 orig+spill uis, 24712 total-reg-r. - 28513- sanity: 15 cheap, 1 expensive checks. - 28513- ccalls: 25847 C calls, 56% saves+restores avoided (85552 bytes) - 28513- 33847 args, avg 0.88 setup instrs each (8098 bytes) - 28513- 0% clear the stack (77541 bytes) - 28513- 8452 retvals, 35% of reg-reg movs avoided (5760 bytes)
https://issues.apache.org/jira/browse/XERCESC-1508
CC-MAIN-2015-40
refinedweb
3,557
60.95
BRK(2) NetBSD System Calls Manual BRK(2)Powered by man-cgi (2021-06-01). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias. NAME brk, sbrk -- change data segment size LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <unistd.h> int brk loca- tion of the ``break''. The break is the first address after the end of the process's uninitialized data segment (also known as the ``BSS''). While the actual process data segment size maintained by the kernel will only grow or shrink in page sizes, these functions allow setting the break to unaligned values (i.e. it may point to any address inside the last page of the data segment). The brk() function sets the break to addr. The sbrk() function raises the break by at least incr bytes, thus allo- cating at least incr bytes of new memory in the data segment. If incr is negative, the break is lowered by incr bytes. sbrk() returns the prior address of the break. The current value of the program break may be determined by calling sbrk(0). (See also end(3)). The getrlimit(2) system call may be used to determine the maximum permis- sible size of the data segment; it will not be possible to set the break beyond the RLIMIT_DATA rlim_max value returned from a call to getrlimit(2), e.g. ``etext + rlim.rlim_max''. (see end(3) for the defi- nition of etext). RETURN VALUES brk() returns 0 if successful; otherwise -1 with errno set to indicate why the allocation failed. The sbrk() function returns the prior break value if successful; other- wise ((void *)-1) is returned and errno is set to indicate why the allo- cation failed. ERRORS brk() or), mmap(2), end(3), free(3), malloc(3), sysconf(3) HISTORY A brk() function call appeared in Version 7 AT&T UNIX. BUGS Note that mixing brk() and sbrk() with malloc(3), free(3), and similar functions may result in non-portable program behavior. Caution is advised. Setting the break may fail due to a temporary lack of swap space. It is not possible to distinguish this from a failure caused by exceeding the maximum size of the data segment without consulting getrlimit(2). NetBSD 4.0 July 12, 1999 NetBSD 4.0
https://man.netbsd.org/NetBSD-4.0/sbrk.2
CC-MAIN-2021-49
refinedweb
382
65.01
Hello, after refactoring some of my old gui code by removing the "Gui" - prefixes and instead putting them into a gui-namespace, plus putting the file into a seperate folder, I've come across a problem. Now I've got some classes that share the same name, and also the same file-name: // in "Gui/Window.h" namespace gui { class Window {}; } // in "Core/Window.h" namespace core { class Window {}; } Those two classes doesn't have anything in common. Before starting, I supposed this was safe, since both files are in different locations, and both classes are in different namespaces. However, when compiling the libary I get a compiler warning about multiple object-files with the same name, and upon compiling the actual game project, I get a lot of unresolved symbol linker errors. Now I ask, is there any way to solve this, without adding some provisorical pre/postfix to the class? Edited by Juliean, 02 May 2013 - 04:00 PM.
https://www.gamedev.net/topic/642588-two-classes-same-name-solution/
CC-MAIN-2017-04
refinedweb
161
61.06
Extract file name from path, no matter what the os/path format Actually, there's a function that returns exactly what you want import osprint(os.path.basename(your_path)) WARNING: When os.path.basename() is used on a POSIX system to get the base name from a Windows styled path (e.g. "C:\\my\\file.txt"), the entire path will be returned. Example below from interactive python shell running on a Linux host: Python 3.8.2 (default, Mar 13 2020, 10:14:16)[GCC 9.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.import os filepath = "C:\\my\\path\\to\\file.txt" # A Windows style file path.os.path.basename(filepath)'C:\\my\\path\\to\\file.txt' Using os.path.split or os.path.basename as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail. Windows paths can use either backslash or forward slash as path separator. Therefore, the ntpath module (which is equivalent to os.path when running on windows) will work for all(1) paths on all platforms. import ntpathntpath.basename("a/b/c") Of course, if the file ends with a slash, the basename will be empty, so make your own function to deal with it: def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) Verification: 'a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c', 'a/b/../../a/b/c/', 'a/b/../../a/b/c'] [path_leaf(path) for path in paths]['c', 'c', 'c', 'c', 'c', 'c', 'c']paths = [ (1) There's one caveat: Linux filenames may contain backslashes. So on linux, r'a/b\c' always refers to the file b\c in the a folder, while on Windows, it always refers to the c file in the b subfolder of the a folder. So when both forward and backward slashes are used in a path, you need to know the associated platform to be able to interpret it correctly. In practice it's usually safe to assume it's a windows path since backslashes are seldom used in Linux filenames, but keep this in mind when you code so you don't create accidental security holes. os.path.splitis the function you are looking for head, tail = os.path.split("/tmp/d/a.dat")print(tail)a.datprint(head)/tmp/d
https://codehunter.cc/a/python/extract-file-name-from-path-no-matter-what-the-os-path-format
CC-MAIN-2022-21
refinedweb
411
66.03
Throw exception in java Hi everyone in this blog I’m explaining about throw keyword in java. The java throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. Before.. in this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. public class TestThrow1{ static void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); System.out.println("rest of the code..."); } } Exception in thread main java.lang.ArithmeticException:not valid check more post on exception handling here
https://www.mindstick.com/blog/10899/throw-exception-in-java
CC-MAIN-2017-34
refinedweb
141
51.44
Hi everyone, i have file CSV called file_1.csv, with attribute : id Name Address PhoneNumber ideal value in csv is : 1,roby,Jl.xxx,0898786 2,anto,Jl.yyy,0898786 3,tini,Jl.ddd,0898786 4,pauli,Jl.aaa,0898786 but the reality is, file_1.csv there is some inconsisten format of separator (such as more "," in address"), such as : 1,Pauli,Jl. Beijing,China,89766 2.Tini,Jl, Tokyo,Japan,2234 i have tried to use operator FileSource with parameter parsing : permissive so my operator just read correct format, but i need to write a tuple with incorrect format in rejected_file_1.csv, so if i have file_1.csv : 1,roby,Jl.xxx,0898786 2,anto,Jl.yyy,0898786 3,tini,Jl.ddd,0898786 4,pauli,Jl.aaa,0898786 5,paulina,Jl.Beijing,china,0898786 6.Anti,Jl,Tokyo,Japan,09876 i have to output, Correct_file_1.csv : 1,roby,Jl.xxx,0898786 2,anto,Jl.yyy,0898786 3,tini,Jl.ddd,0898786 4,pauli,Jl.aaa,0898786 and rejected_file_1.csv : 5,paulina,Jl.Beijing,china,0898786 6.Anti,Jl,Tokyo,Japan,09876 How can i do that ? Thx Answer by Michael.K (1380) | Mar 06, 2015 at 02:26 AM Hello @ihsan2008, by changing the FileSource format from line back to csv, you can use the hasHeaderLine parameter but you lose the ability to validate the record before it is CSV parsed. I would recommend to fall back to the original solution without Parse/Functor and enhance the Validator Custom operator in a way like this: a) Introduce a new state variable that counts the tuples since the last punctuation. mutable uint64 tuplesSincePunctuation = 0ul; b) Introduce an onPunct clause and reset this state variable. onPunct I: { tuplesSincePunctuation = 0ul; } c) Extend the onTuple clause. Increment the variable and check whether you can drop the tuple because it is a header line or whether you must continue with the tokenization and validation. if (tuplesSincePunctuation < 1ul /* put here your number of header lines */) { ++tuplesSincePunctuation; return; } Answer by hnasgaard (1441) | Mar 05, 2015 at 07:16 AM Hi @ihsan2008 You might want to consider normalizing your data first. If there are separators characters embedded in the data strings, the strings should be quoted so that the embedded separator is ignored. Your sample data above suggests that you know where the separators should be so you could read the file in line format, process each line, and then parse it used the Parse operator. Although, given you are parsing it in order to normalize it, perhaps you could simply parse it yourself and create the required tuple using a Custom operator. Answer by Michael.K (1380) | Mar 05, 2015 at 07:18 AM Hi @ihsan2008, either you can require (from your customer) that the strings of the input file that can contain the separator, are quoted or you have to read the input file line by line and implement a validation in a Custom operator. In the 1st case, your applications would work immediately. Please see the "format" description excerpt from the FileSource operator: csv: This format expects the file to be structured as a series of lines, where each line is a list of comma separated values. String literals that are used at the outermost level can appear without the double quotation marks, unless they have a ‘,' character or escaped characters, in which case double quotation marks are required.** In the 2nd case, you would configure your FileSource to use "format: line". The FileSource output stream is connected to the input of a Custom operator. The Custom operator validates each line. For the validation, you could, for example, use the "public list csvTokenize (rstring str)" function checking whether the size of the returned list fits to the expected size (in your case 4). If it fits, you could also implement additional checks, for example, is the first item a number, etc. I hope that this helps. Regards, Michael. Answer by hnasgaard (1441) | Mar 05, 2015 at 07:51 AM Hi @ihsan2008 I'll write an example and post it shortly. Answer by ihsan2008 (55) | Mar 05, 2015 at 07:54 AM Hai @Hnasgaard ,thx :) Answer by ihsan2008 (55) | Mar 05, 2015 at 05:36 PM Hi @Michael.K i have succes use your solved in, but i have new problem, when my CSV has header line,i have tried to use functor n parse, but still not work, maybe you have another suggest to me thx input.csv : Header 1,valid,2 2,still valid,3.0 xxx,invalid,yeah 4,valid again,55.0 and my code : namespace Production ; composite Test_error { type Data = tuple<int64 a, rstring b, float64 c> ; graph stream<rstring row1, rstring row2, rstring row3> data = FileSource() { param file : "input.csv" ; format : csv ; hasHeaderLine : 1u ; } (stream<Data> valid ; stream<I> invalid) as Validator = Custom(Parse_5_out0) ; submit(invalidTuple, invalid) ; } else { if(- 1 == spl.utility::parseNumber(validTuple.a, parts [ 0 ])) { assignFrom(invalidTuple, I) ; submit(invalidTuple, invalid) ; } else if(- 1 == spl.utility::parseNumber(validTuple.c, parts [ 2 ])) { assignFrom(invalidTuple, I) ; submit(invalidTuple, invalid) ; } else { validTuple.b = parts [ 1 ] ; submit(validTuple, valid) ; } } } } () as FileSink_5 = FileSink(valid) { param file : "valid.txt" ; } () as FileSink_6 = FileSink(invalid) { param file : "invalid.txt" ; } (stream<rstring row> Parse_5_out0) as Parse_5 = Parse(Functor_6_out0 as inPort0Alias) { param format : line ; } (stream<blob datablob> Functor_6_out0) as Functor_6 = Functor(data) { output Functor_6_out0 : datablob = convertToBlob((rstring) data) ; } } 25 people are following this question. How handling incorrect format value attribute in CSV with Stream 6 Answers How read CSV file with streams when there is quote string ? 6 Answers Why count row data write into netezza is not match with count row from filesource csv ? 4 Answers FileSource() parsing empty tuple 7 Answers Import CSV records as lists 3 Answers
https://developer.ibm.com/answers/questions/178786/$%7BawardType.awardUrl%7D/
CC-MAIN-2019-47
refinedweb
953
53
The purpose. As you might remember from my previous blog entry, a RESTful url must fulfill these requirements: - An url address must no have suffix in it (in other words, an url address most not contain a suffix like ‘.action’). - The context path of the web application must not start with a prefix like ‘app’. I will give you a brief description of my idea next. The Solution As I mentioned to you before, you can use the dispatcher servlet url mappings for configuring your web application to use RESTful url addresses. This means that you must create section specific context path prefixes and map the dispatcher servlet to these url patterns. This idea might seem a bit confusing at first so I will provide an example which will hopefully explain this idea. Lets assume that your web page has two sections: products and services. This would mean that you would map your dispatcher servlet to following url patterns: ‘/products/*’ and ‘/services/*’. This approach works rather well if the next part of the context path does not contain a path variable. Lets take a closer look of this in following: - Following context paths would not work: ‘/products/1’ and ‘/services/5’. - Following context paths would work: ‘/products/phones/1’ and ‘/services/training/1’. The reason for this behavior is that the dispatcher servlet removes the url pattern from the beginning of the request’s context path and tries to look for a handler to the request by using the resulting string. (E.g. If you have mapped your dispatcher servlet to url pattern ‘/products/*’ and the context path of the incoming request is ‘/products/phones/1’, the dispatcher servlet is looking for a handler which request mapping matches with the string ‘/phones/1’). This naturally means that context paths like ‘/products/1’ and ‘/services/1’ will not work because the resulting request mapping is not “unique”. Enough with the theory. The steps needed to create RESTful url addresses by using this technique are described next. Required Steps The steps needed to fulfill the given requirements are following: - Configuring the application context - Configuring the web application - Creating an index page Each of these steps is described with more details in following. Configuring the Application Context First, you must configure your application context. I have a created a simple Java configuration class which is used to enable Spring MVC, set the component scan base package and configure the view resolver bean. The source code of the configuration class is given in following: import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;. * @author Petri Kainulainen */ @Configuration @ComponentScan(basePackages = {"net.petrikainulainen.spring.restful.controller"}) @EnableWebMvc Second, you must configure your web application. In this case the web application configuration consists of two phases: - Configure the url mapping of the dispatcher servlet. - Configure the welcome file of your application. I decided to configure my web application by implementing the WebApplicationInitializer interface. My example adds dispatcher servlet url mappings for the home page, products section and services section of the web application. The source code of my implementation is given_HOME = "/home"; private static final String DISPATCHER_SERVLET_MAPPING_PRODUCTS = "/products/*"; private static final String DISPATCHER_SERVLET_MAPPING_SERVICES = "/services/*"; _HOME); dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING_PRODUCTS); dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING_SERVICES); servletContext.addListener(new ContextLoaderListener(rootContext)); } } Since it is not yet possible to configure the welcome page of a web application by using Java configuration, I had to create a web.xml configuration file and configure the welcome file of my application in it. My web.xml file looks as follows: <web-app <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> Creating an Index Page Third, you must create an index page which redirects user to your home page. In my example, the url mapping of the home page is ‘/home’. I used the Meta Refresh Tag for this purpose. The source code of my welcome file is given in following: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""> <html> <head> <meta HTTP- <title></title> </head> <body> </body> </html> Final Thoughts I have now described to you how you can use the dispatcher servlet url mappings for creating RESTful url addresses with Spring MVC. I am having some doubts about this approach for three reasons: - If new sections are added to your web application, you must always remember to add the correct mapping for the dispatcher servlet. This feels a bit cumbersome. - The actual url address of your home page is not invisible for the users of your application. I prefer url addresses like over. This might sound ridiculous but in some situations this is not acceptable. - The context path of your application must have more than one “level” because otherwise Spring cannot find the correct handler for the requests. This might not a problem in most cases but if it is, you cannot use the approach described in this blog entry. If you are interested of playing around with my example application, you can get the source code from GitHub. The third and last part of this series will describe how you can create RESTful urls with Spring MVC and UrlrewriteFiter. Stay tuned. thank you for this work, i am currently trying to code a embedded jetty application with a gwt module and spring, my problem is setting the “/” for the dispatch servlet so that post requests can pass thru to standard web.xml mapped servlets and currently they are hijacked by the spring dispatch servlet. I really appreciate the style of writing here, you have a great balance between code and description, a terse but complete description with simple but complete code. Thank you Thank you for your nice words. I really appreciate them. About your problem, were you able to solve you it by using this advice or do you need some help with it? This approach can solve it as long as you can set different urls for different servlets. This naturally mean that if you follow this path, all requests send to a specific url are always processed by the same servlet (the request method does not matter). Mapping urls manually like this can be a bit troublesome but in your case it seems justified. Anyway, if you need more help with this problem, let me know. Hello Petri! Do you know, how I can configure my servlets from Java, for communication with GWT? GWT is MVP-framework, without Controller. Communication with services provides by rpc-calls from GWT-module on client. I am using spring4gwt () I have this web.xml file: myproject org.springframework.web.context.ContextLoaderListener springGwtRemoteServiceServlet org.spring4gwt.server.SpringGwtRemoteServiceServlet springGwtRemoteServiceServlet /myproject/springGwtServices/* 30 myproject.html Thanks! Hi, Unfortunately I have never used GWT so I have no idea how this is done. I hope that you find a solution to this problem! good website ,Thanks so much You are welcome!
https://www.petrikainulainen.net/programming/tips-and-tricks/creating-restful-urls-with-spring-mvc-3-1-part-two-dispatcher-servlet-url-mappings/
CC-MAIN-2019-39
refinedweb
1,149
55.13
Add the chapter title on each line with REG-EXP - Trucide Polère last edited by Given the following file : Chapter 1 1 line 1 2 line 2 3 line 3 Chapter 2 1 line 4 2 line 5 I would like to add the chapter number on each line number : Chapter 1 1-1 line1 1-2 line 2 … Chapter 2 2-1 line 4 … Is it possible using regular expressions ? Thanks for any insight. - Claudia Frank last edited by Claudia Frank a solution with two regular expression might look like this (not really prof but hopefully useful) First change each line after a Chapter find: (Chapter\s)(\d+)(\s*\r\n)(\d+) replace: \1\2\3\2-\4 and next change the remaining lines find: (\d+)(-\d+.*?\s*\r\n)(\d+)(\s) replace: \1\2\1-\3\4 First regex would look for Chapter followed by a single space (Chapter\s) followed by multiple digits but at lease one (\d+) followed by multiple spaces and carriage return (\s*\r\n) followed by multiple digits but at least one(\d+) Each of the () are groups which are reflected by \1 and \2 respectively. So \1 belongs to the result of (Chapter\s) and \2 to (\d+) … Second regex (\d+)(-\d+.?\s\r\n)(\d+)(\s) means multiple digits but at least one (\d+) followed by a dash and multiple digits but at least one followed by any chars non-greedy followed by spaces, either 0 or multiple followed by carriage return (-\d+.?\s\r\n) again multiple digits but at least one (\d+) followed by (\d+) followed by a space. The second regex needs to be performed more often as it always replaces one line per chapter. Make a backup before testing. Cheers Claudia - Trucide Polère last edited by Thanks. Good idea ! but… there’s a lot (and i mean a lot!) of lines in my file, and it only replace one line per chapter. Anyway, it’s a good start, and at least I only have to replace the line for one chapter… Great thanks, Cheers Pierre - Claudia Frank last edited by If it is only one chapter than a much faster attempt would be to use block mode functionality instead of regex. -Put the cursor just before the first line to change, -Scroll, using the scrollbar, to the last line to change -press SHIFT+ALT and click in front of the last line you should see a vertical line -type whatever you need to do and all lines get edited. Done. Cheers Claudia Hello, Trucide Polère and Claudia, Trucide, I also found two S/R to achieve what you would like to but, compared to the Claudia’s solution, the second S/R needs to be run, once only :-))) So, just click on the Replace All button, once for each S/R ! My solution works : Whatever the location of the word “Chapter”, in current line Whatever the number value, of the word “Chapter” ( Numeric sort not needed ) Whatever the case of the word “Chapter” If blank line(s) is(are) inserted between two chapters If blank line(s) is(are) inserted between two lines of a chapter Remark : These regexes need an extra character, which must NOT exist, yet, in your file. I chose the #symbol but any other symbol may be used. Just escape it if this symbol is a special regex character ! So, given the example text, below, with 3 blank lines after “line 10” : Chapter 156 line 1 line 2 line 3 line 4 line 5 Chapter 2 line 5 line 6 This is a test : chapter 37 line 7 line 8 line 9 line 10 The first regex S/R, below, adds a line, beginning with a #symbol and followed by the number of the current chapter, just before the line, containing the next word chapter, whatever its case OR before the very end of the file SEARCH (?i)Chapter\h+(\d+)(?s).+?(?=(?-s).*Chapter|\z) REPLACE $0#\1\r\n So it gives the changed text, below : Chapter 156 line 1 line 2 line 3 line 4 line 5 #156 Chapter 2 line 5 line 6 #2 This is a test : chapter 37 line 7 line 8 line 9 line 10 #37 The second regex S/R, below : #symbol, and deletes it search for a non-empty line, which does not contain the word Chapter, whatever its case but it’s followed, further on, by the nearest #symbol with its number, stored as group 1 then adds this number, followed by a dash, in front of each line, during replacement SEARCH (?i-s)^#.+\R|(?!.*Chapter)^.+(?=(?s).+?#(\d+)) REPLACE ?1\1-$0 So, we obtain the final text, below : Chapter 156 156-line 1 156- line 2 156-line 3 156- line 4 156-line 5 Chapter 2 2-line 5 2-line 6 This is a test : chapter 37 37-line 7 37- line 8 37- line 9 37-line 10 Best Regards, guy038 Note : as usual : The modifier (?-s)means that further dot character ( .) stands for any single standard character, except for any End of Line character The modifier (?s)means that further dot character ( .) stands for any single character, included End of Line character The modifier (?i)means that the regex search is performed in an insensitive way The modifier (?s)means that the regex search is performed in a sensitive way
https://community.notepad-plus-plus.org/topic/13180/add-the-chapter-title-on-each-line-with-reg-exp
CC-MAIN-2020-45
refinedweb
901
57.64
so I am having trouble with my for loop which is meant to display all the tasks allocated to a user. There are four tasks allocated to them, as you can see on this imgur link . However it does not show them on the site. Here is my detail.html file: <h1>{{user.fullName}}</h1> <h4>Username: {{user.userName}}</h4> <ul> {% for i in userName.i_set.all %} <li> {{ i.taskName }} </li> {% endfor %} </ul> from django.db import models class User(models.Model): userName = models.CharField(max_length=30) password = models.CharField(max_length=100) fullName = models.CharField(max_length=50) def _str_(self): return self.fullName class Task(models.Model): userName = models.ForeignKey(User, on_delete=models.CASCADE) taskName = models.CharField(max_length=30) scores = models.CharField(max_length=100) # score should default be set to x/10 until changed def _str_(self): return str(self.userName) + ' - ' + self.taskName Based on the code you have provided your for loop code is completely wrong, try to change it to: {% for i in user.task_set.all %} More better is to use related_name in ForeignKey for ease of access: userName = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tasks') Then you can access related tasks for user in template like this: {% for i in user.tasks.all %}
https://codedump.io/share/i8aYIPR4OXmQ/1/django-html-39for-loop39-not-displaying-any-of-the-objects-in-a-set
CC-MAIN-2018-13
refinedweb
207
64.27
14 June 2013 15:48 [Source: ICIS news] By Mark Yost CHICAGO (ICIS)--Auto and tyre makers said on Friday that they - and the petrochemical companies that supply them with raw materials - need to re-gauge future demand based upon the consumer behaviour of Generation X and Y consumers who will drive spending for the next 30 years. In short, cars do not have the same importance for this upcoming generation of consumers as they did for the Baby Boomers, sources said. They are driving considerably less than Baby Boomers once did, prefer jets to cars for vacation and increasingly prefer bikes or public transportation to automobiles. "We really need to re-think our assumptions about consumer behaviour," said a source, who supplies acrylonitrile-butadiene-styrene (ABS) and other petrochemicals to the auto and tyre industries. "They are really much different than the Baby Boomers and their behaviour is going to significantly impact demand for petrochemicals in ?xml:namespace> Indeed, according to a study released last year by Frontier Group entitled "Transportation and the New Generation", the average American was driving 6% fewer miles in 2011 than in 2004. "From 2001 and 2009, the average annual number of vehicle-miles traveled by young people (16 to 34-years-old) decreased from 10,300 miles to 7,900 miles per capita - a drop of 23 percent," the group said in its study. "The trend away from steady growth in driving is likely to be long-lasting - even once the economy recovers," said Benjamin Davis and Tony Dutzik, authors of the study. Among the key findings that are likely to impact both petrochemical and tyre demand: ·In 2009, 16- to 34-year-olds took 24% more bike trips than they took in 2001, despite that the age group is shrinking in size by 2%. ·In 2009, 16- to 34-year-olds walked to destinations 16% more frequently than the 16- to 34-year-olds in 2001. ·From 2001 to 2009, the number of passenger-miles traveled by 16- to 34-year-olds on public transit increased by 40% per capita*. ·According to Federal Highway Administration, from 2000 to 2010, the share of 14- to 34-year-olds without a driver’s license increased from 21% to 26%. According to another study done by KRC Research and the urban car sharing firm Zipcar, 45% of 18-34 years old have made a conscious effort to replace driving with other transportation alternatives, up from about 32% of older consumers who have made that choice. Other lifestyle choices also are expected to impact tyre and petchem demand, including younger people preferring to cluster around public transportation in cities and saying that "protecting the environment" is a major factor in their transportation choices and driving habits. "This is something that we definitely need to factor into our market expectations," said a source in the petrochemical industry. "This is really going to impact demand for BD and SBR," said another. "If these new generations are driving less, it means they'll need to replace tyres less often. Replacement tyres are 80% of our business. You do the math." "Compare this to the annual total BD consumption," said another source. "It doesn't match
http://www.icis.com/Articles/2013/06/14/9678853/tyre-makers-petchems-need-to-re-think-gen-x-y-demand---sources.html
CC-MAIN-2015-14
refinedweb
536
55.37
Another approach to building software is generating make files. This is what qmake does. qmake is part of Qt, the portable widget library of TrollTech. qmake takes Project files (extension .pro) and turns these into makefiles. The advantage here is that the syntax of .pro files is much simpler. Suppose we have a minimalist test class, something like the following: #include <iostream> #include <string> using std::cout; using std::endl; using std::string; class Hi { private: string message; public: Hi(){ message = "Hi There!"; } void sayHi(){ cout << message << endl; } }; int main(){ Hi hi; hi.sayHi(); return 0; } Save it in a file called Hi.cpp or similar. Next, we let qmake generate the .pro file. This is not something we'll do regularly, but it's easy to start off with. $ qmake -project A new .pro file appears, looking something like this: TEMPLATE = app TARGET = DEPENDPATH += . INCLUDEPATH += . # Input SOURCES += Hi.cpp I've removed the header that says 'autogenerated at date xxx' because that's just confusing for colleagues who might think they shouldn't touch this file. They should. This new project file is where we'll work from. We can now generate a makefile: $ qmake And build the software with: $ make You immediately get other targets as well: $ make clean $ make distclean
https://www.vankuik.nl/qmake
CC-MAIN-2021-04
refinedweb
213
77.64
Twitter is dead! Long live Mastodon! I've written lots of 'bots for Twitter - and been part of their developer outreach programme. Lots of us have politely requested improvements to the bot experience on Twitter, but to no avail. So, today I'm going to show you how to quickly and easily write your first Mastodon-bot. Bots In Spaaaaaaace Step 1 - you need to set up a new account for your bot. Create it on - a Mastodon instance specifically for robots. Set it up just like a regular account. Give it a name, an avatar image, and a description. As you edit the profile, be sure to tick the box marked "This is a bot account". Like Twitter, there's no way to officially link a bot to its owner. I suggest using the profile metadata to say who you are. But that's optional. Step 2 - create an application. Unlike Twitter, you don't have to sign up for a development programme. Nor do you have to verify yourself with a phone number. Just go to preferences and click Development - it should take you to You need to set an application name - that's it. You can ignore all the other fields. By default your bot can read and write its own timeline. Hit save when you're done. Click on the name of your application - and you'll see some long alphanumeric strings. These are your secret tokens. Do not share these with anyone. Don't take screenshots of them and post them online. You're going to need "Your access token" for the next stage. Python I'm going to assume you're using Python 3. These instructions will work on Linux. You may need to adjust this depending on your software. Step 3 - we're going to use the Mastodon.py library. On the commandline, run: pip3 install Mastodon.py After a few moments, your library will be installed. Step 4 - create a new file called token.secret In this file, paste the long alphanumeric string from "Your access token". Make sure you don't have a space at the start or end of the string. Save the file. Step 5 - create a new file called bot.py Paste the following into the file: from mastodon import Mastodon # Set up Mastodon mastodon = Mastodon( access_token = 'token.secret', api_base_url = '' ) mastodon.status_post("hello world!") Step 6 - run the file using python3 bot.py You bot will "toot" - that is, post a message on Mastodon. If all you want to do is automagically toot something - that's it. You're done. Shouldn't take you longer than 5 minutes. Images You can post up to 4 images on Mastodon. Assuming you have the image save as test.png here's the code you need: media = mastodon.media_post("test.png") mastodon.status_post("What a great image!", media_ids=media) Want to upload multiple images? media1 = mastodon.media_post("1.jpg") media2 = mastodon.media_post("2.jpg") media3 = mastodon.media_post("3.jpg") media4 = mastodon.media_post("4.jpg") mastodon.status_post("Lots of photos.", media_ids=[media1,media2,media3,media4]) There we go, nice and easy! Demo! You can follow my Colours bot What about...? This is just a basic guide to getting your bot to post to Mastodon. If there's interest, I'll write about other topics. 6 thoughts on “Easy guide to building Mastodon bots” Could you write up something for WordPress to Mastadon? I use this plugin Thx, works like a charm I made a docker-ized version of this. Thank you for the tutorial! easiest bot I ever made, though tumblr was pretty easy too.
https://shkspr.mobi/blog/2018/08/easy-guide-to-building-mastodon-bots/
CC-MAIN-2019-35
refinedweb
603
78.96
Planning Your Namespace When planning your namespace, you must decide whether to use a private root and whether you want your internal and external namespaces to have the same domain name. Whether you can use a private root depends on the type of clients you have. You can use a private root only if each of your clients has one of the following: name exclusion list . A list of DNS suffixes that are internal. proxy autoconfiguration (PAC) file . A list of DNS suffixes and exact names that are internal or external. If you have clients lacking both of these, the DNS server hosting your organization's top-level internal domain must forward queries to the Internet. Table 6.12 shows, based on the proxy capability of your client, whether you can use a private root. (Note that a local address table is a list of IP addresses that are internal and external.) Table 6.12 Configuring Internal and External Namespaces Based on Proxy Capability To simplify name resolution for internal clients, use a different domain name for your internal and external namespaces. For example, you can use the name reskit01 - ext.com for your external namespace and reskit.com for your internal namespace. You can also use the name reskit.com for your external namespace and noam.reskit.com for your internal namespace. However, do not make your external domain a subdomain of your internal domain; that is, in the context of this example, do not use reskit.com for your internal namespace and noam.reskit.com for your external namespace. You can use the same name internally and externally, but doing so causes configuration problems and generally increases administrative overhead. If you want to use the same domain name internally and externally, you need to perform one of the following actions: Duplicate internally the public DNS zone of your organization. Duplicate internally the public DNS zone and all public servers (such as Web servers) that belong to your organization. In the PAC file on each of your clients, maintain a list of the public servers that belong to your organization. Caution Make sure that the domain name for your internal namespace is not used anywhere on the Internet. Otherwise, you might have problems with ambiguity in the name resolution process. Which action you need to perform to use the same domain name internally and externally varies. Table 6.13 shows whether you can use the same domain name for your internal and external namespaces, and if so, which method you must use, based on your client software proxy capability. Table 6.13 Using the Same Name for Internal and External Namespaces Based on Proxy Capability
https://technet.microsoft.com/en-us/library/cc959282.aspx
CC-MAIN-2017-34
refinedweb
446
55.84
Suggestions All Countries & Regions $300.00/ Carton 1 Carton(Min. Order) $300.00/ Carton 500 Cartons(Min. Order) Powder Milk Powder Almond Milk Powder Manufacturer Supply Natural Almond Powder Organic Almond Milk Powder $6.00-$15.00/ Kilogram 2.0 Kilograms(Min. Order) $14.00-$20.00/ Kilogram 1 Kilogram(Min. Order) $8.00-$20.00/ Kilogram 1.0 Kilograms(Min. Order) $500.00-$1,000.00/ Ton 10.0 Tons(Min. Order) $13.76-$14.68/ Piece 1.0 Pieces(Min. Order) $300.00-$700.00/ Metric Ton 25.0 Metric Tons(Min. Order) $7.00-$12.00/ Carton 100.0 Cartons(Min. Order) $800.00-$1,200.00/ Metric Ton 5.0 Metric Tons(Min. Order) $2.00-$4.00/ Box 250.0 Boxes(Min. Order) $4.60/ Kilogram 1000 Kilograms(Min. Order) $2.00/ Carton 50 Cartons(Min. Order) $2,500.00/ Metric Ton 100 Metric Tons(Min. Order) $400.00-$450.00/ Metric Ton 10.0 Metric Tons(Min. Order) $1,500.00-$2,000.00/ Metric Ton 28.0 Metric Tons(Min. Order) $700.00-$1,200.00/ Metric Ton 25.0 Metric Tons(Min. Order) Top Grade Instant Full Cream Milk Powder Wholesale Sheep Whey Milk Powder Imported Milk Source from Germany.. $400.00-$600.00/ Metric Ton 10.0 Metric Tons(Min. Order) $8.50/ Unit 48 Units(Min. Order) $210.00-$300.00/ Unit 1.0 Units(Min. Order) $0.5938-$1.19/ Piece 500.0 Pieces(Min. Order) $150.00-$1,800.00/ Ton 27 Tons(Min. Order) $21.80-$34.40/ Unit 1 Unit(Min. Order) $400.00-$600.00/ Metric Ton 25.0 Metric Tons(Min. Order) $5.00-$6.00/ Unit 60.0 Units(Min. Order) $500.00-$650.00/ Ton 27.0 Tons(Min. Order) $200.00/ Ton 50 Tons(Min. Order) $8.32-$10.69/ Box 325600.0 Boxes(Min. Order) $450.00/ Metric Ton 22 Metric Tons(Min. Order) $111.00-$210.00/ Metric Ton 25 Metric Tons(Min. Order) $15.00/ Carton 1000 Cartons(Min. Order) $150.00-$200.00/ Ton 27.0 Tons(Min. Order) $5.94-$17.82/ Pallet 15.0 Pallets(Min. Order) $350.00/ Metric Ton 20 Metric Tons(Min. Order) $500.00-$550.00/ Metric Ton 5.0 Metric Tons(Min. Order) $12.00-$16.00/ Carton 100 Cartons(Min. Order) Use Alibaba.com to get quality and healthy. import.. import milk powder have become a go-to product for a lot of people for different reasons They are known to improve bone structure, significantly reducing the risk of arthritis.. import milk powder. import milk powder. import milk powder and offers. They are available in large quantities which are accredited to their worldwide availability. You can make a variety of milk products and enjoy them with friends and family. Find options from a range of wholesalers and retailers.
https://www.alibaba.com/showroom/import-milk-powder.html
CC-MAIN-2021-17
refinedweb
479
65.59
Search: Search took 0.01 seconds. - 14 Jan 2013 6:08 AM Unfortunately, I haven't. :( And I can't reproduce the issue (at least not reliably... It occurs occasionally). - 23 Apr 2010 2:36 AM - Replies - 0 - Views - 887 Hi, I am trying to fill a TreeTable with a static model. The table headers are displayed correctly, but no data lines appear. I have followed the TreeTableExample class (except for the loader,... - 25 Feb 2010 12:29 AM - Replies - 1 - Views - 1,300 Hi, when using GXT Dialog, the buttons "Yes", "No", "Cancel" are translated to German, if I use the locale de_DE, however, they are not translated to French, if I use fr_FR. Is GXT (1.2.4) not... - 19 Nov 2009 6:15 AM Sure... But beware, it still is pretty large :). Thanks for trying!! package com.tensegrity.blueview.client; import com.extjs.gxt.ui.client.Style.LayoutRegion; import... - 19 Nov 2009 6:08 AM Just to be clear: It is always the same source code that is being executed. Most of the time it works, sometimes, it does not... I know that some panels are missing, but I know (I debugged it) that... - 19 Nov 2009 5:25 AM Hi, we use GXT 1.4 along with GWT 1.5.3 in our web-application. On the left hand side, I display a tree and when a user clicks on an item in this tree, an editor on the right hand sides opens... - 16 Sep 2009 5:10 AM - Replies - 3 - Views - 1,431 I have, they don't respond... (I waited two weeks) - 16 Sep 2009 2:57 AM - Replies - 3 - Views - 1,431 in addition to my previous question, I’ve got a second one: When we as a company have 2 licenses for the 2 developers in a project and then one of them gets another duty or leaves the company... - 16 Sep 2009 2:56 AM - Replies - 0 - Views - 754 I’ve got a question concerning licensing. When I now buy „Ext GWT 2.X Commercial Licenses” do I then also have „Ext GWT 1.X Commercial Licenses”, a license for both – current and old version? ... - 25 Aug 2009 12:11 AM - Replies - 0 - Views - 1,610 Hi, I am using GXT 1.2.4 and I have added a TreeDragSource to my TreeBinder. All in all, my dnd works pretty well, but in IE (or in hosted mode on Windows), it takes approximately 4 seconds... Results 1 to 10 of 10
http://www.sencha.com/forum/search.php?s=16c628c0e4d26c47f0f1a9e8da6e5658&searchid=7094163
CC-MAIN-2014-35
refinedweb
420
83.96
This article needs a technical review. How you can help. « Gecko Plugin API Reference « Browser Side Plug-in API Summary Lets a plug-in display a message on the browser's status line. Syntax #include <npapi.h> void NPN_Status(NPP instance, const char* message); Parameters The function has the following parameters: instance - Pointer to the current plug-in instance. - Pointer the buffer that contains the status message string to display. Description You can use this function to make your plug-in display status information in the browser window, in the same place the browser does. If your plug-in has a button or other object that acts as a link when clicked, you can call NPN_Status() to display a description or URL when the user moves the cursor over it. The browser always displays the last status line message it receives, regardless of the message source. Your message is always displayed, but you have no control over how long it stays in the status line before another message replaces it.
https://developer.mozilla.org/en-US/Add-ons/Plugins/Reference/NPN_Status
CC-MAIN-2016-30
refinedweb
170
63.49
Hi, If you create a project-level python library with the same name as a global-level python library, the global-level will be used. Hence it is best to have different names for python files and/or directory structure at project-level and global-level. Since you can have a directory structure in these libraries, you can define your own submodule structure to customize the name resolution. For instance, you can create a directory named "global_lib" inside the global python-lib directory. You could then advise users to put all global-level library files inside the former directory. Then from a Python notebook inside a project, they would reference the global module with: from global_lib.foo import bar Cheers, Alex
https://community.dataiku.com/t5/Using-Dataiku-DSS/Shared-libraries-in-recipes-and-notebooks/m-p/2421/shared-libraries-in-recipes-and-notebooks
CC-MAIN-2020-24
refinedweb
121
55.24
Carriage Return -vs- Line Feed Every now and then, I end up having a text parsing issue that simply comes down to carriage returns versus line feeds. For instance, with Twitter’s streaming API, you can receive multiple responses that all form a single JSON entity. You can realize this situation because the end of an entity will have a carriage return, while individual chunks before the end will only have line feed (new line) terminators. What’s really a bit messed up is that Windows is a big fan of CRLF (‘\r\n’), while most of Unix prefers LF (‘\n’) for line terminators. Apparently, Apple has a thing for sometimes using single CR (‘\r’) because it likes to be special. This all started when computers were supposed to mimic typewriters. At the end of a line, you needed to do two things at once: (1) Return the character carriage to the left so you could type more and (2) advance the line feed so you wouldn’t simply write over what you just wrote. Recognizing CRLF -vs- LF Both the carriage return (CR) and line feed (LF) are represented by non-printable characters. Your terminal or text editor simply knows how to interpret them. When you tell a script to write ‘\n’ for a line feed, you’re actually referencing the non-printable ASCII character 0x0A (decimal 10). When you write ‘\r’, you’re referencing 0x0D (decimal 12). But those characters don’t actually print. They only instruct a terminal or text editor to display the text around the characters in specific ways. So, how do you recognize them? The Linux ‘file’ command will tell you what sort of line terminators a file has, so that’s pretty quick. Here’s an example: $ file my_file_created_on_Windows.txt my_file_created_on_Windows.txt: ASCII text, with very long lines, with CRLF line terminators $ file my_file_created_on_Linux my_file_created_on_Linux: ASCII text, with very long lines If the file uses only LF terminators, this is considered the default and you won’t be informed. Removing CR Terminators You have several options for getting rid of those ‘\r’ CR characters in text. One option is to simply ‘tr’ the text in the terminal: $ tr -d '\r' < my_file_created_on_Windows.txt > my_new_file.txt Another option is to use a utility such as ‘dos2unix.’ Yet another option would be to use a more advanced text parsing language, such as Python, and replace the characters manually: import codecs f_p = codecs.open('my_file_created_on_Windows.txt','r','utf-8') g_p = codecs.open('my_new_file.txt','w','utf-8') for line in f_p: g_p.write(line.replace('\r','').replace('\n','')) f_p.close() g_p.close() A few notes on that Python code.. First, we use the codecs module to read text because it may contain non-ASCII characters such as Unicode. In this case, we’re reading the characters in UTF-8 encoding. Also, we replace both the CR and LF because Python will automatically write an LF at the end of the line, and we don’t want two LFs. 2 Comments Of course it is actually decimal 13, in case anyone cares. It’s going to be finish of mine day, however before ending I am reading this fantastic paragraph to improve my know-how. my weblog
http://code.jasonbhill.com/linux/line-terminators-carriage-returns-versus-line-feeds/
CC-MAIN-2017-51
refinedweb
539
62.58
Code formatter (notepad++ 64) How reformat code in notepead++ 64, like this: #include <iostream> #include "sources/config.h" #include <memory> using std::cout; using std::endl; using std::shared_ptr; int main() { int SIZE = 5; std::cin >> SIZE; shared_ptr<int[]> ptr(new int[SIZE]{1 , 34, 65, 23, 2}); for (int i = 0; i < SIZE; ++i) { ptr[i] = rand() % 10; cout << ptr[i] << endl; }} - Ekopalypse last edited by by using plugins like editor config or code alignment … welcome to the notepad++ community, @Andrey-Ws on 32 bit notepad++ one of the best plugins to reformat c++ code would be textfx, which is available at the built in plugins admin (notepad++ 7.6.x). the menu would be textfx > textfx edit > reindent c++ codeas seen at the screencast below. unfortunately the textfx plugin is not available for your notepad++ 64 bit, so you would have to install and use notepad++ 7.6.4 32 bit from here: note: there is an experimental version of textfx for x64, but currently exactly the c++ reindent feature is not working on that. here’s the link, if you want to play around with it: Thanks, but TextFX not so good formatted like in clion (on video)… ps. what soft u use for gif? - Alan Kilborn last edited by Alan Kilborn Ooooooh, progress bar! Nice. :) Ooooooh, progress bar! Nice. :) ps: i’ve posted the optimised settings for the progress bar here (just in case you haven’t seen them yet): - Alan Kilborn last edited by Seen and duly noted. Nice job figuring it out. Another nice plugin, but don’t format empty spaces between variables, etc… TextFX can format empty spaces ? TextFX can format empty spaces ? the best thing is, if you test everything yourself, by downloading the portable notepad++ 7.6.4. 32 bit from here: (the portable version will work completely isolated from your installed version and is perfect for any testing. any settings or plugin installation you do at the portable version, will not modify anything at your installed version. that’s why many of us use this version for testing) extract npp.7.6.4.bin.zip to your desktop. start it by double clicking on notepad++.exe inside the npp.7.6.4.bin folder. use the built in plugins admin to download textfx, or any other available plugins you would like to try. happy testing.
https://community.notepad-plus-plus.org/topic/17336/code-formatter-notepad-64/4
CC-MAIN-2019-51
refinedweb
395
70.94
In our wavetable series, we discussed what size our wavetables needed to be in order to give us an appropriate number of harmonics. But since we interpolated between adjacent table entries, the table size also dictates the signal to noise ratio of playback. A bigger (and therefore more oversampled) table will give lower interpolation error—less noise. We use “signal to noise ratio”—SNR for short—as our metric for audio. SNR has a precise definition—it’s the RMS value of the signal divided by the RMS value of the noise, and we usually express the ratio in dB. We’ll confine this article to sine tables, because they are useful and the ear is relatively sensitive to the purity of a sine wave. We could derive the relationship of table size and SNR analytically, but this article is about measurement, and it’s easily extended to other types of waveforms and audio. Calculating SNR To calculate SNR, we need to know what part of the sampled audio is signal and what part is noise. Since we’re generating the audio, it’s pretty easy to know each. For example, if we interpolate our audio from a sine table, the signal part is the best precision sine calculations we can make, and the noise is that minus the wavetable-interpolated version. RMS is root-mean-squared, or taking the square roots of all the samples, producing the average, then squaring that value. We do that for both the signal and the noise, sample by sample, and divide the two—and convert to dB. The greatest error between the samples will be somewhere in the middle. Picking halfway for the sine is a good guess, but we can easily take more measurements and see. It ends up that the table size can be relative small for an excellent SNR with linear interpolation. This shouldn’t be surprising, since a sine wave is smooth and therefore the error of drawing a line between two points gets small quickly with table size. A 512 sample table is ample for direct use in audio. It yields a 97 dB SNR. While some might think that’s fine for 16-bit audio but not so impressive for 24 bit, a closer look reveals just how good that SNR is. Keep in mind, this is a ratio of signal to noise. While the noise floor is -97 dB compared with the signal, that’s not the same as saying we have a noise floor of -97 dB. The noise floor is -97 dB when the signal is 0 dB (actually, this is RMS, so a full-code sine wave is -3 dB and the noise is -100 dB). But people don’t record and listen to sine waves at the loudest possible volume. When the signal is -30 dB, the noise floor is -127 dB. When the signal is disabled, the noise floor is non-existent. However, if that’s still not good enough for you, every doubling of the table size yields a 20 dB improvement. Code Here’s a simple C++ example that calculates the SNR of a sine table. Set the tableSize variable to check different table sizes (typically a power of 2, but not enforced). The span variable is the number of measurements from one table entry to the next. You can copy and paste, and execute, this code in an online compiler (search for “execute c++ online” for many options). #include <iostream> #include <cmath> #if !defined M_PI const double M_PI = 3.14159265358979323846; #endif using namespace std; int main(void) { const long tableSize = 512; const long span = 4; const long len = tableSize * span; double sigPower = 0; double errPower = 0; for (long idx = 0; idx < len; idx++) { long idxMod = fmod(idx, span); double sig = sin((double)idx / len * 2 * M_PI); double sin0, sin1; if (!idxMod) { sin0 = sig; sin1 = sin((double)(idx + span) / len * 2 * M_PI); } double err = (sin1 - sin0) * idxMod / span + sin0 - sig; sigPower += sig * sig; errPower += err * err; } sigPower = sqrt(sigPower / len); errPower = sqrt(errPower / len); cout << "Table size: " << tableSize << endl; cout << "Signal: " << 20 * log10(sigPower) << " dB RMS" << endl; cout << "Noise: " << 20 * log10(errPower) << " dB RMS" << endl; cout << "SNR: " << 20 * log10(sigPower / errPower) << " dB RMS" << endl; } Quantifying the benefit of interpolation This is a good opportunity to explore what linear interpolation buys us. Just change the error calculation line to “double err = sin0 – sig;”, and set span to a larger number, like 32, to get more readings between samples. Without linear interpolation, the SNR of a 512-sample table is about 43 dB, down from 97 dB, and we gain only 6 dB per table doubling. You can extend this comparison to other interpolation methods, but it’s clear that linear interpolation is sufficient for a sine table. Extending to other waveforms OK, how about other waveforms? A sawtooth wave is not as smooth as a sine, so as you might expect, it will take a larger table to yield high SNR number. Looking at it another way, the sawtooth is made up of a sine fundamental. The next harmonic is at half the amplitude, which alone would contribute half the signal and half the noise, but it’s also double the frequency—the equivalent of half the sine table size and therefore 20 dB worse than the fundamental is taken alone. It’s a little more complicated than just summing up the errors of the component sines, though, because positive and negative errors can cancel. But the measurement technique is basically the same as with the sine example. The signal would be a high-resolution bandlimited sawtooth (not a naive sawtooth), and noise would be the difference between that and the interpolated values from your bandlimited sawtooth table. Left to you as an exercise, but you may be surprised at the poor numbers of a 2048 or 4096 sample table in the low octaves (where the is no oversampling). But again, the noise only occurs when you have signal, particularly when you have a bright waveform, and remains that far below it at any amplitude. It’s still hard to hear the noise through the signal! Checking the SNR of wavetable generated by our wavetable oscillator code is a straightforward extension of the sine table code. For a wavetable of size 2048 and a given number of harmonics, for instance, create a table of size 2048 times span. Then subtract each entry of the wavetable, our “signal”, from the corresponding interpolated value for the “noise”. For instance, if tableSize is 2048 and span is 8, create a table of 16384 samples. For each signal sample n, from 0 to 16383, compare it with the linearly interpolated value between span points (compare samples 0-7 with the corresponding linear interpolation of samples 0 and 8, etc., using modulo or counters). It’s more code than I want to put up in this article, especially if I want to give a lot of options or waves and interpolations, but it’s easy. You might want to make a class that lets you specify a waveform, including number of harmonics and wavetable size, which creates the waveform. Create a function to do the linear interpolation (“lerp”) and possibly others (make it a class in that case); input the wavetable and span, output the computed signal and noise numbers. Then main simply makes the call to build the waveform, and another call to analyze it, and displays the results.
https://www.earlevel.com/main/2018/09/22/wavetable-signal-to-noise-ratio/
CC-MAIN-2020-45
refinedweb
1,245
58.52
Recent: Archives: How can we debug method calls that are not part of our own source code, say a call to JButton.setEnabled()? Java provides us with anonymous inner classes, which come in quite handy for this problem. Usually, when we derive a class, we can override existing methods by providing a new one: public class MyButton extends JButton { public void setVisible( boolean visible ) { // Rolling our own visibility } } After instantiating buttons of type MyButton, any call to setVisible() will be handled by the code above. The problem is we do not want to declare a whole new class just to override one method, especially when the number of instantiations is limited. Anonymous inner classes let us override methods on the fly at the time of instantiation. If we just want to roll our own visibility logic in one specific JButton, we just write the method as we declare the button: JButton myButton = new JButton() { public void setVisible( boolean visible ) { // Rolling our own visibility } }; What happened here? The code between the curly braces declares the method setVisible() and overrides the one from JButton, but only for myButton. We have not altered the JButton class, we have not declared a new class, we have just given one special JButton its own visibility logic. In object-oriented terminology, myButton is an object of an unnamed, hence anonymous, class derived from JButton. When is overriding a method and creating an anonymous class on the fly useful? If you code with Swing, you have seen and coded such a mechanism before when you added an event listener, say an ActionListener, to a GUI element. Now, imagine we have a big class with a bunch of buttons, where one button magically appears and disappears. We want to know why this problem occurs. Use the code above and set a breakpoint in the body of the setVisible method. Then, as we run our program, the breakpoint will stop us just at the right place. With a look at the stack trace, we find the culprit that called setVisible() unexpectedly and be able fix the problem. Anonymous inner classes prove helpful for debugging those classes where the source code is unavailable. Even when source code is available, setting a breakpoint in heavily used methods, such as setVisible(), might be cumbersome because we'll run into it for every instance of the class that implements setVisible(). Anonymous inner classes allow surgical debugging for one specific instance. Archived Discussions (Read only)
http://www.javaworld.com/javaworld/jw-01-2006/jw-0102-debug.html
crawl-002
refinedweb
411
59.23
dup, dup2, dup3 - duplicate a file descriptor Synopsis Description Errors Versions Notes Colophon #include <unistd.h> int dup(int oldfd); int dup2(int oldfd, int newfd); #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <fcntl.h>/*ObtainO_*constantdefinitions*/ #include <unistd.h> int dup3(int oldfd, int newfd, int flags); These system calls create a copy of the file descriptor oldfd.: On success, these system calls return the new descriptor. On error, -1 is returned, and errno is set appropriately. dup3() was added to Linux in version 2.6.27; glibc support is available starting with version 2.9. dup(), dup2(): SVr4, 4.3BSD, POSIX.1-2001. dup3() is Linux-specific.. close(2), fcntl(2), open(2) This page is part of release 3.44 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.sgvulcan.com/dup.2.php
CC-MAIN-2017-13
refinedweb
142
70.5
Sometimes, you have a small bit of data, may something like a GUID (for which there are many possible solutions), that you may have to store in a plain-text file, nothing crucial, not sensitive, but that you don’t really want your users to poke with, even if they really mean to. In such cases, you could use encryption, but it may be that mild obfuscation is quite sufficient and dissuasive. So, if you don’t really want strong encryption, what can you do to provide a machine-efficient encryptionnette? OK, let me repeat this one more time: the premise is that we do not need top-notch encryption, just a way to keep the user from messing with a value stored in a plain-text file. Of course, if you’re doing open-source, he will be able to do so more easily, but the point is that you want to make sure that it’s kind of not really worth the trouble to mess with that value. So let’s say that your GUID is built from the machine’s first MAC address and a strong check-sum, something like a CRC, yielding 64 bits strings: 16 for the check-sum, and 48 for the MAC Address. So what are the easily invertible operations one can apply to a 64-bits number to yield an (apparently) uncorrelated number? We can try to multiply by a constant such that . In other words, find such it is its own inverse modulo . Typically, for machine-efficiency reasons, but can be any value larger than 1. For some , only the only solutions are , for others, you’ll have a couple more solutions. If , then is a solution. For , 0x7fffffffffffffff and 0x8000000000000001 are solutions. Interestingly enough, these multipliers seem to randomize the input quite nicely. For example, using and , we get: …which looks randomizing enough. The inverse is to multiply by again, which makes it a symmetric operation. The integer multiplication is not that expensive on a modern processor, but it can be quite involved for a micro-controller class CPU (even if it’s capable of 32-bits arithmetic). * * * We can xor our data with a fixed random mask. Pick any 64-bits number using a pseudo-random number generator), not necessarily a strong one. Since the mask is fixed, there’s no point of having a very strong random number; it just has to be random enough so that when you xor it with your data, it looks more random than it used to. Of course, this is clearly not impervious to a known plain-text attack, it suffice to send a zeroed vector to retrieve the key. * * * We can use a bit blender. A bit blender, at least how I defined it in a previous post, is an operation that move bits around in a lossless fashion—that is, the operation is reversible. That is, it applies an arbitrary permutation of the input bits: it can reverse the vector, apply a rotation, move blocks around, etc. For the application we are considering here, a blender that disperses the bits randomly (but reversibly) is preferable. One simple operation that does that rather well is the perfect shuffle—an operation known to card-game players as the Faro Shuffle. The following diagram shows the shallowest network that produces the perfect shuffle for 8 elements: A simple Python implementation of the perfect shuffle would look like: def perfect_shuffle(a): """perfectly shuffles the supplied list, throws AssertionError if list has odd length.""" l=len(a) if l % 2: raise AssertionError else: h=l/2; # half-length # variant proposed by Kirk McDonald # (from the #python channel on Freenode) return [item for pair in zip(a[:h],a[h:]) for item in pair] def perfect_unshuffle(a): """perfectly unshuffles the supplied list, if previously perfectly shuffled.""" return a[::2]+a[1::2] It will take a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and yield [0, 5, 1, 6, 2, 7, 3, 8, 4, 9]. Note that the shuffled list contains all of the original list’s items. The transformation is also reversible, and we can recover [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] from [0, 5, 1, 6, 2, 7, 3, 8, 4, 9]. A C/C++ implementation is a bit more involved. Well, a whole lot. uint32_t perfect_shuffle(uint32_t x) { x=(x & UINT32_C(0xff0000ff)) | ((x & UINT32_C(0x00ff0000)) >> 8) | ((x & UINT32_C(0x0000ff00)) << 8); x=(x & UINT32_C(0xf00ff00f)) | ((x & UINT32_C(0x0f000f00)) >> 4) | ((x & UINT32_C(0x00f000f0)) << 4); x=(x & UINT32_C(0xc3c3c3c3)) | ((x & UINT32_C(0x30303030)) >> 2) | ((x & UINT32_C(0x0c0c0c0c)) << 2); x=(x & UINT32_C(0x99999999)) | ((x & UINT32_C(0x44444444)) >> 1) | ((x & UINT32_C(0x22222222)) << 1); return x; } uint32_t perfect_unshuffle(uint32_t x) { x=(x & UINT32_C(0x99999999)) | ((x & UINT32_C(0x44444444)) >> 1) | ((x & UINT32_C(0x22222222)) << 1); x=(x & UINT32_C(0xc3c3c3c3)) | ((x & UINT32_C(0x30303030)) >> 2) | ((x & UINT32_C(0x0c0c0c0c)) << 2); x=(x & UINT32_C(0xf00ff00f)) | ((x & UINT32_C(0x0f000f00)) >> 4) | ((x & UINT32_C(0x00f000f0)) << 4); x=(x & UINT32_C(0xff0000ff)) | ((x & UINT32_C(0x00ff0000)) >> 8) | ((x & UINT32_C(0x0000ff00)) << 8 ); return x; } uint64_t perfect_shuffle(uint64_t x) { uint16_t *y=(uint16_t*)&x; std::swap(y[1],y[2]); return ((uint64_t)perfect_shuffle((uint32_t)(x >> 32)) << 32) | perfect_shuffle((uint32_t)x); } uint64_t perfect_unshuffle(uint64_t x) { x=((uint64_t)perfect_unshuffle((uint32_t)(x >> 32)) << 32) | perfect_unshuffle((uint32_t)x); uint16_t *y=(uint16_t*)&x; std::swap(y[1],y[2]); return x; } How this works is explained here in great detail. The point is that the perfect shuffle, like when you’re shuffling cards, disperses bits around quite a bit. But reversibly so. * * * So what if we were to combine all these operations? that would be the best order? Since they are each reversible, any order could be applied: xor-mul-shuffle, or mul-shuffle-xor, or mul-xor-shuffle, or… The mul-xor-shuffle test code would look something like: // reversibility test std::cout << std::hex; const uint64_t mult=UINT64_C(0x7fffffffffffffff); uint64_t mask=((uint64_t)std::rand() << 32) | std::rand(); std::cout << "mask=" << mask << std::endl; for (int i=0; i<10000000; i++) { uint64_t u=((uint64_t)std::rand() << 32) | std::rand(); // sure! uint64_t obfuscated_u=perfect_shuffle((u*mult)^mask); uint64_t unobfuscated_u=(perfect_unshuffle(obfuscated_u)^mask)*mult; if (unobfuscated_u != u) { std::cout << "oh noes!!!" << u << " " << unobfuscated_u << std::endl; return 1; } } With a mask of 1888600f3e744fe9 (generated randomly), we get: OK, listing a list of numbers that kind of looks like random is a proof by volume, but you can experiment by yourselves. * * * I am sure you have thought, reading this entry, of many more ways of mildly obfuscating a n-bit word, and that’s fine. The main point is the operation must be randomizing but reversible. If it’s not reversible, it’s merely a hash, and that’s not what we wanted. Can you think of other reversible randomizing operations? […] Mild Obfuscation, I […] Hello Steven, your first table (x -> a*x mod m) seems to be using m=2^32, contrary to your statement that m=2^32-1. Great post! You’re absolutely right! (I was thinking & 0xffffffff). I will correct this. […] discussed moving bits around before. The first function (that I called “blender”) moves bits around following this […]
https://hbfs.wordpress.com/2011/11/08/mild-obfuscation/
CC-MAIN-2017-13
refinedweb
1,184
59.74